text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Lazarus - why doesn't this work with ShowModal? I have two forms in Lazarus. one is frmMain and the other is frmSub1. both have a text box.
The following code works. i.e., on clicking a button on frmMain, the value
procedure TfrmMain.cmdShowClick(Sender: TObject);
begin
frmSub1.Show ;
frmSub1.txtAns.text := txtMark.Text;
end;
But when I replace .Show with .ShowModal, it shows the form but frmSub1.txtAns is blank.
Any idea why this is so?
A: Thats because ShowModal is blocking call, ie the line frmSub1.txtAns.text := txtMark.Text; wont execute until it returns. You have to switch the order of statements, following should work as you expect:
procedure TfrmMain.cmdShowClick(Sender: TObject);
begin
frmSub1.txtAns.text := txtMark.Text;
frmSub1.ShowModal;
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: type=dict in argparse.add_argument() I'm trying to set up a dictionary as optional argument (using argparse); the following line is what I have so far:
parser.add_argument('-i','--image', type=dict, help='Generate an image map from the input file (syntax: {\'name\': <name>, \'voids\': \'#08080808\', \'0\': \'#00ff00ff\', \'100%%\': \'#ff00ff00\'}).')
But running the script:
$ ./script.py -i {'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}
script.py: error: argument -i/--image: invalid dict value: '{name:'
Even though, inside the interpreter,
>>> a={'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}
works just fine.
So how should I pass the argument instead?
Thanks in advance.
A: I’ll bet your shell is messing with the braces, since curly braces are the syntax used for brace expansion features in many shells (see here).
Passing in a complex container such as a dictionary, requiring the user to know Python syntax, seems a bad design choice in a command line interface. Instead, I’d recommend just passing options in one-by-one in the CLI within an argument group, and then build the dict programmatically from the parsed group.
A: Necroing this: json.loads works here, too. It doesn't seem too dirty.
import json
import argparse
test = '{"name": "img.png","voids": "#00ff00ff","0": "#ff00ff00","100%": "#f80654ff"}'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=json.loads)
args = parser.parse_args(['-i', test])
print(args.input)
Returns:
{u'0': u'#ff00ff00', u'100%': u'#f80654ff', u'voids': u'#00ff00ff', u'name': u'img.png'}
A: Combining the type= piece from @Edd and the ast.literal_eval piece from @Bradley yields the most direct solution, IMO. It allows direct retrieval of the argval and even takes a (quoted) default value for the dict:
Code snippet
parser.add_argument('--params', '--p', help='dict of params ', type=ast.literal_eval, default="{'name': 'adam'}")
args = parser.parse_args()
Running the Code
python test.py --p "{'town': 'union'}"
note the quotes on the dict value. This quoting works on Windows and Linux (tested with [t]csh).
Retrieving the Argval
dict=args.params
A: You can definitely get in something that looks like a dictionary literal into the argument parser, but you've got to quote it so when the shell parses your command line, it comes in as
*
*a single argument instead of many (the space character is the normal argument delimiter)
*properly quoted (the shell removes quotes during parsing, because it's using them for grouping)
So something like this can get the text you wanted into your program:
python MYSCRIPT.py -i "{\"name\": \"img.png\", \"voids\": \"#00ff00ff\",\"0\": \"#ff00ff00\",\"100%\": \"#f80654ff\"}"
However, this string is not a valid argument to the dict constructor; instead, it's a valid python code snippet. You could tell your argument parser that the "type" of this argument is eval, and that will work:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i','--image', type=eval, help='Generate an image map...')
args = parser.parse_args()
print args
and calling it:
% python MYSCRIPT.py -i "{\"name\": \"img.png\", \"voids\": \"#00ff00ff\",\"0\": \"#ff00ff00\",\"100%\": \"#f80654ff\"}"
Namespace(image={'0': '#ff00ff00', '100%': '#f80654ff', 'voids': '#00ff00ff', 'name': 'img.png'})
But this is not safe; the input could be anything, and you're evaluating arbitrary code. It would be equally unwieldy, but the following would be much safer:
import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('-i','--image', type=ast.literal_eval, help='Generate an image map...')
args = parser.parse_args()
print args
This also works, but is MUCH more restrictive on what it will allow to be eval'd.
Still, it's very unwieldy to have the user type out something, properly quoted, that looks like a python dictionary on the command line. And, you'd have to do some checking after the fact to make sure they passed in a dictionary instead of something else eval-able, and had the right keys in it. Much easier to use if:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--image-name", required=True)
parser.add_argument("--void-color", required=True)
parser.add_argument("--zero-color", required=True)
parser.add_argument("--full-color", required=True)
args = parser.parse_args()
image = {
"name": args.image_name,
"voids": args.void_color,
"0%": args.zero_color,
"100%": args.full_color
}
print image
For:
% python MYSCRIPT.py --image-name img.png --void-color \#00ff00ff --zero-color \#ff00ff00 --full-color \#f80654ff
{'100%': '#f80654ff', 'voids': '#00ff00ff', 'name': 'img.png', '0%': '#ff00ff00'}
A: One of the simplest ways I've found is to parse the dictionary as a list, and then convert that to a dictionary. For example using Python3:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--image', type=str, nargs='+')
args = parser.parse_args()
if args.image is not None:
i = iter(args.image)
args.image = dict(zip(i, i))
print(args)
then you can type on the command line something like:
./script.py -i name img.png voids '#00ff00ff' 0 '#ff00ff00' '100%' '#f80654ff'
to get the desired result:
Namespace(image={'name': 'img.png', '0': '#ff00ff00', 'voids': '#00ff00ff', '100%': '#f80654ff'})
A: For completeness, and similarly to json.loads, you could use yaml.load (available from PyYAML in PyPI). This has the advantage over json in that there is no need to quote individual keys and values on the command line unless you are trying to, say, force integers into strings or otherwise overcome yaml conversion semantics. But obviously the whole string will need quoting as it contains spaces!
>>> import argparse
>>> import yaml
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-fna', '--filename-arguments', type=yaml.load)
>>> data = "{location: warehouse A, site: Gloucester Business Village}"
>>> ans = parser.parse_args(['-fna', data])
>>> print ans.filename_arguments['site']
Gloucester Business Village
Although admittedly in the question given, many of the keys and values would have to be quoted or rephrased to prevent yaml from barfing. Using the following data seems to work quite nicely, if you need numeric rather than string values:
>>> parser.add_argument('-i', '--image', type=yaml.load)
>>> data = "{name: img.png, voids: 0x00ff00ff, '0%': 0xff00ff00, '100%': 0xf80654ff}"
>>> ans = parser.parse_args(['-i', data])
>>> print ans.image
{'100%': 4161164543L, 'voids': 16711935, 'name': 'img.png', '0%': 4278255360L}
A: Using simple lambda parsing is quite flexible:
parser.add_argument(
'--fieldMap',
type=lambda x: {k:int(v) for k,v in (i.split(':') for i in x.split(','))},
help='comma-separated field:position pairs, e.g. Date:0,Amount:2,Payee:5,Memo:9'
)
A: General Advice: DO NOT USE eval.
If you really have to ...
"eval" is dangerous. Use it if you are sure no one will knowingly input malicious input. Even then there can be disadvantages. I have covered one bad example.
Using eval instead of json.loads has some advantages as well though. A dict doesn't really need to be a valid json. Hence, eval can be pretty lenient in accepting "dictionaries". We can take care of the "danger" part by making sure that final result is indeed a python dictionary.
import json
import argparse
tests = [
'{"name": "img.png","voids": "#00ff00ff","0": "#ff00ff00","100%": "#f80654ff"}',
'{"a": 1}',
"{'b':1}",
"{'$abc': '$123'}",
'{"a": "a" "b"}' # Bad dictionary but still accepted by eval
]
def eval_json(x):
dicti = eval(x)
assert isinstance(dicti, dict)
return dicti
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=eval_json)
for test in tests:
args = parser.parse_args(['-i', test])
print(args)
Output:
Namespace(input={'name': 'img.png', '0': '#ff00ff00', '100%': '#f80654ff', 'voids': '#00ff00ff'})
Namespace(input={'a': 1})
Namespace(input={'b': 1})
Namespace(input={'$abc': '$123'})
Namespace(input={'a': 'ab'})
A: A minimal example to pass arguments as a dictionary from the command line:
# file.py
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("-par", "--parameters",
required=False,
default=None,
type=json.loads
)
args = parser.parse_args()
print(args.parameters)
and in the terminal you can pass your arguments as a dictionary using a string format:
python file.py --parameters '{"a":1}'
A: You could try:
$ ./script.py -i "{'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}"
I haven't tested this, on my phone right now.
Edit: BTW I agree with @wim, I think having each kv of the dict as an argument would be nicer for the user.
A: Here is a another solution since I had to do something similar myself. I use the ast module to convert the dictionary, which is input to the terminal as a string, to a dict. It is very simple.
Code snippet
Say the following is called test.py:
import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('--params', '--p', help='dict of params ',type=str)
options = parser.parse_args()
my_dict = options.params
my_dict = ast.literal_eval(my_dict)
print(my_dict)
for k in my_dict:
print(type(my_dict[k]))
print(k,my_dict[k])
Then in the terminal/cmd line, you would write:
Running the code
python test.py --p '{"name": "Adam", "lr": 0.001, "betas": (0.9, 0.999)}'
Output
{'name': 'Adam', 'lr': 0.001, 'betas': (0.9, 0.999)}
<class 'str'>
name Adam
<class 'float'>
lr 0.001
<class 'tuple'>
betas (0.9, 0.999)
A: TLDR Solution:
The simplest and quickest solution is as below:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-par", "--parameters",
default={},
type=str)
args = parser.parse_args()
In the parser.add_argument function:
*
*Use a dictionary object for default object
*str as the type
Then args.parameters will automatically be converted to a dictionary without any need for ast.literal.eval or json.loads.
Motivation:
The methods posted by @Galuoises and @frankeye, appear to not work when the default is set as a json encoded dictionary such as below.
parser.add_argument("-par", "--parameters",
required=False, default="{\"k1\":v1, \"k2\":v2}",
type=json.loads)
This is because
A: The following works just fine:
parser = argparse.ArgumentParser()
parser.add_argument("-par", "--parameters",
required=False, default={"k1a":"v1a","k2a":"v2a"},
type=json.loads)
args = parser.parse_args()
print(str(parameters))
result:
{'k1a': 'v1a', 'k2a': 'v2a'}
For default value, the type should be dict since json.loads returns a dictionary, not a string, the default object should be given as a dictionary.
import argparse,json,sys
sys.argv.extend(['-par','{"k1b":"v1b","k2b":"v2b"}'])
parser = argparse.ArgumentParser()
parser.add_argument("-par", "--parameters",
required=False, default={"k1":"v1","k2":"v2"},
type=json.loads)
args = parser.parse_args()
print(str(args.parameters))
result:
{'k1b': 'v1b', 'k2b': 'v2b'}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: sqlite3 inside C++ (stored procedure or complex sql with TABLE and its INDEX) I'm trying sqlite3 in my C++ app. I have done:
*
*sqlite3 my.db
*sqlite> CREATE TABLE links(UrlAsID VARCHAR(255) PRIMARY KEY, Owner VARCHAR(255), ......, CreationTime INTEGER);
*sqlite> CREATE INDEX linkIDs ON links(UrlAsID, CreationTime ASC);
Then I opened a connection from the C++ code to the database.
From within the code I have an Url object. Now I have todo:
// check if url is in index (and in table as well)
string urlID = sqlite3_exec("SELECT UrlAsID FROM linkIDs WHERE UrlAsID = " + Url.id + ";");
if (urlID.empty()) {
sqlite3_exec("INSERT INTO links VALUES (" + Url.properties + ");");
sqlite3_exec("INSERT INTO linkIDs VALUES (" + Url.id + "," + int(Url.creationTime) + ");");
} else {
sqlite3_exec("UPDATE links SET (CreationTime = " + int(Url.creationTime) + "," + ... + ") WHERE UrlAsID = " + Url.id + ";");
sqlite3_exec("UPDATE linkIDs SET (CreationTime = " + int(Url.creationTime) + ") WHERE UrlAsID = " + Url.id + ";");
}
I thought to create a stored procedure or to use a complex SQL statement to encapsulate the above logic. Could you please provide me with more precise code to accomplish this.
Thank you in advance!
A: Your statements should be wrapped in a transaction for both safety and speed. Furthermore, you should use prepared statements with parameters, again for both safety and speed (different sort of safety, but even so). And you should use INSERT OR REPLACE with a suitable COALESCE. All of this is irrespective of which language you're embedding within, but the links are to relevant syntax.
A: SQLite doesn't support stored procedures: http://www.sqlite.org/whentouse.html
If the SQL code is complex I would try to put in a .sql file, then load into a variable and execute.
A: SQLite does not support stored procedures. The most you can do is use prepared statements. You should also use the SQLite binding methods to set parameters, instead of string concatenation. Read the introduction here: http://sqlite.org/cintro.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does JPA only refer to RDBMS JPA is all about data persistence; is data persistence only limited to RDBMS ? if not what are all the different persistence mechanisms (like Excel,File System,XML, NON RDMS etc ..) we can achieve with JPA specifications ?
A: JPA is designed for RDBMS, and looking at the API and metadata you can see that this is the case. It is possible to apply JPA to other datastores, but approximations have to be made for some concepts, particularly when querying. On the other hand the JDO API was designed for all datastores, and such approximations don't have to be made.
DataNucleus was the first implementation to provide JPA across a range of other datastores (Excel, ODBMS, ODF, LDAP, BigTable, HBase, MongoDB, etc), and has provided these for the last 2+ years. It also provides JDO access for the same datastores.
A:
JPA is all about data persistence; is data persistence only limited to RDBMS ?
Yes.
JPA is a framework that provides an object / relational mapping. Relational is the "R" in RDBMS.
A project (Hibernate OGM) started recently to allow Hibernate to interface with NoSQL-type databases. The goal of the project is "to provide a common interface for NoSQL datastores using JPA constructs". (That is not the same as implementing JPA for NoSQL.) The article linked below describes the project as "nascent"; i.e. only recently started, don't hold your breath waiting.
References:
*
*Java Persistence API - Wikipedia.
*Hibernate Object Mapping for NoSQL Data Stores
A: JPA only defines standard mappings for relational data. But many JPA providers support non-relational data as well. Normally it is the runtime side of the API that is supported, mapping is normally done through non-standard meta-data.
Also there are many JDBC providers that support the JDBC API and SQL to non-relational data and data sources, which will work with any JPA provider. This is typically the best solution for accessing non-relational data.
There is no standard to mapping to non-relational data, as non-relational data encompasses a broad range of data formats, and are by definition non-standard. The Java Connector Architecture (JCA) standard is Java's standard for accessing non-relational data. However most non-relational adapters provide JDBC drivers instead of JCA drivers as JDBC usage is more widespread.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Databases#EIS.2C_and_Non-relational_Data_Sources
EclipseLink has support for several persistence services including:
*
*JPA
*EIS (Enterprise Information Systems) non-relational data sources through JCA connectors
*JAXB (mapping XML data)
*DBWS (database web-services)
*SDO (Service Data Objects)
A:
The Java Persistence API deals with the way relational data is mapped
to Java objects ("persistent entities"), the way that these objects
are stored in a relational database so that they can be accessed at a
later time, and the continued existence of an entity's state even
after the application that uses it ends. In addition to simplifying
the entity persistence model, the Java Persistence API standardizes
object-relational mapping.
The qoutes are taken fro here:
http://www.oracle.com/technetwork/articles/javaee/jpa-137156.html
Shortly, yes. The JPA is about mapping of java objects to relational DB.
Is there a way to "abuse" the API and create implementation that maps objects to other targets like NOSQL? I believe it is possible but not very simple. How for example will you implement support of relational annotations like @OneToMany?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Priority between thread messages? Though I am quoting this in context of Borland C++ application, but the question is both specific for Borland as well as generic in nature.
In a Borland C++ project, I observe that a user interaction with the GUI (say a menu item click) is taking less priority than a task delegated to the main thread using Synchronize(), even though the user interaction is happening a few milliseconds earlier. When the main thread is available, the delegated task is done first and then the action corresponding to the user interaction is performed. A worker thread delegates a task to main thread and waits for the task to complete using Synchronize(). So we can equate Synchronize() to SendMessage().
I believe that the user interaction queues up as a message in the message queue and same should be the case with the delegated task. But how does the task execute first? Is there any priority between messages?
A: Up to and including C++Builder 5, Synchronize() did indeed make a call to SendMessage(). But in C++Builder 6, Synchronize() was re-written to not use SendMessage() anymore (to support Linux under CLX). Requests are now placed in a FIFO queue, and the VCL periodically calls CheckSynchronize() to process the queue. Even though CLX is long dead, Synchronize() still uses the same FIFO queue (and it has been enhanced over the years).
Aside from that, in cases where SendMessage() is used, it does have higher priority. User interactions are posted messages to the main thread message queue (aka PostMessage()). Although SendMessage() goes directly to a window's wndproc, it is not called until the receiving window's owning thread performs message processing if sent by a different thread (which used to be the case with Synchronize()). Pending SendMessage() requests to the main thread message queue have higher priority than pending posted messages to the same queue, as there are other threads/processes being blocked until the pending SendMessage() requests are processed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: listview for a single row? I've got an application which displays a field that can have multiple entries but I only wish to show the first entry and then give the user the option to expand that to display all items. I was thinking of making this a listview but once it's expanded I want it to retain the expansion.
the text field in question is part of a viewpager not a view on it's own.
Anyone got any good ideas or advice?
Thanks, m
A: You could use ExpandableListView with single item group.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to auto linewrap comments in .NET? I'd like to have a single command to auto-linewrap the XML-style comments in .NET.
Example:
/// <summary>
/// This comment line should be
/// on one line, and other lines in this <summary> block should be wordwrapped.
/// </summary>
I wouldn't mind buying some of the commercial Visual Studio plugins, if they are capable of doing this.
A: Try the trial of ReSharper, it states it formats XML Doc Comments (Go Here and search for XML doc comments for more information) and tends to be very customisable.
If that doesn't work, the closest thing I could find was on CodeProject , it's intended for Visual Studio 2003; however is open source so you may be able to get it working without the expensive of a third party plugin.
A: I've written an addin for Visual Studio, AtomineerUtils Pro Documentation which will update and word-wrap both normal comments and documentation comments (in XML, Doxygen, Qt and JavaDoc formats). (It's not free, but it's very inexpensive and there's a 30 day free trial)
It tries to intelligently preserve important newlines - text such as indentation, bullet lists, blank lines or a double space at the end of a line (among other things) will all be used as hints to the wrapping engine to ensure that your formatting is not lost.
A: Add a <para /> in your comments
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to insert a row into table automatically? I have two tables (parent & child) in my database. How can I insert a new record into the parent table so that a record is automatically inserted into child table?
A: You can use (after insert) triggers for that, see MySQL manual for syntax.
A: Here's an example of using a trigger to insert a new child record with the just-generated parent auto-increment id.
mysql> create table ParentTable (id int auto_increment primary key);
mysql> create table ChildTable (id int auto_increment primary key,
parentId int, foreign key (parentId) references ParentTable(id));
mysql> CREATE TRIGGER MyTrigger AFTER INSERT ON ParentTable
-> FOR EACH ROW
-> INSERT INTO ChildTable (parentId) VALUES (NEW.id);
mysql> insert into ParentTable () values ();
Query OK, 1 row affected (0.02 sec)
mysql> select * from ChildTable;
+----+----------+
| id | parentId |
+----+----------+
| 1 | 1 |
+----+----------+
This is a trivial example, because the two tables don't have any other columns except for their primary keys and the foreign key.
But what if you want to insert other columns into the child table?
The trigger only has access to the NEW.* columns of the row it just inserted into the parent. It may also SELECT other existing data from elsewhere in the database. Or it could use hard-coded literal values.
There may also be defaults on the other columns in the child table, or else it may be okay for them to be NULL temporarily, until you can fill them in with subsequent UPDATE statements.
You have to accept that the trigger might not be able to give specific values for the relevant columns as it INSERTs to the child table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Syntax error when Insert to Access using OleDb I do not have a lot of experience in vb.net, but I am trying to use OleDB to insert a record with String,string,Yes/no(studentname, number, gender). However when I insert it , there's a exception raised stating that I have invalid syntax for the "insert into" query. I could not spot the error.
Test case:
txtName.Text = "asdasdasd"
txtPhone.Text = "123456789"
rGender.Checked = True
Here's the code:
cmd = New OleDbCommand()
With cmd
.Connection = cn
.CommandText = "INSERT INTO [Student] (StudentName, Number, Gender) VALUES(@Name,@Number,@Gender)"
.CommandType = CommandType.Text
.Parameters.AddWithValue("@Name", txtName.Text)
.Parameters.AddWithValue("@Number", txtPhone.Text)
.Parameters.AddWithValue("@Gender", rGender.Checked)
End With
A: Number is reserved word,
INSERT INTO [Student] ([StudentName], [Number], [Gender]) VALUES(@Name,@Number,@Gender)
A: Seems like the Problem with field name "Number", its a keyword in MSAccess - http://support.microsoft.com/kb/286335.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Vim visual selection delete/insert in Emacs I was trying to find a replacement of vim's visual mode which is extremely useful, say I would like to delete the first two characters on the below two lines
11 line1
22 line2
in vim, I enter into the visual mode and select the region I want to delete, and delete it. Moreover I also can add to the column after
11
22
like
11 added line1
22 added line2
wiht Shift+I after selecting the column in visual mode. Is there a way to do the same in emacs?
A: Sounds like Emacs' rectangle features. You kind have to visualize a rectangle in your head between the point and the mark.
C-x r k to kill rectangle
C-x r t to fill rectangle with text. You want a rectangle zero column wide to do your second request.
A: cua-mode provides exactly this sort of feature. You can turn it on with the following in your .emacs:
(setq cua-enable-cua-keys nil)
(cua-mode)
The first line is necessary to prevent cua-mode from replacing a bunch of standard keyboard shortcuts with Windows-style things (C-c for copy, C-x for cut etc).
Once you're in cua-mode, C-enter will turn on visual rectangles, which you can then expand with the movement keys (arrows, C-n, C-f etc) to cover the text you want to manipulate. While this is going on, hitting enter moves the cursor around the edges of the rectangle, and anything you type is inserted outside the rectangle on the same side as the cursor. The insertion matches the size of the rectangle, so if you want to add the same text to the beginning (or middle or end) of a bunch of lines at once, this is the fastest way to do it.
If you disabled the cua keybindings, then C-w will kill the contents of the rectangle.
It's kind of unfortunate that the rectangle bits of cua-mode aren't in their own mode, as lots of people who don't want the cua-mode bindings don't realize that the mode also has this very cool feature!
A: I think that the emacs rectangle feature would be a solution
A: It sounds like Vimpulse may be what you need:
http://www.emacswiki.org/emacs/vimpulse.el
Vimpulse emulates Vim's most popular features, like Visual mode
and text objects. Vimpulse is a set of modifications to Viper, the
standard library that emulates vi. Vimpulse is not a minor mode;
as soon as it is loaded, Viper will start working in a more
Vim-like way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Relation "OR" in relational databases The question is pretty trivial I guess. But nevertheless,
E.g., I have Entities: user (id, name), group (id, name), user_group (user_id, group_id) and gallery (id, name, owner_id).
Owner of the gallery could be user OR group.
What's the best solution for this in relational databases?
Thanks!
PS If anybody knows relational algebra and schema optimization. How will it look like?
I was thinking about Owner (id, user_id, group_id), but I don't have any idea how to show "OR" relation in terms of relational algebra.
A: The simplest solution would be a relation Owner(id, user_id, group_id) where either user_id or group_id can be set -- guard that with an appropriate constraint.
Collapsing Group and User into one table drags several consistency checks from the database into the application logic:
*
*A group could have not only users but other groups (recursion and/or infinit cylces ahead).
*If User and Group are used in some more places more adaptions might be necessary.
*Data consistence cannot be enforced by the database any more.
A: Combine owner and group into one table. Owner and group should only differ by the attributes they have in this table, or the presence / absence of rows in a relationtable joining this new table with itself ("is member of" ).
A: There is no technical difference between a user and a group (only a conceptual one).
Put them both into the same table (user) and flag a row's type (group or user) in a second field.
Use application logic to make sure that only a row of type group may "have children" in the user_group table.
A: Introduce a new entity OWNER and make it owner of the GROUP. Then make USER and GROUP categories of (i.e. "inherit" them from) OWNER.
Your ER model would look like this (only PK fields shown):
Theoretically, there are 3 major ways to implement a category in the physical database. All of them have pros and cons, but for your model, the solution 1 is probably the most appropriate:
*
*Use separate tables for OWNER, USER and GROUP and connect them via FOREIGN KEYs.
*
*In this scenario, you may or may not use the discriminator (i.e. type identifier) in OWNER.
*Put USER and GROUP in the separate tables, with OWNER's fields present in both.
*Put OWNER, USER and GROUP in the same table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring jdbc with aop transaction configuration not committing I am using Spring 3.0.6 in Tomcat 6 with JDK 1.6. I have configured Spring JDBC with declarative transaction using the Spring reference. I see following in the log for my delete query but after the execution the record does not get deleted. Any idea what is the reason?
Creating new transaction with name [com.accept.web.modules.personalization.UserPreferencesServiceImpl.delete]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [ProxyConnection[PooledConnection[oracle.jdbc.driver.T4CConnection@73bddb4e]]] for JDBC transaction
Bound value [org.springframework.jdbc.datasource.ConnectionHolder@3f6f1ea2] for key [org.apache.tomcat.jdbc.pool.DataSource@1123065c{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=oracle.jdbc.OracleDriver; maxActive=30; maxIdle=3; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=600000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=1800000; testWhileIdle=true; testOnConnect=false; password=accept; url=jdbc:oracle:thin:@bbhangale-pc:1521/bbhangale; username=accept; validationQuery=select name from usr_user where id=104; validationInterval=1200000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=true; removeAbandonedTimeout=360; logAbandoned=true; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; alternateUsernameAllowed=false; }] to thread [http-8001-1]
Initializing transaction synchronization
Getting transaction for [com.accept.web.modules.personalization.UserPreferencesServiceImpl.delete]
Executing prepared SQL update
Executing prepared SQL statement [SELECT "KEY", "VALUE" FROM config WHERE "KEY" IN (?) AND user_id = ?]
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@3f6f1ea2] for key [org.apache.tomcat.jdbc.pool.DataSource@1123065c{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=oracle.jdbc.OracleDriver; maxActive=30; maxIdle=3; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=600000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=1800000; testWhileIdle=true; testOnConnect=false; password=accept; url=jdbc:oracle:thin:@bbhangale-pc:1521/bbhangale; username=accept; validationQuery=select name from usr_user where id=104; validationInterval=1200000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=true; removeAbandonedTimeout=360; logAbandoned=true; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; alternateUsernameAllowed=false; }] bound to thread [http-8001-1]
Setting SQL statement parameter value: column index 1, parameter value [FILTER_rcaGrid], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [107], value class [java.lang.Integer], SQL type unknown
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@3f6f1ea2] for key [org.apache.tomcat.jdbc.pool.DataSource@1123065c{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=oracle.jdbc.OracleDriver; maxActive=30; maxIdle=3; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=600000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=1800000; testWhileIdle=true; testOnConnect=false; password=accept; url=jdbc:oracle:thin:@bbhangale-pc:1521/bbhangale; username=accept; validationQuery=select name from usr_user where id=104; validationInterval=1200000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=true; removeAbandonedTimeout=360; logAbandoned=true; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; alternateUsernameAllowed=false; }] bound to thread [http-8001-1]
SQL update affected 1 rows
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@3f6f1ea2] for key [org.apache.tomcat.jdbc.pool.DataSource@1123065c{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=oracle.jdbc.OracleDriver; maxActive=30; maxIdle=3; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=600000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=1800000; testWhileIdle=true; testOnConnect=false; password=accept; url=jdbc:oracle:thin:@bbhangale-pc:1521/bbhangale; username=accept; validationQuery=select name from usr_user where id=104; validationInterval=1200000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=true; removeAbandonedTimeout=360; logAbandoned=true; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; alternateUsernameAllowed=false; }] bound to thread [http-8001-1]
Completing transaction for [com.accept.web.modules.personalization.UserPreferencesServiceImpl.delete]
Triggering beforeCommit synchronization
Triggering beforeCompletion synchronization
Initiating transaction commit
Committing JDBC transaction on Connection [ProxyConnection[PooledConnection[oracle.jdbc.driver.T4CConnection@73bddb4e]]]
Triggering afterCommit synchronization
Triggering afterCompletion synchronization
Clearing transaction synchronization
Removed value [org.springframework.jdbc.datasource.ConnectionHolder@3f6f1ea2] for key [org.apache.tomcat.jdbc.pool.DataSource@1123065c{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=oracle.jdbc.OracleDriver; maxActive=30; maxIdle=3; minIdle=0; initialSize=0; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=600000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=1800000; testWhileIdle=true; testOnConnect=false; password=accept; url=jdbc:oracle:thin:@bbhangale-pc:1521/bbhangale; username=accept; validationQuery=select name from usr_user where id=104; validationInterval=1200000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=true; removeAbandonedTimeout=360; logAbandoned=true; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; alternateUsernameAllowed=false; }] from thread [http-8001-1]
Releasing JDBC Connection [ProxyConnection[PooledConnection[oracle.jdbc.driver.T4CConnection@73bddb4e]]] after transaction
Returning JDBC Connection to DataSource
A: All is working fine now. I forgot to change the query to a delete query. As you pointed you cannot see any delete query in the logs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Download Manager with priority (Java, Android) I'm doing a little download manager within my app. I was using
ThreadPoolExecutor threadpool = new ThreadPoolExecutor(1,210, (int) 210, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(210), new mThreadFactory());
and calling the following method for order the downloads:
threadpool.execute( new DownloadRunnable(url) );
Recently I changed a little my app and now I need to distinguish two kinds of downloads: Foreground Downloads (for elements that need to be shown to the user asap) and Background Downloads for saving a Internet resource at the disk for example.
I want some kind of pool executor always when picking the new element for download priorize Foreground downloads if exists and else download a background resource.
Can someone guide me with that solution?
Thanks in advance
A: You can use a PriorityBlockingQueue instead of your ArrayBlockingQueue and give the foreground downloads a higher priority.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The mechanism behind Unity3D visual programming third party tools First sorry for posting this here.I just got no answer to this question on "Unity Answers"I have been looking into the tools like uScript or Strumpy Shader Editors which are node based visual programming tools like Unreal Kismet or 3DsMax particle flow system. I have been researching on how in fact these tools generate the source code in Unity.So I assume that during the node logic assembly the code should be generated and compiled to DLLs (in Unity all the source code is compiled into DLLs)dynamically.I started looking into such C# assemblies like Reflections , Microsoft.CSharp and System.CodeDom.Compiler; I even tried to write a C# class in Unity via the editor as a text and then parse and compile it into DLL using the above mentioned tools(it was ok but the DLL was existing only during the Runtime in the temp..) Therefore I would like to know is this the approach those tools are likely to use? Or there is a better and cleaner way to do it ?Thanks .
A: I'm actually in the process of doing the same thing.. I think you are on the right path with the Compiler classes. I dont think you can emit IL on the fly on mobile devices as a security sandbox issue but I'm dynamically creating c# code and compiling it into persistent dll's like this..
CompilerParameters compilerParameter = new CompilerParameters();
compilerParameter.OutputAssembly = "/Your/Path/Here.dll";
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
StringBuilder code = new StringBuilder();
code.AppendLine("public static class Test {");
//More code here...
code.AppendLine("}");
var compilerResult = codeDomProvider.CompileAssemblyFromSource(compilerParameter, code.ToString());
Hope this helps..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Bridging standard input/output over a TCP socket I want to write a script that does the following:
*
*Start listening on a random available localhost TCP port.
*Start a certain external program passing the port number as an argument.
*Accept a single connection to the server socket.
*Send the script’s standard input into the socket, and the socket’s output to standard output.
*Exit when the external program exits.
The ideal solution would be a shell script invoking some reasonably standard tools, so if anybody can come up with a way to do that, well, that would be the perfect answer. If that proves intractable, a Ruby implementation would be convenient for me. Failing that, I’ll take any workable implementation.
P.S. I’m pretty new here, so please let me know if this question is too general or if it doesn’t belong for some other reason (maybe "please implement X for me" is frowned upon?).
A: Have you tried netcat ? Both listener and client can be done with nc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cast object at runtime I want to perform the following line of code using reflection.
IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(Environment.SpecialFolder.Desktop.ToString()+"\\Max Y+Y.lnk");
I have successfully get the right part of expression.
WshShell.CreateShortcut(....)
By using
this.assembly = Assembly.LoadFrom(Environment.CurrentDirectory + "\\Interop.IWshRuntimeLibrary.dll");
AppDomain.CurrentDomain.Load(assembly.GetName());
this.WshShellClass = assembly.GetType("IWshRuntimeLibrary.WshShellClass");
object classInstance = Activator.CreateInstance(this.WshShellClass, null);
object[] parameters = new object[1];
parameters[0] = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Max Y+Y.lnk";
MethodInfo methodInfo = this.WshShellClass.GetMethod("CreateShortcut");
object result = methodInfo.Invoke(classInstance, parameters);
Now I want to cast it to object of Type IWshRuntimeLibrary.IWshShortcut result in above case and assign it to.
IWshRuntimeLibrary.IWshShortcut desktopShortCut,
How is this possible?
A: If WshShellClass.CreateShortcut returns a IWshRuntimeLibrary.IWshShortcut then you could just say
IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut) result
Am I missing something?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validate an email inside an EditText I want to validate an email introduced inside an EditText and this the code that I already have:
final EditText textMessage = (EditText)findViewById(R.id.textMessage);
final TextView text = (TextView)findViewById(R.id.text);
textMessage.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (textMessage.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && s.length() > 0)
{
text.setText("valid email");
}
else
{
text.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
The problem is that when I introduce 3 characters after the "@", it appears the message "valid email", when it must appear when I introduce the complete email.
Any suggerence?
Thank you all!
A: public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
A: If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link
A: Several good options here including android.util.Patterns.EMAIL_ADDRESS for API 8+.
https://stackoverflow.com/a/7882950/1011746
A: Just change your regular expression as follows:
"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
Because . (dot) means match any single-char.ADD a double backslash before your dot to stand for a real dot.
A: I wrote a library that extends EditText which supports natively some validation methods and is actually very flexible.
Current, as I write, natively supported (through xml attributes) validation methods are:
*
*regexp: for custom regexp
*numeric: for an only numeric field
*alpha: for an alpha only field
*alphaNumeric: guess what?
*email: checks that the field is a valid email
*creditCard: checks that the field contains a valid credit card using Luhn Algorithm
*phone: checks that the field contains a valid phone number
*domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
*ipAddress: checks that the field contains a valid ip address
webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
*nocheck: It does not check anything. (Default)
You can check it out here: https://github.com/vekexasia/android-form-edittext
Hope you enjoy it :)
In the page I linked you'll be able to find also an example for email validation. I'll copy the relative snippet here:
<com.andreabaccega.widget.FormEditText
style="@android:style/Widget.EditText"
whatever:test="email"
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="textEmailAddress"
/>
There is also a test app showcasing the library possibilities.
This is a screenshot of the app validating the email field.
A: Don't do it in code. You can use inputType attribute of EditText.
<EditText
android:id="@+id/edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"/>
A: Try this pattern.....
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
pattern = Pattern.compile(".+@.+\\.[a-z]+");
matcher = pattern.matcher(editText.getText().toString());
if(matcher.matches()) {
Log.i("Test","--------Valid Email--------");
}else {
Log.i("Test","--------Invalid Email------");
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
A: private boolean validateEmailAddress(CharSequence emailAddress)
{
if( Build.VERSION.SDK_INT >= 8 )
{
return android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches();
}
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(emailAddress);
return matcher.matches();
}
A: // validate your email address format. [email protected]
public boolean emailValidator(String email)
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How to access a password protected site using python? I was thinking that, if I access a password protected site using python's mechanism, I would get a 401 Unauthorized error which needs authentication data.
So inside my script, I tried to access my yahoo mail box which apparently needs username and password, I thought I would get 401, but I didn't.
Code:
yahoo_mail = 'http://mail.cn.yahoo.com'
br = mechanize.Browser()
r = br.open(yahoo_mail)
print r.info() #here, I got 200, it's ok apparently
br.select_form(nr=0) #select the login form
r = br.submit() #submit the form without providing username and password
print r.info() #but I didn't get 401, why?
Question:
*
*Why I didn't get 401 without providing auth-info ?
*If not my mail box, any other website can give me a 401 ?
A: Most web sites these days do not use HTTP Authentication. So 401 is not returned if you fail to log in; instead, a normal 200 successful response is returned, and the text inside the web page says you did not log in.
Instead, sites use cookies. This means that your browser does not actually know what sites it is logged into; when you finally provide a successful password to Yahoo!, it either changes the cookie it has stored on your browser, or maybe even keeps the cookie the same but just changes the database record on their end that is associated with the cookie.
So HTTP status codes are generally useless during the process of logging in. Instead you will have to scrape the text of the "200 Success" page that comes back to see if it congratulates you on logging in or repeats the form; or, alternately, you might just check the URL of the page you get back, and see whether it is the login form again, or whether it is instead the destination that you wanted to visit.
A: *
*Authentication failed doesn't mean you're not allowed to see the page behind the authentication. It means you won't see the version of this page that take your credentials into account. If you're on a homepage and you failed to authenticate, you still can see the homepage.
*Search engines don't seem to index 401 pages, so it can be a bit hard to find...
A: It looks like Yahoo just handles the password authentication in their code. Try adding the following two lines to your code:
f = open('a.html', 'w')
f.write(r.read())
When you read the page, you will see the same page again.
It looks like they just have a bit of javascript that tells you your password was wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What should we prefer to use Stored Proc or Prepared statements I have recently started working on Databases. I know the basic difference between Stored Procedures and Prepared Statements. But can just brief me an idea that when we have to use which one. My trainer told me both are used when you have to execute a command often but then which one we should go for. I have heard that Stored procedures are always preferred. I know Stored procedures are pre-compiled and written in database.
I can accept if someone says actually there is no similarity between the two so no question of differences and usage preference, but still I putted this question as I am unaware of these things. I am using SQL Server 2008 Express with C#. Can some one help me out please.
A: Use both? Stored procedures for writes, prepared statements for reads?
Why?
*
*Command-query separation
*RDBMS deals with transactions, data integrity etc (eg less round trips to check a condition)
*Clients are not constrained to stored procedures for reads (but would still use a view or UDF: never raw tables)
Oherwise, there is no correct answer because it will be different depending who you ask
*
*stored procedures and banks
*When to use Stored Procedures instead of using any ORM with programming logic?
*Any reason not to use stored procedures for every query?
*and many others
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript: Radio button not checked value I have variable that get's value of checked radio button named: parentcheck
I wanna check if parentcheck is checked and =0 or if not checked. Tried if(parentcheck=='') for "not checked". it doesn't work.
var parentcheck = $(".parentcheck:checked").val();
if(parentcheck=='0'){
$("#parent").hide();
}
if(parentcheck==''){
$("#parent").hide();
}
A: if(!$('.parentcheck:').is(':checked')) {
$('#parent').hide();
}
A: I actually can't get your question, it should help you.
var $check = $('.parentCheck');
if ($check.val() == '' || toString($check.val()) == "0") {
// do your stuff
}
if ($check.attr('checked')) {
// checked, do your stuff
}
else {
// is not checked, do another stuff
}
A: Use .attr('checked')=='checked'
A: First off, that selector you use will only return you elements with the class .parentcheck which are actually checked. By definition, that means every element it returns (as it always returns a set in jQuery) will be checked, so if the element you're looking for isn't checked then it won't be in the set. Something like this might be what you're after:
if (! $(".parentcheck").is(":checked")) {
$("#parent").hide();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Regex for whole words only I have the following code:
function mmh_links($message){
ini_set('auto_detect_line_endings','1');
$row = 1;
if (($handle = fopen(realpath(dirname(__FILE__))."/mmh_replace.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$message = preg_replace("/({$data[0]}(?![^><]*?(?:>|<\/a)))/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);
}
fclose($handle);
}
return $message;
}
Which looks for specific keywords from a CSV file and surround them by a link given in the CSV file as well. Additionally, it makes sure it only replaces each keyword only once, and makes sure it doesn't replace keywords that are already within links, and it is case insensitive. All good so far.
Now I want to limit to search to "whole words", meaning I don't want "test" to catch "xxxtestxxx".
What's my best option to do this, while keeping all the rules I wrote before?
A: Wrap the whole words you'd like to match with the \b operator - this indicates a word boundary:
$pattern = "/(\b{$data[0]}\b(?![^><]*?(?:>|<\/a)))/i";
$subject = "<a href=\"{$data[1]}\" class=\"postlink\">$1</a>";
$message = preg_replace($pattern, $subject, $message, 1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Prevent url's from appearing as links in mail clients I'm sending an HTML mail from my app, this mail contains URLs, is there a way to prevents from mail clients to show these URLs as links?
for example:
<table>
<tbody>
<tr>
<td>http://www.google.com</td>
</tr>
</tbody>
</table>
will generate" http://www.google.com
instead I want it to generate a static text.
any thoughts?
A: I have found the accepted answer doesn't work for Outlook 2013. I have had success with the following:
http<a href='#' style='text-decoration:none; color:#000;'>://www.google.</a>com
Setting the style cursor:default is not honored by Outlook 2013, but if you only make the middle of the url a hyperlink then a user can still select the link text without the cursor pointer appearing.
A: This is a feature of some mail clients and there's no foolproof way to stop them from doing whatever they want with the message contents.
You could try to trick the mail clients by wrapping the addresses in empty tags and hope that they aren't smart enough to see through it:
<td><span>http</span><span>://</span>www.<span>google.</span>com</td>
A: Use a "zero width space" character: ​
It does as the name implies. It adds a space in your string but the space takes up zero width so instead of looking like two strings, it looks like one.
A: I'd say that largely depends on the mail client and thus is beyond your control. The only option would be to not make it a URL. E.g. write www.google.com (which the user can copy/paste just like the URL.
A: I didn't have any luck in preventing MacMail and Yahoo Mail from creating links out of any text string ending in .com (or other domain extension). After hours of testing (even 'href=""' and 'href="#"' did not work), I finally inserted my own URL and then manipulated the CSS and inline styles to remove the mail clients' link styling.
A: Adding in hidden line break elements in the right places seems to have fixed this for me (for now) in almost all clients, including desktop Outlook, according to Litmus's tests (Apple Mail desktop looks like the main exception).
https:<br style="display: none;"/>//www.w3<br style="display: none;"/>.org/TR/2020/WD-WCAG22-20200227/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: ORDER BY relevance, while using parametarized values i found the following query online:
SELECT company_title
FROM companies
WHERE company_title like '%gge%'
GROUP BY company_title
ORDER BY CASE WHEN company_title like 'gge%' THEN 0
WHEN company_title like '% %gge% %' THEN 1
WHEN company_title like '%gge' THEN 2
ELSE 3
END, company_title
limit 100
that works perfectly.
the thing is, i am passing a parameter as value, and then fails.
so the question is, how to use this query with parametized values?
an example for a mysql programmer could be to define a variable at top SET @what = '%gge%'
and then use it in the query.
A: You can't use variables in an order by clause.
You have to use Dynamic SQL, check this: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
A: Move the case when statement to the select part and refer to it the the order by clause by its alias.
SELECT company_title
,CASE WHEN company_title like CONCAT(@param,'%') THEN 0
WHEN company_title like CONCAT('% %',@param,'% %') THEN 1
WHEN company_title like CONCAT('%',@param) THEN 2
ELSE 3
END as relevance
FROM companies
CROSS JOIN (SELECT @param:= ?) as trick_to_set_at_param_in_one_go
WHERE company_title like CONCAT('%',@param,'%')
GROUP BY company_title
ORDER BY relevance, company_title
LIMIT 100
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invoking Visual Studio's visualizer manually Scenario
I've been trying to manually invoke Visual Studio's visualizer from code/immediate window, so far without any luck.
I've written a simple console application with the following code:
var dataset = new System.Data.DataSet();
Then I added dataset into the Watch Window and visualized it using the DataSet Visualizer. As expected, that worked.
Once I've done that, I entered the following code into the immediate window:
new Microsoft.VisualStudio.DebuggerVisualizers.VisualizerDevelopmentHost(dataset, typeof(EnhancedDataSetVisualizer.DataSetVisualizer)).ShowVisualizer();
Which caused the following exception (full exception):
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.Debugger.DataSetVisualizer, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.VisualStudio.Debugger.DataSetVisualizer, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity,
….
Which is really strange to me because if I look into Debug->Widnow->Modules in Visual Studio, I see that DataSetVisualizer.dll is already loaded:
Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\Visualizers\Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll No No Cannot find or open the PDB file. 18 10.0.30319.1 18/03/2010 12:06 PM 77AB0000-77AC2000 [6784] PresentingBugAid.vshost.exe: Managed (v2.0.50727)
Yet, it tries to load it, and fails. I've tried to examine the fusion log (full log):
…
file:///C:/SVN/Debugger/src/Test/PresentingMyTest/PresentingMyTest/bin/Debug/Microsoft.VisualStudio.Debugger.DataSetVisualizer.DLL.
LOG: Attempting download of new URL
...
And just for the sake of trying I copied Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll to c:\SVN\Debugger\src\Test\PresentingMyTest\PresentingMyTest\bin\Debug\ then retried the scenario above. This time it seemed to work, the visualization appeared, yet, it froze the whole application. Moreover, trying it again no longer showed the visualization at all.
Afterthoughts
I realized after a while that what I did might be weird - Visual Studio's Visualizers are designed to run inside the debugger's process (devenv.exe), yet, in my case I've been trying to force the visualizer to load in the debuggee (PresentingMyTest.exe). While it doesn't explain why it tried to load Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll even though it was loaded, I guess it explains why it didn't work in general.
Another solution I considered to try is skipping VisualizerDevelopmentHost completely, and instead, invoking via reflection DataSetVisualizer's Show method directly, a method that any visualization must have. Is that a good idea?
I realize the whole scenario is quite unsupported, yet, it is quite important for my project and I'be happy to hear additional thoughts and things I can try to make it work.
Thanks!
A: Maybe it's possible to use 'Microsoft.VisualStudio.DebuggerVisualizers.VisualizerDevelopmentHost' type and particular ShowVisualizer() method? I haven't had time to play around vizualization debuggers, so this is just a wild guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I read file by line and execute each line with cat I have file js.txt which contains paths to javascript files. I want to output all javascripts into one file.
js.txt content:
js/jquery/jquery-1.6.2.min.js
js/jquery/jquery-ui-1.8.6.custom.min.js
My bash script:
#!/bin/bash
WEBROOT=/home/rexxar/web/webroot/
FILE=$WEBROOT"js.txt"
cat "js.txt" | while read LINE; do
cat $WEBROOT$LINE >> js_all.js
done
Output in terminal is error message: "Directory or file doesn't exist" followed by file path fragment for each line.
: Directory or file doesn't exist/jquery/jquery-1.6.2.min.js
: Directory or file doesn't exist/jquery/jquery-ui-1.8.6.custom.min.js
I am sure that all paths are right and files does exist.
A: Firstly, some advices.
1) Check absolute paths of files js/jquery/jquery-1.6.2.min.js and js/jquery/jquery-ui-1.8.6.custom.min.js. Use readlink -f and dirname.
2) Check absolute path of directory your script is running from.
3) Think about variable $FILE . Maybe it's a good idea to use cat ${FILE} instead of cat "js.txt"
4) Empty lines in js.txt is also make some kind of problems to you.
5) And why are you using CAPS_VARIABLE_NAMES?
Secondly, the solution.
I'm trying to understand your problem, so I've create all files you've got there:
$> cat js/jquery/jquery-1.6.2.min.js
test1
$> cat js/jquery/jquery-ui-1.8.6.custom.min.js
test2
$> cat js.txt
js/jquery/jquery-1.6.2.min.js
js/jquery/jquery-ui-1.8.6.custom.min.js
So, like Arnout Engelen said (but I cannot understand why he use > instead of >>)
$> cat ./js.txt | xargs cat >> ./js_all
$> cat ./js_all
test1
test2
A: How about:
cd $WEBROOT; cat js.txt | xargs cat > js_all.js
A: It looks to me like your js.txt file has DOS line endings (carriage return+linefeed) instead of unix (just linefeed), and the script is treating the CR as part of the filename. Either convert the file with something like dos2unix, or make the script convert it on the fly:
...
tr -d "\r" <"js.txt" | while read LINE; do
....
A: relative paths are saved in your js.txt. you have to make sure that the path is valid from the directory where you execute the script. unless in your script you first run 'cd' command to the right directory.
if the directory thing is fixed, awk oneliner can do what you need.
awk '{if($0) system("cat "$0" >> js_all.js")}' js.txt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mock classes with traits Is there any library that provides tools for mocking classes with traits (both can be statefull)?
Simplified example:
trait T {
var xx: List[Int] = List[Int]()
def t(x: Int) {
xx ::= x //throws NPE, xx == null, even after implicit initialization
}
}
class A extends T {
}
class Testable(a: A) {
def bar() {
a.t(2)
}
}
@Test def testFoo() {
val a: A = mock[A]
val testable = new Testable(a)
testable.bar()
verify(a).t(2)
}
A: Paul Butcher has been working on Borachio, a Scala mocking library. It supports mocking of traits, classes, functions and objects. See the following blogs for more information:
http://www.paulbutcher.com/2011/02/announcing-borachio-native-scala-mocking/
http://www.paulbutcher.com/2011/07/power-mocking-in-scala-with-borachio/
A: Well ... I don't have an answer, but I think I can offer a hint at where the problem is coming from. I took a look at A.class and found this (de.schauderhaft.testen is the package I used):
// Method descriptor #21 (I)V
// Stack: 2, Locals: 2
public bridge void t(int x);
0 aload_0 [this]
1 iload_1 [x]
2 invokestatic de.schauderhaft.testen.T$class.t(de.schauderhaft.testen.T, int) : void [26]
5 return
Line numbers:
[pc: 0, line: 13]
Local variable table:
[pc: 0, pc: 6] local: this index: 0 type: de.schauderhaft.testen.A
[pc: 0, pc: 6] local: x index: 1 type: int
I'm no byte code expert but this
2 invokestatic de.schauderhaft.testen.T$class.t(de.schauderhaft.testen.T, int) : void [26]
looks like the call to t(Int) is actually a called to a static method and you can't mock static methods. PowerMock would help, but probably ugly to use.
A: I just released ScalaMock 2.0. As well as functions and interfaces, ScalaMock can mock:
*
*Classes
*Singleton and companion objects (static methods)
*Object creation (constructor invocation)
*Classes with private constructors
*Final classes and classes with final methods
*Operators (methods with symbolic names)
*Overloaded methods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to keep a table field value in consecutive growing order throughout delete operations? I'm working on a table in a database which has a primary key field with numeric int value.
CREATE TABLE 'table' (
'primary_key_field' INT NOT NULL
'other_fields' ....
PRIMARY KEY ( 'primary_key_field' )
)
When I insert a new element the id value is set to auto increment.
My problem is that when I delete elements and insert new ones the order of the id values is not consecutive any more but has holes in it.
ex: if I delete elements with key field value 3 and 6 the values will be:
1,2,4,5,7,..and so on..
Is there a way to keep elements in the correct succession?
ex: so that when I delete the table element with field value 3 the element with field value 4 will automatically update its value to 3 and so on for all other elements?
Thanks in advance for help!
A: Unless you write your own query, no mainstream RBDMS supports it.
*
*An autonumber/identity column should have no meaning or external value
*foreign keys would need updating
*history tables track original values: delete the new id 3 in your example there is a conflict
If you need a contiguous number for reading then you need ROW_NUMBER or a MySQL equivalent.
A: Is there any reason why you need to not have gaps in your primary key sequence? Other than serving to identify a record in the database uniquely, an autoincrement primary key serves no other function. There's no drawbacks to allowing gaps (unless you're worried about running out of keys, and seeing as how int gives you about 2 billion values you're unlikely to run up against that problem), and there's considerable drawbacks to trying to not allowing gaps. For example, you delete the record with ID 3 from your table, then insert a new record. This new record, because you're not allowing gaps, gets an ID of 3. Now how do you know that this is the original record, or one that's replaced another record that was deleted previously?
This problem will only be compounded if your table's primary key is being used as a foreign key somewhere else. Suppose you delete record 3 and replace it with something else, but there's also an entry in another table in your database that refers to record 3. Does that record's foreign key need to be updated to point somewhere else? Should it point to the new record 3? Should it be deleted along with the original record 3? And that's just if you have 2 tables with 1 foreign key reference. Real world databases tend to get a lot more interdependent than that very quickly.
There is simply no good reason for doing what you want to do.
A: You are trying to reclaim the id values. You will have to do this programmatically which is not a good idea because you will have to update the foreign keys throughout the database.
I would like to ask the fundamental question about why would you want to keep the ids continous ? Are you worried about running out of ids ? If you are, then I would suggest you change the datatype of your primary key to something like bigint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wrong decibel result on fft data If i remember the decibel range is bit depth * 6.
I play wav file that his bit depth = 16 (using NAudio lib) and I get the fft result then i'm calc the decibels for each fft result. 20 * Math.log10(fftData[i]) and i've got strange results (-109...)
how it can be over -96 (for 16 bit)?
(i work with .net 4)
Thanks!
A: The limit of the dynamic range of amplitude in time domain does not carry over to magnitude of components in the frequency domain. A square wave can be represented by an audio signal with a resolution of only 1 bit, no dynamic range whatsoever. But in the frequency domain, it is defined by sin(x) + 1/3 sin(3x) + 1/5 sin(5x) ... The fractional coefficients illustrate this point. The upper harmonics are an infinite series with ever smaller coefficients, with no limit on their dynamic range.
Also, to respond to your follow up: yes, for display and visualization purposes, you should pick some limit like -120 dB and ignore the content below. I think the rationale for ignoring content below -120 dB is that the dynamic range of human hearing is about 120 dB. You might also consider the content below -96 dB quantization noise, but I'm not certain about that.
A: dB is a measure of ratio, not absolute amplitude. Your figure of -109 dB is a ratio relative to some arbitrary 0 dB reference point, which may or may not correspond to full scale in your case.
It's also important to note that the energy in just one frequency bin may be a lot smaller than the energy corresponding to a 1 bit signal, as already mentioned by Matt M, since it represents energy in a relatively small bandwidth (units are V / sqrt(Hz)).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: several choices for executable path, but only one works inside Visual Studio? I am trying to register my executable for some shell action and need to find out the path to current executable. I found several questions (and answers) here on SO, and found the following options:
*
*Environment.GetCommandLineArgs()[0]
*System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
*typeof(Program).Assembly.Location
However when debugging inside Visual Studio 2010 the first two return the vshost exe name, e.g. ...bin\Debug\ExportVSProject.vshost.exe. I think I understand why. By trial-and-error I found that the last provides the right name inside VS and outside.
My question is, are there any downsides to using Assembly.Location? The reason I am asking is I did not see any comparison to choose one over the other in the other answers.
A: It's fine. The more general solution is Assembly.GetEntryAssembly().Location, usable anywhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails server on VirtualBox is running really slow My local Rails server is running excruciatingly slow. The setup: Ubuntu server in VirtualBox, and Windows can SSH and access HTTP port 3000. Memory allocated is 1.5GB, but the page is still responding really slow in my Windows 7 browser.
Any thoughts on this? (I might be one of the really few people who's using this setup...)
A: I managed to solve this problem by switching from Webrick to another Rails server (can't remember which one anymore), simple as that.
Webrick might not necessarily be the problem though, because later when I switched back to it, the server run just fine without any sluggishness.
A: Looks like this could be one of a couple issues:
*
*Webrick reverse DNS lookups are slowing you down: Webrick is very slow to respond. How to speed it up?
*You're using a VirtualBox shared folder, and vboxfs is very slow: Rails VERY slow in development using Ubuntu VVM
A: After you created your vm make sure that you install the Guest Additions!
It lets you use your virtual machine at fullscreen and it also adds extras kernel modules to get better performance.
once in your VM on the above menu click devices and click insert guest editions cd image..
then go to my computer and find that image, should be cd, double click and it should load
that worked for me, good luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Purpose and Use of ThreadLocal class? I was going through the ThreadLocal class documentation and wondered in what scenarios it can be used.
First I thought it can be used in those scenarios where we have third party/legacy classes and we want to handle synchronization issues. Then I looked at other examples of ThreadLocal and found out that ThreadLocal wont help there, because in most of those cases we have single object which is shared across all threads. Is this correct?
With further understanding, now I can think of using the ThreadLocal class in those scenarios where we need a seperate object for each thread and if a specific thread interacts with an object in ThreadLocal, the same object is used every time instead of creating a new one.
Is this correct or am I missing something?
A: ThreadLocal is most commonly used to implement per-request global variables in app servers or servlet containers where each user/client request is handled by a separate thread.
For example, Spring, Spring Security and JSF each have the concept of a "Context" through which functionality of the framework is accessed. And in each case, that context is implemented both via dependency injection (the clean way) and as a ThreadLocal in cases where DI can't or won't be used.
It's bad for maintainability because it hides dependencies, and also directly causes problems because such containers use a thread pool. They have to use reflection to delete all ThreadLocal instances between requests to avoid having data from one request turn up in another (potentially causing nasty security problems). Sometimes it also causes memory leaks.
Basically, it's a feature that can be very useful in a hackish way, but also very dangerous. I'd advise you to avoid it if possible.
A: Another often used application is a per thread cache for objects where synchronization is required but the overhead must be avoided.
For example: SimpleDateFormat is not thread safe - no Format is. Creating always a new instance is not efficient. Synchronizing on one instance in a multithreaded environment is also not efficient. The solution is this:
class Foo
private final static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>(){
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
public void doStuff(){
SimpleDateFormat df = threadLocal.get();
// use df
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: java regex not working Why this regex isnt working for non-word and non-digits like this: )(ª º ?
sentence.split("[^(\\p{L}\\p{N})]");
Is it suposed to work or not?
PS: I can't find any information either on SOF or in the web
A: A better description of the problem would be nice, but I'm guessing you're looking for:
sentence.split("\\W+");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenGL - Not Draw Completely Occluded Polygons? Let's say we have a set of polygons, can change the camera view angle and can translate the camera in the 3D environment. From certain view angles some of these polygons are completely occluded by one or several of the other polygons. For each drawn frame we know the exact coordinates for each of these polygons and can iterate through them in the "increasing distance to camera" or "decreasing distance to camera" order.
Now my question:
What is an efficient way to prerender determine whether a polygon is completely occluded by others, so that we could simply skip it in the drawing process to boost performance?
A: The technique you're looking for is called Occlusion Culling and is a rather complex task.
Being able to iterate through them in increasing camera distance order (front-to-back) gives you some advantages. Just rendering them this way lets you profit from early z-testing features of nowaday's graphics hardware and the polygons only have to go through vertex-processing and rasterization, but need not to be fragment-shaded. This can also be achieved without sorting the polygons but rendering them (in an arbitrary order) in a so-called depth-prepass, where you disable color writes and only render the polygons' depth values. Now in the next rendering pass (the real one) you also profit from early z-rejection.
You might also use hardware occlusion queries of nowaday's GPUs like explained in this GPU Gems article.
But like Hannesh said, it should always be weighted if the overhead of the occlusion culling is worth it. I assume the front-to-back sorting in your case doesn't just come out of nowhere. Maybe the depth-prepass is a viable alternative requiring no sorting. Whereas you can use occlusion queries in a way that doesn't require any sorting (like described in the link), in this case it's not as effective as with front-to-back sorting.
A: What you're thinking of is called Occlusion culling. Modern graphics cards have functions you can call that tell you exactly that. You have to have already rendered the occluding scene first though. The alternative is to do this on the CPU.
However, I would not suggest doing what you are trying to do in any case. Graphics cards are fast at rendering static data in big chunks. If you are modifying that data to remove hidden surfaces, you're going to kill performance no matter how fast your occlusion algorithm is. And graphics cards a smart, if they realise that a polygon is completely covered they'll throw it out the the pipeline early.
If you are not already doing so, put your polygons into a static vertex buffer. Vertex buffers are a great way to rendering a lot of polygons quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Filling an array with selected items of another array I'm just getting to know AppleScriptObj-C and trying to create a simple application that would allow me to create playlists.
The question is:
I have an array, containing all the music tracks from my iTunes library viewed through NSTableView. I make a selection and want these selected items to be copied to another array. How do I do it?
Thank you.
A: I'm not that familiar with AppleScriptObj-C, but I can give it to you in AppleScript...
tell application "iTunes" to set the array to the selection as list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it more efficient to make a half-transparent PNG, or set opacity/alpha-filter on a non-transparent PNG? The image in question will be reused about 5 times on each page of a website. I can either set the opacity to 0.5 and alpha(opacity) to 50 or I can lower the opacity of the image in Photoshop and save it with that setting.
Is there a better practice to follow?
A: If the image is going to have the same opacity wherever it's used, I don't see why you should need to add a bunch of opacity declarations with the same values everywhere you use it.
Lower the opacity in Photoshop, save it once, and use it everywhere. In case you need to change the image's opacity later, you can simply open the PSD, change it there, save it once more and the change will be reflected automatically without you having to change all the opacity styles again.
A: Check the 5th answer of linked question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort after inserting an item into a Linked List? I have a C++ Program to insert Nodes to a linked list. The Nodes consist of a string that we'll call data, and a pointer to the next node that we'll call next. Also, the head node will be defined as head.
I'm not sure what's more efficient -
1. Inserting a bunch of strings to my list then sorting it afterward
2. Or sorting the list as I insert.
I think it's the latter, and I am wondering how I will go about implementing something like that.
I want to know the simplest way to implement such a function.
A: first solution: insert k elements unsorted, just insert them to the start, it is O(1) each. and one sort: O(nlogn) after these k elements. you get amortized time of O(nlogn+k)/k = O(n(logn/k)).
second solution: inserting an element to a list is in sorted order is O(n), since you need to find the place in the list. for k insertions, it will be O(n*k), and amortized of O(n*k/k) = O(n).
So the first solution is better for logn < k, and the second for logn > k
For better efficiency, you will probably want a sorted data structure that access elements in O(logn) such as a skip-list [which is basically a variation of linked list with additional information for easier accessing] or an avl tree
A: I had answered a similar question (99 % similar :) ) HERE
Now its for integer i guess, for string you can compare using std::string compare function or strcmp provided by C library
As per my opinion and seeing other answers it would be better for your application (if it needs sorted linked list ) to sort the data as you insert .
A: I think it doesn't actually make a difference how you do it, when you sort while inserting, you'll have O(n) on the insert, cause you might have to traverse the entire list before you find the right spot to insert.
However when you sort after adding all items to the list, you'll also have at least O(n) to move items around the list.
A: The simplest solution is to use what C++ already offers - std::list and std::list::sort:
#include <list>
#include <algorithm>
#include <iostream>
#include <string>
class Node {
public:
Node(const std::string& data) : Data(data) {
}
std::string Data;
};
bool NodeLess(const Node& n1, const Node& n2) {
return n1.Data < n2.Data;
}
void main() {
std::list<Node> l;
l.push_back(Node("d"));
l.push_back(Node("c"));
l.push_back(Node("a"));
l.push_back(Node("b"));
l.sort(NodeLess);
for (auto i = l.begin(); i != l.end(); ++i)
std::cout << i->Data.c_str() << " ";
}
If you can get away with it (memory-wise), you could also use std::vector to pre-sort the items (through std::sort) before inserting them into linked list, which could be somewhat faster.
You could also use std::map (or even std::set) instead of list - it will "auto-sort" your items as you insert them.
If you still want to use your own list, you could implement begin and end in it, and use std::stable_sort. Note that std::stable_sort expects bidirectional iterators, (unlike std::sort which expects random-access iterators). To implement bidirectional iterators in your list, you'll need to make it doubly-linked, not just singly-linked.
If you want to implement the sort itself, it is possible to implement both Quicksort and Mergesort on linked lists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting information from PFX file Is there a utility to get information from PFX files like for example to get the private key? How is a PFX structured?
A: KeyPal utility will help you partially.
Refer Pkcs#12 options.
A: Use the below command.
keytool -list -keystore path of pfx file in quotes -storepass password of pfx file in quotes
It will display how many certificates keychain it has along with all details one by one
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java - looking a method like contains static boolean contains(Iterable<String> haystack, String needle) {
for (String s : haystack) {
if (s.contains(needle)) {
return true;
}
}
return false;
}
static void containsAll() throws IOException {
List<String> words = loadLines("opacial.txt");
List<String> tocheck = loadLines("queries0.txt");
System.out.println(words.size());
System.out.println(tocheck.size());
int index2 = 0;
for (String s : tocheck) {
if (contains(words, s)) {
index2++;
//return false;
}
}
System.out.println(index2);
//return true;
}
i am looking a method like contains (code above) that will do this:
it will check if needle exists in the haystack, or if needle is part of a string in haystack.
In that case (the code above) if i reverse the file that goes to haystack, and the file that gives the needle, the result is the same. but i dont want that. for example:
File 1:
i love beers
i like travelling
stackoverflow
beers
And File2 :
beers
i love stackoverflow
then if haystack comes from file 1 and needle comes from file2, i want the result to be 2 because the word beers is part-or the same only with two strings of haystack. (beers ---> i love beers and beers) - nothing happens with i love stackoverflow)
BUT when haystack comes from file2 and needle comes from file1, i want the result to be 2. (i love beers is not part or same with anything of file 2, i like travelling the same, stackoverflow is part of i love stackoverflow -1- and finally beers is same with beers -2-)
what is the correct method for that?
As i said before contains gives me the same result no matter what file is haystack or gives the needle's strings.
PS in my example the result is the same, but i think that is random.
how can i do that?
A: I think that you meant that the values should probably be different for the two cases? You show them as being the same.
If you want to find a string within another string, use the String object's indexOf method. For example:
String s = "abcdef";
s.indexOf("b");
will return 1. If the value is not present, the method returns -1.
So if you want to find a needle in a haystack, it means checking every line one file for the existence of a line in another file. Keep in mind that if the files (and the lines in them) are large, this means a lot of string processing, which can be slow. And you would have to do it in both directions. First, get a line in file 1, and compare it to every line in file 2 (unless you find a match, in which case you can stop looking for the line from file 1). Then move to the next line in file 1, etc.
The reverse, and look for line 1 from file 2 in file 1.
I won't describe all the logic, but that part shouldn't be too hard to figure out, assuming you know how to open files and write loops.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: No results showing for mysql select all Hello guys i am trying to show all the users pokemon were the table belongsto = there username here is my code
i have a connect on top of this has well
// Get all the data from the "example" table
$result = "SELECT * FROM user_pokemon WHERE
belongsto='".$_SESSION['username']."'
AND (slot='0')'";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
i have print red the username and there username is in the username session .
i think i mite be missing a ' or something i add or mysql at the end of the query but then the pages dies with no error
A: You are not running the query and have an error in it. And you're not escaping strings going into query.
A proper version of the code would be
// escape a string going to query.
$username = mysql_real_escape_string($_SESSION['username']);
// create a query
$sql = "SELECT * FROM user_pokemon WHERE belongsto='$username' AND slot=0";
// run a query and output possible error for debugging purposes.
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// keep getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
A: It appears to me that the final query would be:
SELECT * FROM user_pokemon WHERE belongsto='NAME' AND (slot='0')'
where NAME is the name you pass in. If that is the case, there is an extra single quote at the end. I presume you are getting a SQL error?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to read repository at http://download.eclipse.org/releases/indigo I was trying to add the PDT,
Indigo - http://download.eclipse.org/releases/indigo
Unable to read repository at http://download.eclipse.org/releases/indigo.
Unable to read repository at http://download.eclipse.org/releases/indigo.
http://download.eclipse.org/releases/indigo is not a valid repository location.
So what's the correct url ? I went and looked lots of places. Can someone point me to the exact link ?
Edit :
Problem once you go to http://download.eclipse.org/releases/indigo , you will see the below error. So I guess its moved somewhere.
This software repository URL, http://download.eclipse.org/releases/indigo/ , provides access to the software repository for the Eclipse indigo release. Until its released in June 2011, it will contain milestone builds.
The repository site URL is typically pre-populated in the list of software repositories when you install the Eclipse Platform or SDK.
For more information about installing or updating software, see the Eclipse Platform Help.
There is also a collection of handy, downloadable all-in-one zip files available for many interests and platforms. Many people find these all-in-one packages the easiest way to get started.
A: Can you connect to internet at all through Eclipse?
*
*Open the internal webbrowser. In Eclipse: Window -> show view -> Other -> General: Internal web browser.
*Look up any normal adress, is it working?
Can you connect to another update site? Try for example Eclipse Emma:
http://update.eclemma.org/
Do you see anything there?
What are your proxy preferences? Go to Window -> preferences -> General: Network connections.
The active provider:
Specifies the settings profile to be used when opening connections. Choosing the Direct provider causes all the connections to be opened without the use of a proxy server. Selecting Manual causes settings defined in Eclipse to be used. On some platforms there is also a Native provider available, selecting this one causes settings that were discovered in the OS to be used.
If internet is working fine outside of Eclipse, try changing to Native. After that, try Direct.
I have encountered problems where an update site would not load, then I had to remove it and add it again. This forces Eclipse to reread the contents of the site even if it has a cached copy. So, if you still get no connection to the indigo update site, but everything else is working, try that. Go to Window -> Preferences -> Install/update: Available Software sites. Then remove and add the indigo site. Just remember to copy the adress so you can add it again.
As suggested in a comment below by @lostiniceland, this is a simpler way to achieve the above:
Goto Window -> Preferences -> Install Update -> Available Software Sites => select the entry and click the "Reload" button to the right. This is sometimes also helpful when you have a local updatesite for testing custom plugins
A: Check if you are able to connect to eclipse market place url (http://marketplace.eclipse.org/) from browser. If its working then the issue is because of proxy server using in your network.
We have to update eclipse with proxy server details used in our network.
Go to :- Windows-> Preference -> General -> Network Connections.
And edit HTTP ,with proxy details.
Click OK
Done.
A: I was having this problem and it turned out to be our firewall. It has some very general functions for blocking ActiveX, Java, etc., and the Java functionality was blocking the jar downloads as Eclipse attempted them.
The firewall was returning an html page explaining that the content was blocked, which of course went unseen. Thank goodness for Wireshark :)
A: Another way to solve this kind of error is to start eclipse with this argument
-vmargs -Djava.net.preferIPv4Stack=true
Working fine with Eclipse (x64) 4.3.1
A: Had this problem in Linux, and I found that the user doesn't have permission to update the eclipse directory
change the owner of eclipse folder recursively, or run eclipse with user who has write permission to the folder
A: I had the same problem and resolved it by
*
*Deleting the cache directory \eclipse\p2\org.eclipse.equinox.p2.repository\cache
*Refreshing the repositories.
*
*Preferences -> Install Update -> Available Software Sites => select the entry
*Click the "Reload"
A: In Windows 7 32-bit version, I started the eclipse with as an administrator. This worked for me.
A: I had the same problem. Try to deactivate your Firewall (I had avast!), which worked for me.
(Sorry for my English I'm French :D)
A: Please make sure you are using correct url. If You are using url - http://download.eclipse.org/releases/indigo on your eclipse luna(v4.4) then it might be not working in this case you should use - http://download.eclipse.org/releases/luna
I have tried this and its working.
A: Kudos to @Fredrik above. His answer didn't work for me, but lead me to the resolution of my issue:
In 'Window'|'Preferences'|'Install/Update'|'Available Software Sites'. The location that I was attempting to install from the 'Marketplace' was getting inserted with an https:// URL. Editing this to http:// allowed me to then use 'Help'|Install New Software ...' to select the repository from the drop down 'Work with:' combobox instead of having the https:// one automatically inserted and used.
A: What worked for me:
Since yesterday, I have been trying to install the Eclipse plugin - "Remote System Explorer" from the Eclipse marketplace on a freshly downloaded Eclipse 4.8 as shown below,
and everytime I was getting this error:
Unable to read repository at http://download.eclipse.org/releases/kepler/.
Unable to read repository at http://download.eclipse.org/releases/kepler/201306260900/content.jar.
download.eclipse.org:80 failed to respond
which brought me to this SO post.
I tried a few solutions mentioned here in the different answers like this one and this one and this one, but none of them worked. I just gave up almost, thinking that either the corporate network here is somehow blocking the specific download requests or the 4.8 version of Eclipse is buggy.
Discovery:
I could not reload all the paths under 'Window' -> 'Preferences' -> 'Install/Update' -> 'Available Software Sites'.
Preconditions:
*
*What did work for me from the beginning was:
*
*I could open google.com from the internal web browser of eclipse and,
*some of the update paths, I could reload even. (As was mentioned as a possible solution or test, in some of the answers here, like this one.)
Finally, this answer put me on the right track - for my specific case, at least. Just my step was to do the exact opposite of what that answer was doing.
Solution:
I had to change all the http:\\ paths to https:\\ and suddenly it started to work. I don't know who - either IE/Edge on Windows 10 or the Windows 10 firewall or the company firewall is blocking HTTP communications. But with HTTPS, I can finally install plugins from the Marketplace.
*
*HTTPS reload works
I must say, what is strange is that not all the paths required https. Except a few, the rest seemed to have had no problem working with HTTP. But I anyways changed all to HTTPS, just for good measure.
*
*Then reload all the repositories one by one. Press "Apply and close".
*Then check for updates. Eclipse will update itself successfully now.
*Restart after update.
*Finally you can install whichever Plugin you would like to from the Eclipse Marketplace.
Note: In case during the update, this same error pops up again, then see in the repositories that any new paths added by eclipse during the update, are also HTTPS and not HTTP.
A: For eclipse, there are normally different options available:
*
*If you want to use the PHP development environment (only), you should go with the corresponding distro of eclipse. There is a distro for PHP provided by Zend.
*You may add PDT to an indigo release by doing the following steps:
*
*Check if an update site for PDT is included in your eclipse installation:
*
*Open the Help > Install New Software dialog.
*Click there on the link Available Software Sites.
*In the list, the URL http://download.eclipse.org/releases/indigo should be marked.
*Close the dialog.
*Select from the Work with list the site with the right URL.
*Enter in the filter box PDT and search in the list for the PDT tooling you want to install.
*Install the PDT tooling.
*If that does not work, you may download a complete update site from the PDT project site.
*
*Visit the site (URL above).
*Click on downloads.
*Search there for the string "all in one update site".
*Download the zip file.
*Install it in your Indigo installation. Help > Install New Software > Add... > Enter name and select from button Archive the zip file
I hope some of the installation instructions will work for you.
A: This is the correct URL. Chances are Eclipse cannot read it properly because of the Internet connexion.
Are you using a proxy to get Internet access? If this is the case you need to notify Eclipse via the "Preferences/General/Network Connections" menu.
A: That URL works fine. The message you report is normal when you look at it in a browser. My copy of Eclipse has no problems talking to it. If yours does, I suspect a proxy configuration error in your copy of eclipse.
A: Also try it by turning off the firewall, and similar services. It worked for me!
A: If you can't access https://dl-ssl.google.com/android/eclipse/ simply
try to use http://
instead of https://
A: I spent whole my day figuring out this and found the following. And it works great now.
This is basically an issue with your gateway or proxy, If you are under proxy network, Please go to the network settings and set the proxy server settings(server, port , user name and password). If you are under direct gateway network, your firewall may be blocking the http get request from your eclipse.
A: I was also unable to read the repository. Even after the disabling most of the entries under Available Software Sites things were still not working.
I had no proxy to worry about and even disabling the firewall (which I do not recommended) as a last resort did not help.
Viewing the error log, from the dialog box which Eclipse displayed, there was mention of a cache directory under .eclipse in my home directory. I deleted the two cache directories I found and Eclipse was working again.
For my setup the two directories I deleted were:
.eclipse/org.eclipse.platform_4.4.2_119745494_macosx_cocoa_x86_64/p2/org.eclipse.equinox.p2.core/cache
.eclipse/org.eclipse.platform_4.4.2_119745494_macosx_cocoa_x86_64/p2/org.eclipse.equinox.p2.repository/cache
NB: My setup is Eclipse Luna 4.4.2 running on Mac OS X Yosemite 10.10.3
A: In my case, I discovered that the major issue why my eclipse won't connect to internet is my Internet Service Provider. I was only able to browse some websites but unable to browse other website. Fixing the issue with the ISP worked.
A: My issue was the Eclipse Marketplace client needed updating.
After trying Fredriks solution of
Go to Window -> Preferences -> Install/update: Available Software sites. Then remove and add the indigo site. Just remember to copy the adress so you can add it again.
The Marketplace client wouldn't load. But I could access it via a browser.
So, I went to the Help -> Eclipse Marketplace
it loaded fine
Clicked on Installed and found the Eclipse Marketplace Client and it had so i clicked it it updated and then when I did the standard update everything worked.
A: Sometimes, there will be firewalls and restrictions in the network preventing the plugin to get downloaded. We can try some other network. This actually resolved my issue.
A: I was facing the issue while adding team explorer plugin to eclipse from https://marketplace.eclipse.org/content/team-explorer-everywhere.
Used team explorer plugin for ecplise for internal use of xamarin for mac.
Error:
unable to read repository at http://marketplace.eclipse.org/content/team-explorer-everywhere
org.eclipse.equinox.p2.core.provisionexception unable to read repository
Unknown host exception
Goto https://github.com/microsoft/team-explorer-everywhere/releases
Download: TFSEclipsePlugin-UpdateSiteArchive-14.135.0.zip
From Eclipse->Help->Install new software.
From Add Repository window select Archive select the downloaded zip file.
Continue installation.
A: No meu caso era o anti-vírus que estava bloqueando a conexão do eclipse, desativei o anti-víruse tudo funcionou o//.
Translation:
In my case it was the anti-virus that was blocking the connection from eclipse. I disabled the anti-virus and everything worked.
A: Also try if in the eclipse paths there is some duplicated
Luna - http://download.eclipse.org/releases/luna
Luna - http://download.eclipse.org/releases/luna/1234567...
Try both of them, one may work.
In my case, with 2 eclispes installed, in one of them the path
Luna - http://download.eclipse.org/releases/luna
works, in the other one, i must select:
Luna - http://download.eclipse.org/releases/luna/123456...
In both the internal browser can access to internet. Both are Luna (but one is RCM, the other one i don't remember).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
} |
Q: zend google fusion table update As anyone any idea on how to update a table in google fusion using Zend framework?
I can get the data:
$url = "https://www.google.com/fusiontables/api/query?sql=SELECT%20name%20FROM%201695591";
$data = $gdata->get($url);
$postcodes = $data->getRawBody();
But have no idea how to update a row ...
I know I have to 'call' this url, but no idea how :
UPDATE table_id
SET column_name = value {, column_name = value }*
WHERE ROWID = row_id
Thank you
A: Try this class http://barahlo.semero.com/description/Zend_Gdata_Fusion.zip
Example of usage:
$client = Zend_Gdata_ClientLogin::getHttpClient('[email protected]', 'your_pass_here', 'fusiontables');
$base = new Zend_Gdata_Fusion($client);
$sql = "SELECT ROWID FROM 596524 WHERE id = 1;";
$rowdata = $base->query($sql)->get_array();
print_r($rowdata);
$newRowId = $base->insertRow('596524',array(
'id' => time(),
'name' => 'trird row',
'added' => date('n/j/y'),
) );
$base->updateRow(
'596524',
array('name' => 'new first row'),
$rowdata[1][0] //ROWID from insert query
);
Oauth login for Zend_Gdata:
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => $CONSUMER_KEY,
'consumerSecret' => $CONSUMER_SECRET
);
$consumer = new Zend_Oauth_Consumer($oauthOptions);
$token = new Zend_Oauth_Token_Access();
$client = $token->getHttpClient($oauthOptions,null);
$base = new Zend_Gdata_Fusion($client);
// ...
Also, there is official php client library http://code.google.com/p/fusion-tables-client-php/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Encoding issue with WebView's loadData I'm loading some data, containing latin-1 characters, in a WebView using
String uri = Uri.encode(html);
webview.loadData(uri, "text/html", "ISO-8859-1");
When displayed, the latin1 characters are replaced by weird characters.
If I load the html directly in a TextView (just to test), latin characters are properly displayed.
Anybody can help?
Thanks
html:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- some html -->
</html>
A: I have display © 2011 and it was displaying ©.
With the below code i have achieved displaying correct value © 2011
webViewContent.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
A: myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
You should always use UTF-8 encoding. Every other character encoding has become obsolete for many years already.
A: Only way to have it working, as commented here:
webview.loadDataWithBaseURL("fake://not/needed", html, "text/html", "utf-8", "");
No URI encoding, utf-8... loadData bug?
A: String start = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /></head><body>";
String end = "</body></html>";
webcontent.loadData(start+ YOURCONTENT + end, "text/html; charset=UTF-8", null);
One of solution of problem.
A: webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
A: AFAIK that:
Firstly, loadData() method is used to load raw html code.
Secondly, just put the html code directly to the loadData(), don't encode it
You might wanna try like this:
webview.loadData(uri, "text/html", "ISO-8859-1");
Cheers!
A: I too had the problem of getting a weird character like  here and there. Tried different options, but the one that worked is below.
String style_sheet_url = "http://something.com/assets/css/layout.css";
String head = "<head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"" + style_sheet_url + "\" /></head>";
String locdata = "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + head + "<body>"+ data + "</body></html>";
wv_news_text.loadData(locdata, "text/html", "utf-8");
wv_news_text is the WebView.
A:
Info from Java docs about loadData method
Loads the given data into this WebView using a 'data' scheme URL.
Note that JavaScript's same origin policy means that script running in
a page loaded using this method will be unable to access content
loaded using any scheme other than 'data', including 'http(s)'. To
avoid this restriction, use loadDataWithBaseURL() with an appropriate
base URL.
The encoding parameter specifies whether the data is base64 or URL
encoded. If the data is base64 encoded, the value of the encoding
parameter must be 'base64'. For all other values of the parameter,
including null, it is assumed that the data uses ASCII encoding for
octets inside the range of safe URL characters and use the standard
%xx hex encoding of URLs for octets outside that range. For example,
'#', '%', '\', '?' should be replaced by %23, %25, %27, %3f
respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII
charset. If you need need to set a different charset, you should form
a 'data' scheme URL which explicitly specifies a charset parameter in
the mediatype portion of the URL and call loadUrl(String) instead.
Note that the charset obtained from the mediatype portion of a data
URL always overrides that specified in the HTML or XML document
itself.
Following code worked for me.
String base64EncodedString = null;
try {
base64EncodedString = android.util.Base64.encodeToString((preString+mailContent.getBody()+postString).getBytes("UTF-8"), android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(base64EncodedString != null)
{
wvMailContent.loadData(base64EncodedString, "text/html; charset=utf-8", "base64");
}
else
{
wvMailContent.loadData(preString+mailContent.getBody()+postString, "text/html; charset=utf-8", "utf-8");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Deploying Pyramid to dotcloud What is the proper way to deploy a Pyramid project to dotcloud?
The contents of wsgi.py:
import os, sys
from paste.deploy import loadapp
current_dir = os.path.dirname(__file__)
application = loadapp('config:production.ini', relative_to=current_dir)
I'm currently getting the following error.
uWSGI Error
wsgi application not found
A: This could indicate that wsgi.py could not be imported successfully.
You can check the following:
*
*output of dotcloud logs appname.servicename
*log into the service with dotcloud ssh appname.servicename, then go to the current directory, start python and see what happens if you try to do from wsgi import application
If that can help, here is a super-simple Pyramid app:
https://github.com/jpetazzo/pyramid-on-dotcloud
A: try this:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'hellodjango.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
http://docs.dotcloud.com/tutorials/python/django/
A: I was able to get pass the uWSGI Error error using :
import os
from paste.deploy import loadapp
current_dir = os.getcwd()
application = loadapp('config:production.ini', relative_to=current_dir)
I still had a path problem with the static files so I changed:
config.add_static_view('static', 'static', cache_max_age=3600)
to
config.add_static_view('<myapp>/static', 'static', cache_max_age=3600)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "surprising" constant initialization because of definition order When reading the slides about constexpr the introduction is about "surprisingly dynamic initialization with consts". The example is
struct S {
static const int c;
};
const int d = 10 * S::c;
const int S::c = 5;
Alas, the audio track is missing, so are the notes, so I can only guess what is meant here.
Is it corrrect that d is "surprisingly" initialized dynamically, because S::c is defined before d? That the declaration of S::c is before d is probably not enough, the compiler needs the complete definition, right?
That said, I suspect, that in the following example d would be initialized statically?
struct S {
static const int c;
};
const int S::c = 5;
const int d = 10 * S::c; // now _after_ defn of S::c
And to take the cake, in C++11, what would have to be constexpr for full static initialization? S::c, d or both?
A: In the first example, d is not initialized by a constant expression, because S::c is not
a non-volatile const object with a preceding initialization,
initialized with a constant expression
(see C++11 [expr.const]p2, bullet on lvalue-to-rvalue conversions), because the initialization of S::c does not precede the initialization of d. Therefore static initialization will be used for S::c (because it is initialized by a constant expression), but dynamic initialization can be used for d.
Since static initialization precedes dynamic initialization, d would be initialized to 50 by its dynamic initializer. The compiler is permitted to convert the dynamic initialization of d to static initialization, but if it does, it must produce the value that d would have had if every variable which could have used dynamic initialization had, in fact, used dynamic initialization. In this case, d is initialized to 50 either way. See C++11 [basic.start.init]p2 for more information on this.
There is no way to add constexpr to the first example to guarantee that static initialization is used for d; in order to do that, you must reorder the initializations. However, adding constexpr will produce a diagnostic for the first example, which will at least allow you to ensure that dynamic initialization is not used (you get static initialization or a compilation error).
You can update the second case to ensure that static initialization is used as follows:
struct S {
static const int c; // do not use constexpr here
};
constexpr int S::c = 5;
constexpr int d = 10 * S::c;
It is ill-formed to use constexpr on a variable declaration which is not a definition, or to use it on a variable declaration which does not contain an initializer, so const, not constexpr must be used within the definition of struct S. There is one exception to this rule, which is when defining a static constexpr data member of a literal, non-integral type, with the initializer specified within the class:
struct T { int n; };
struct U {
static constexpr T t = { 4 };
};
constexpr T U::t;
In this case, constexpr must be used in the definition of the class, in order to permit an initializer to be provided, and constexpr must be used in the definition of the static data member, in order to allow its use within constant expressions.
A: I believe that the rules laid out in 3.6.2 to determine when static initialization happens do not include the initialization for d, which is therefore dynamic initialization. On the other hand, S::c is indeed statically initialized (since 5 is a constant expression). Since all static initialization happens before dynamic initialization, you get the expected result.
To make d eligible for static initialization, it has to be initialized with a constant expression. This in turn forces you to write the S::c inline:
struct S { static constexpr int c = 5; };
const int d = S::c; // statically initialized
Note that the standard permits dynamic initialization to be replaced by static initialization, which is why reordering the two lines in your original example will cause the two different sorts of initialization. As TonyK points out, you can use array[d] in the static case, but not in the dynamic case, so you can check which one is happening. With the constexpr approach, you're guaranteed to have static initialization and you don't have to rely on optional compiler behaviour.
A: For static initialization one needs, roughly speaking, a constant-expression initializer.
To be a constant-expression, roughly speaking, a variable needs to be of a const type and have a preceding initialization with a constant-expression.
In the first example d's initializer is not a constant-expression, as S::c isn't one (it has no preceding initialization). Hence, d is not statically initialized.
In the second example d's initializer is a constant-expression, and everything is OK.
I'm simplifying matters. In full formal standardese this would be about nine times longer.
As for constexpr specifier, no object has to be declared constexpr. It is just an additional error-check. (This is about constexpr objects, not constexpr functions).
You may declare S::c constexpr in the second variant if you want some extra error protection (perhaps 5 will start changing its value tomorrow?) Adding constexpr to the first variant cannot possibly help.
A: You can find out whether a constant is statically or dynamically initialised by trying to declare an array:
struct S {
static const int c;
};
const int d = 10 * S::c; // (1)
const int S::c = 5; // (2)
static char array[d];
This code fails in g++ version 4.7.0, because d is dynamically initialised. And if you exchange (1) and (2), it compiles, because now d is statically initialised. But I can't find another way to fix it, using constexpr.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Flash as3 dragging Movieclips from Scrollpane component into a movieclip/stage Hi im new on this board hope you can help me.
Im trying to make a flash map game.Now i have got items in a Movieclip and want this Movieclip into a scrollpane component but i have got probs cause the dragging dont go outside of the scrollpane.
Here is my Code
container.mc_item.buttonMode = true;
container.mc_item.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(event:MouseEvent):void {
container.mc_item.startDrag();
}
container.mc_item.addEventListener(MouseEvent.MOUSE_UP, onUp);
function onUp(event:MouseEvent):void {
container.mc_item.stopDrag();
trace(container.mc_item.dropTarget.parent.name); // this is the command that tells us which area the mc_item was dropped on
}
container.scrollpane.source= container.mc_item;
Please help
I uploaded the source in cs4.
Would be great if you can make the each dynamic _mc in scrollpane dragable, to drag into the movieclip outside.
Is it possible to give each of the _mc in the scrollpane a label?
http://www.speedshare.org/download.php?id=5324318F11
Thanks
A: I think you either need to write your own scroll-pane component, or (easier I think), add some code so that when you start dragging the item in the list, you create a duplicate of the item instead (which is not added as a child to the scrollpane), and drag that instead. Don't forget to remove it when you drop it :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to run parallel applications (High Performance Computing) on google app engine? Has anyone used Google App Engine with a HPC application? is it possible to do parallelism? You can do parallelism (at least in theory) using java + threads, but how many threads can you get? how efficient is it?
A: When using Google App Engine, your program doesn't run in a complete JRE, but in a sandbox, which does not enable you to create new threads. Therefore, you can't just use java + threads.
But you can run some concurrent Backends, which are some instances "designed for applications that need faster performance, large amounts of addressable memory, and continuous or long-running background processes". These backends can be configured and are billable.
A: App Engine is designed primarily with serving scalable web applications in mind. While you could do HPC on it, it's not its design goal, so your experience is likely to be less than satisfactory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Understanding architecture and folder structure in Symfony2? I'm completely new to Symfony 2 and i can't really understand the folder structure and organization of a project. I know what a bundle is, but what is unclear to me is:
*
*what's the main directory (the directory to be copied on the web server for deployment)
*where assets (css, javascript) should be placed
*if (and how) environment should be changed when publishing my website
I've already read the book on Symfony website and i can't find those answers.
A: *
*The web root of a Symfony2 app is the 'web' directory, but when you push to production the entire symfony2 project should be pushed not just the web root.
From the symfony2 book
app/: This directory contains the application configuration;
src/: All the project PHP code is stored under this directory;
vendor/: Any vendor libraries are placed here by convention;
web/: This is the web root directory and contains any publicly accessible files;
*
*The assets should be kept in the bundles 'Resources/public/[css/js/images]' folders. From here you would have to copy or symlink those directories into the web root to make them accessible. Symfony2 comes with a command line utility located in the 'app' directory. app/console assets:install web --symlink command executed from the command line of your symfony2 project root will install all of the bundle's assets for you.
*To change environments and you are using Apache you would use a .htaccess file and mod_rewrite to select which environment you would want to use
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app.php [QSA,L]
using /app.php puts me into production mode and using /app_dev.php would put me in development mode.
A: *
*The main directory contains the app folder.
*The assets should be
placed in the bundles folder they're related to. This folder is named
"public".
*Read this. All you need to do is remove the app_dev.php file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ActionBar capacity/overflow not changing on orientation change I have an app using the ActionBar, where I handle orientation changes myself:
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
...and the menu should fit in the ActionBar without overflow in landscape, but not in portrait:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="@string/Game" android:id="@+id/game" android:icon="@android:drawable/ic_menu_manage" android:showAsAction="ifRoom|withText"/>
<item android:title="@string/Type" android:id="@+id/type" android:icon="@android:drawable/ic_menu_edit" android:showAsAction="ifRoom|withText"/>
<item android:title="@string/Other" android:id="@+id/other" android:icon="@android:drawable/ic_menu_gallery" android:showAsAction="ifRoom|withText"/>
<item android:title="@string/Solve" android:id="@+id/solve" android:icon="@android:drawable/ic_menu_directions" android:showAsAction="ifRoom|withText"/>
<item android:title="@string/Help" android:id="@+id/help" android:icon="@android:drawable/ic_menu_help" android:showAsAction="ifRoom"/>
</menu>
On startup, this works correctly:
Landscape:
Portrait:
(yes, I could force all items to always display and they would fit, as shown below, but that might break on a smaller tablet)
When the emulator changes orientation, the ActionBar's capacity doesn't seem to change:
Portrait, when I started in landscape:
(this is ok, but inconsistent)
Landscape, when I started in portrait:
This looks really silly and is the reason I want to fix this.
I added this call to invalidateOptionsMenu(), but it doesn't help:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
maybeMoveSomeViewsAround(newConfig);
super.onConfigurationChanged(newConfig);
invalidateOptionsMenu();
}
(Actually I call it by reflection for backward compatibility, but the debugger tells me it really is called and does not encounter an exception.)
invalidateOptionsMenu() actually ends up calling onCreateOptionsMenu() (which re-inflates the menu) before returning, and I can see inside the latter that getResources().getConfiguration().orientation has already changed. So this is really puzzling. If the options menu is being recreated, when the orientation has changed, it must be ActionBar itself caching the width?
Is there a way to re-create the ActionBar without destroying/creating the Activity? (because the latter is a bit expensive in my case)
Edit: Here's a minimal sample project showing the issue.
Edit 2: I had thought of checking the screen width and programmatically adjusting the showAsAction flags between always and never appropriately, but that requires knowing (or guessing) the width of each item. ActionBar's public API does not help me on that point.
A: I ran into this problem to and came up with a hack which works 100%.
I eneded up calling invalidateOptionsMenu() two times. Look at the code below:
private boolean hackActionBarReset = false;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//a hack to reset the items in the action bar.
hackActionBarReset = true;
invalidateOptionsMenu();
hackActionBarReset = false;
invalidateOptionsMenu();
}
And in your onCreateOptionsMenu() set this on you menuitems you want to show:
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT | (hackActionBarReset ? MenuItem.SHOW_AS_ACTION_NEVER : MenuItem.SHOW_AS_ACTION_IF_ROOM));
Not a pretty solution but it works.
A: I've cautiously worked around this: when the device's width is greater than 850dip, force showing all items in the ActionBar, otherwise continue to let the platform decide.
Here's the git commit. Edit: and the follow-up commit to fix using a field that's too new, oops. :-)
I'm definitely still interested in better answers (other than waiting for a fix to the platform).
A: I found that the simplest and most effective workaround was to clear the menu and then rebuild it.
For example:
Menu menu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
// Setup code goes here...
}
@Override
public void onOrientationChanged() {
if (menu != null) {
menu.close(); // Ensure the menu is closed before changing its contents.
menu.clear();
onCreateOptionsMenu(menu); // Rebuild the menu.
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Getting week started date using MySQL If I have MySQL query like this, summing word frequencies per week:
SELECT
SUM(`city`),
SUM(`officers`),
SUM(`uk`),
SUM(`wednesday`),
DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)
The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00
A: It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C: drive access permission in windows 7 In matlab, I used a windows standalone application. There is a line in this application that writes a file in C:\...\...\. When I run the output exe file produced from this windows standalone application, the exe doesn't write in C:\...\...\ neither tells me that there is a security issues in that partition. All the execution does is nothing. But, when I right-click and run the exe as administrator, it runs correctly.
I want to do it without right-click and run as administrator. Are there is a command in matlab that can do that?
A: If you create a shortcut to your application, you can go to the Properties of the shortcut, click on Advanced in the Shortcut tab, and select "Run as administrator". That way, whenever you start the application from the shortcut it will be run as an administrator.
(Disclaimer: applications really shouldn't "foul their own nest" by writing into Program Files. This is bad design.)
A: Starting from Vista, unprivileged processes are not allowed to write to protected folders such as Program Files, because Program Files is designed to store code and not data. However, since this limitation has not been enforced in XP, MS has provided a backward-compatibility hack in the form of Virtual Store. Now, when a program tries to write to protected folder, its output is being redirected into a dedicated folder. This way, the program still "thinks" it writes to its usual location, while in fact it writes to an unprotected location. However, when you later check the Program Files location, you might not see the file - because it's not really there.
You can find more details here: User Account Control Data Redirection.
A: If you are administrator, add full control permission for your username to the destination folder. You do that by right clicking on the folder, going to properties and then security tab. Then edit and add you username with Full Control rights. Then you don;t have to run the the program as an administrator.
A: There is no way you can elevate a process once it is started, so Matlab cannot possibly have a command for that. Just running Matlab elevated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update MYSQL and SET particular row Content I am trying to update my table t1 which has rows as following :-
*
*id
*menu
Currently i am having data in it as
id = "1"
menu = "menu1 ,menu2 ,menu3, menu4"
I am using explode method of PHP to get MENU row of my table t1.
$show_data = mysql_query("SELECT menu FROM t1");
$showrow = mysql_fetch_assoc($show_data);
$showmenu = $showrow['menu'];
$pieces = explode(",", $showmenu);
Now I want to delete content menu3 from row MENU ,
Please provide me which query should i use , UPDATE , ALTER or DELETE.
A: You should store your menus in a separate table, linked to this one by a unique identifier.
Then edit that table in the usual way.
A: It is better to separate $menu1 $manu2 $menu3 and $menu4
*
*You can implode() them as a single $string with \t separator
*and Insert it to Mysql.
*When nessesary,select the field from table
*explode() it to separate strings using \t separator
*remove the $menu3 variable frome being imploded this time
*again implode() them
*and UPDATE the field
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Pixel Loading and Evaluating with PIL I want to create a program that loads the RGB values of each pixel in a image and saves them in some kind of list/dictionary/tuple and then when I type in a value it tells me how much pixels in the image have that value. So far I have read through the whole PIL documentation trying to find a method that could fit my needs and I have tried several other approaches with for example the .getpixel() or the .load() function, but it is very difficult to save and evaluate that information for each pixel.
A: First, you will want to convert the image to the "RGB" mode, so that you always get (R, G, B) tuples for pixels, even for grayscale/monochrome images.
image = image.convert("RGB")
Then, iterate over getdata() to build your histogram.
colors = {}
for color in image.getdata():
colors[color] = colors.get(color, 0) + 1
Then, you can use get() to retreive the number of pixels of a given color
print colors.get((255, 255, 255), 0) # No. of white pixels
A: New in version 1.1.5 of PIL is the method getcolors() which should do exactly what you're looking for. The documentation from the PIL web documentation follows:
getcolors
im.getcolors() => a list of (count, color) tuples or None
im.getcolors(maxcolors) => a list of (count, color) tuples or None
(New in 1.1.5) Returns an unsorted list of (count, color) tuples,
where the count is the number of times the corresponding color occurs
in the image.
If the maxcolors value is exceeded, the method stops counting and
returns None. The default maxcolors value is 256. To make sure you get
all colors in an image, you can pass in size[0]*size[1] (but make sure
you have lots of memory before you do that on huge images).
A: .load() is the way to go. It works really efficiently and allows to get many pixels quickly.
width,height=image.size
px=image.load()
col={}
for y in range(height):
for x in range(width):
c=px[x,y]
col[c]=col.get(c,0)+1
# `col` will look like this: {(r,g,b):n,...}
A: I think that .getpixel() is exactly what you need — if you are going to be doing lots of lookups and you need speed, then loop over each image once, creating a dictionary of coordinates at which each color is found. Make it look like this:
{
(128,128,4): [(1,1), (1,2)],
(128,130,6): [(1,3)],
...
}
Of course, if it is really just the counts you need (you are building a histogram, then?), then just store an integer at each dictionary entry instead of the whole list of points.
If only the .histogram() method broke its results out by specific color — but it looks like it returns each channel separately, without regard for the combinations in which the various color components appear together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Zend_From Validator only if the field input has changed? I'm writing a Backend System and I want to allow the users to change their email address.
I've written a custom validator to check if the email-address the user has entered already exists in my database.
Now I ran into a problem: The form is populated with the user data, so his email address is the default value of the email field. Now if the user submits the form, my validators throws an error, because (of course) this email address does already exist!
How can I solve this problem? Maybe a Validator is not the right approach to do this?
Or is there a solution to detect if the user changed the default value and fire the validator only in that case?
A: Hehe, that's a common problem running into validators the first time. The key is to remove that one id from the validator, inside your validator exclude the current user ID from the clause:
$validator = new Zend_Validate_Db_NoRecordExists(
array(
'table' => 'users',
'field' => 'email',
'exclude' => array(
'field' => 'id',
'value' => $id_to_edit
)
)
);
Edit: for further explanation as to what this does. It still grabs all the email adresses from the database and it still checks if there's a misconflict. If an email exists, it just ignores the email from id=$id_to_edit - so when the user changes its email but another user has that email already, the error gets thrown anyways!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GWT - how to implement RequestContext methods outside an @Entity-annotated class? Is it possible to implement RequestContext methods outside an @Entity-annotated class?
@Entity
class TheEntity {
public static TheEntity theMethod() { ... } // don't want it here
}
@Service(TheEntity.class)
interface TheEntityRequest extends RequestContext {
Request<TheEntity> theMethod(); // this one
}
A: Yes, you can. This is mentioned in the official GWT documentation, though it's not very detailed.
I've found of great help this blog post by David Chandler.
Some pointers:
(example links are from the project discussed in the blog post)
Entity locator methods (find, create, getId, getVersion) can be moved in a generic Locator class (example). For this to work your entities must extend a BasicEntity class that has the getId and getVersion methods. Then on the client you would specify the locator like this:
@ProxyFor(value = MyEntity.class, locator = GenericLocator.class)
public interface MyEntityProxy extends EntityProxy {
...
}
Data access methods can be moved in a service. You can have a generic service (example), and then extend it for each entity to provide specific methods (example).
On the client you define your service like this:
// MyEntityDao is your server service for MyEntity
@Service(value = MyEntityDao.class, locator = MyServiceLocator.class)
interface MyEntityRequestContext extends RequestContext {
Request<List<MyEntityProxy>> listAll();
Request<Void> save(MyEntityProxy entity);
...
}
Note the need for a service locator also. It can be as simple as this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Form not being serialized? jquery and ajax I have a form that is submitted to a php script with jquery and ajax, but turning out blank in the php script.
form:
<table id="coachapplication">
<form id="coachapplicationform" action="" method="post">
<tr><td>Briefly explain your teaching methods:<br /> <textarea maxlength="100" name="coachmethods" id="coachmethods"></textarea></td></tr>
<tr><td><input type="checkbox" value="yes" name="agree" id="agree" /> I am fully prepared to take on the responsibilities of being a coach which include logging into the website daily and hosting sessions.
<tr><td><button id="submitcoachapplication" type="button">Submit</button></td></tr>
</form>
</table>
jquery script:
$('#submitcoachapplication').click(function() {
$.ajax({
type: "POST",
url: "includes/sendcoachapplication.php",
data: $("form#coachapplicationform").serialize(),
success: function(msg){
$("#coachapplication").html(msg);
}
});
});
php script:
<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
include("user.php");
$result = mysql_query("SELECT * FROM coachapplications ORDER BY username");
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
if($username == $user) die("You already have a pending application.");
}
$coachmethods = $_POST['coachmethods'];
$coachmethods = mysql_real_escape_string($coachmethods);
$agree = $_POST['agree'];
if($coachmethods == "") die("Please enter some info about how you intend to teach.");
if($agree != "yes") die(" Please agree to the terms.");
$sql="INSERT INTO coachapplications (username, methods) VALUES ('$user', '$coachmethods')";
if (!mysql_query($sql,$con)) die('Error: ' . mysql_error());
echo 'Your application has been submitted, and is awaiting admin approval. If you are found suitable for the program, you will be taught how to use the system.';
mysql_close($con);
?>
A: A <form> element is not allowed as a child of <table>. Your browser is likely error correcting by moving it outside the table, which would mean that the <input> elements are no longer inside it.
Put the <table> inside the <form>, not the other way around.
Better yet, don't use tables for layout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to properly add entries for computed values to the django internationalization messages file? Django documentation states:
The caveat with using variables or computed values, as in the previous
two examples, is that Django's translation-string-detecting utility,
django-admin.py makemessages, won't be able to find these strings.
That is fine with me, I'm ready to provide translations for all possible values of the translated variable by hand. But how to do that?
Let's say I have in my template code like this:
{% trans var %}
The var is extracted from the database, and I know all of the possible values of it - let's say the possible values are "Alice" and "Bob".
I thought all I need to do is provide entries like these:
msgid "Alice"
msgstr "Alicja"
in django.po file. Unfortunately, whenever i run djangoadmin makemessages after that, these entries are being commented out:
#~ msgid "Alice"
#~ msgstr "Alicja"
What am I doing wrong? Have I misunderstood the idea of translating computed values?
A: We're currently in the process of figuring this out as well. While we haven't done so properly, we do have a rather annoyingly ugly hack to get around it.
We simply define a "dummy" function somewhere in the code (for example your models.py or even settings.py) and fill it up with all the strings that we need to have a translation for.
from django.utils.translation import ugettext_lazy as _, pgettext
def dummy_for_makemessages():
"""
This function allows manage makemessages to find the forecast types for translation.
Removing this code causes makemessages to comment out those PO entries, so don't do that
unless you find a better way to do this
"""
pgettext('forecast type', 'some string')
pgettext('forecast type', 'some other string')
pgettext('forecast type', 'yet another string')
pgettext('forecast type', 'etc')
pgettext('forecast type', 'etc again')
pgettext('forecast type', 'and again and again')
This function is never called but simply defining it prevents the message strings from getting commented out by makemessages.
Not the most elegant solution but it works.
A: There is one nice way of doing this!
(I know, because I happened to work on the same code).
First of all - this value is computed somewhere. So, in your action, you may have:
context['var'] = 'good' if condition(request) else 'bad'
and later in the template:
{% if var == 'good' %}
{% trans "Congratulations, var equals: "}
{% else %}
{% trans "Oops, var equals: "}
{% endif %}
{% trans var %}
You may have different values, which can become impractical... Unless you use this trick:
_ = lambda x: x
context['var'] = _('good') if condition(request) else _('bad')
You need to make _ something local if you don't want to clash with ugettext_lazy, etc.
This way, you're not:
*
*translating prematurely
*using some lame "dummy" redundant function to "list" your translated strings
*messing up, and having to give up manage.py makemessages
A: I ended up solving it with a similar solution suggested in @StFS answer.
When I used pgettext('forecast type', 'some string'), then using {% trans varName %} in my template still returns "some string" instead of "New Text" for the translation.
So I have changed the syntax in the function to gettext('some string').
Now using {% trans varName %} would give "New Text" in my template.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: iOS - Unable to access NSMutableArray in didSelectRowAtIndexPath? I am unable to access my NSMutableArray in didSelectRowAtIndexPath although i am able to access it in cellForRowAtIndexPath.
Here is my code :-
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"];
self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSLog(@"%@", self.drinkArray);
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
NSLog(@"I am inside cellForRowAtIndexPath");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
NSDictionary *dict = [self.drinkArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dict objectForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[dict release];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DrinkDetails *detailViewController = [[DrinkDetails alloc] initWithNibName:@"DrinkDetails" bundle:nil];
// ...
// Pass the selected object to the new view controller.
//detailViewController.drink = [self.drinkArray objectAtIndex:indexPath.row];
NSLog(@"%@", self.drinkArray);
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
Sometime NSLog prints some stupid output and sometime it gives me an error "EXC_BAD_ACCESS".
Please take a look and check what is wrong with my code.
Any help would be appreciated.
Thanks.
A: You have one (really two) issues, but the main one is in your -cellForRowAtIndexPath: method:
[dict release];
Get rid of this line and it should work just fine.
The reason why this fixes your issue is because -objectAtIndex: simply returns a pointer to the requested object in memory, therefore you do not (and should not) send the -release message to that object because the NSArray obtained ownership of the object when it was inserted. Sending -release to this object reference effectively deallocates the object in memory and now this indice in the NSArray is pointing to garbage memory. BAD BAD BAD
The other issue is that you have a memory leak here:
self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
You are sending the -retain message to an object reference that you already have ownership of by way of sending -alloc. (This of course assumes that your @property has the retain setter modifier)
To fix this issue, simply send the -autorelease message to this instance:
self.drinkArray = [[[NSMutableArray alloc] initWithContentsOfFile:path] autorelease];
A: Don't release an object unless it was created with alloc or obtained with a method beginning with new or copy or explicitly retain'ed. (NARC)
In this case:
NSDictionary *dict = [self.drinkArray objectAtIndex:indexPath.row];
was not returned retained so you do not have ownership and should not release it.
By the same token:
self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
is alloc'ed so it needs to be released or obtained with a convince method that will return an autoreleased object:
self.drinkArray = [NSMutableArray arrayWithContentsOfFile:path];
A: You shouldn't [dict release]in cellForRowAtIndexPath. objectAtIndex does not retain it, so it may be sweeped out of your array when you release it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Estimated size of the self-join operation on a relation R, given a histogram for R Query optimizers typically use summaries of data distributions to estimate the sizes of the intermediate tables generated during query processing. One popular such summarization scheme is a histogram, whereby the input range is partitioned into buckets and a cumulative count is maintained of the number of tuples falling in each bucket. The distribution within a bucket is assumed to be uniform for the purposes of estimation.
The following shows one such histogram for a relation R on a discrete attribute a with domain [1..10]:
Bucket 1: range = [1..2] Cumulative tuple count = 6
Bucket 2: range = [3..8] Cumulative tuple count = 30
Bucket 3: range = [9..10] Cumulative tuple count = 10
What is the estimated size of the self-join operation R x R
A) 46
B) 218
C) 248
D) 1,036
E) 5,672
Answer given in solutions : B
How is the answer to be calculated?
A: The size of a self-join on attribute R is equal to the summation of the frequency of each value of attribute R.
Here the frequency is given in buckets, e.g. the first bucket has 2 values r with frequency = 6, so we can assume the frequency of each value in bucket one is frequency = 3, similarly for bucket two frequency of each = 30/6 = 5, and for bucket three frequency of each value = 10/2 = 5.
Therefore, the size is
Size = [(3^2)*2] + [(5^2)*6] + [(5^2)*2]
= 218
A: I've been trying to figure this one out myself (it's from the GRE Computer Science subject test preparation exam).
So far I haven't found an answer as to why the answer is 218, but I have found a connection between the numbers given and the correct answer.
It turns out that that sum of the square of the cumulative tuple counts divided by the number of discrete values in each bucket, you get 218. Less abstractly: 6²/2 + 30²/5 + 10²/2 = 218.
It's not an answer, but at least there's a connection =)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Retrieving the image name from a powerpoint file I need to retrieve the image file name from an image in a pptx file. I already got the stream from the image but i didn't got the name of the image file... Here is my code:
private static Stream GetParagraphImage(DocumentFormat.OpenXml.Presentation.Picture picture, DocumentFormat.OpenXml.Packaging.PresentationDocument presentation, ref MyProject.Import.Office.PowerPoint.Presentation.Paragraph paragraph)
{
// Getting the image id
var imageId = picture.BlipFill.Blip.Embed.Value;
// Getting the stream of the image
var part = apresentacao.PresentationPart.GetPartById(idImagem);
var stream = part.GetStream();
// Getting the image name
var imageName = GetImageName(imageId, presentation);
/* Here i need a method that returns the image file name based on the id of the image and the presentation object.*/
// Setting my custom object ImageName property
paragraph.ImageName = imageName;
// Returning the stream
return stream;
}
Anyone knows how i can accomplish this ?
Thanks!!
A: There are in fact two file names for a picture/image in a pptx file:
If you need the file name of the image as it is embedded in the pptx file
you can use the following function:
public static string GetEmbeddedFileName(ImagePart part)
{
return part.Uri.ToString();
}
If you need the orignial file system name of your image you can use the following function:
public static string GetOriginalFileSystemName(DocumentFormat.OpenXml.Presentation.Picture pic)
{
return pic.NonVisualPictureProperties.NonVisualDrawingProperties.Description;
}
BEGIN EDIT:
Here is a complete code example:
using (var doc = PresentationDocument.Open(fileName, false))
{
var presentation = doc.PresentationPart.Presentation;
foreach (SlideId slide_id in presentation.SlideIdList)
{
SlidePart slide_part = doc.PresentationPart.GetPartById(slide_id.RelationshipId) as SlidePart;
if (slide_part == null || slide_part.Slide == null)
continue;
Slide slide = slide_part.Slide;
foreach (var pic in slide.Descendants<DocumentFormat.OpenXml.Presentation.Picture>())
{
string id = pic.NonVisualPictureProperties.NonVisualDrawingProperties.Id;
string desc = pic.NonVisualPictureProperties.NonVisualDrawingProperties.Description;
Console.Out.WriteLine(desc);
}
}
}
END EDIT
Hope, this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: On converting a Short to a Byte what goes on? I'm new to Java, from PHP, so spending some time/effort understanding types. Then I came across this:
Byte bb = new Byte("127");
System.out.println(bb.byteValue());
Short ss = new Short("32727");
System.out.println(ss.shortValue());
System.out.println(ss.byteValue());
Outputs 127, 32727 and -41 ?
Can someone explain to me how it arrived at -41 when the Short 32727 is represented as a byte?
A: The binary representation of 32727 is 0111111111010111. The byteValue() of that is just the smallest 8 bits, so 11010111
11010111 is negative since it begins with a 1.
Taking the Two's complement (complement each bit and then add one) gives 101001 which is 2^5 + 2^3 + 2^0 = 32+8+1 = 41
So we have -41.
A: Java only knows signed types. When you truncate 32727 to 8 bits (i.e. modulo 256), you get 215, which is -41 when interpreted as a signed 8-bit number (215 + 41 = 256 = 28).
The choice of making the Byte type signed has caused plenty of criticism, since it adds a lot of subtlety to basic serialization operations, for which people generally prefer the int type for this very reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: google.zxing barcode generator in iReport I want put a barcode in my page and can preview it. The barcode generator is google.zxing and my reporting tool is iReport.
But i dont know, how to configure Image Expression and Expression Class of an image in iReport.
A: The two key ideas are first to write a bit of Java code to create the relevant image and then to design the report to reference this code appropriately. Perhaps the simplest way to generate the image is in a scriptlet like this:
package com.jaspersoft.alliances.mdahlman;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;
public class QRCodeScriptlet extends JRDefaultScriptlet {
public void afterDetailEval() throws JRScriptletException {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(getFieldValue("barcode_text").toString(), BarcodeFormat.QR_CODE, 256, 256);
this.setVariableValue("BarCodeImage", MatrixToImageWriter.toBufferedImage(matrix) );
} catch (WriterException e) {
e.printStackTrace();
}
}
}
That's full of hard-coded ugliness, but the key ideas are all shown. Then you need to define the report like this:
*
*Sample query: select 'some text' as barcode_text
I included this only to reinforce the point that my scriptlet hard-codes the field name barcode_text. (This is bad.)
*Variable: BarCodeImage of type java.awt.image.BufferedImage with calculation System.
This name is hard-coded in the scriptlet too. (This is equally bad.)
*Add to iReport's classpath:
*
*The compiled scriptlet .jar file
*core.jar (from ZXing)
*javase.jar (from ZXing)
*Add an Image element to the report with Expression $V{BarCodeImage}.
The result is a happy happy QR-code in your generated JasperReport:
I recall a sample that I have seen which does things much more cleanly. It actually included a nice plug-in so you could easily install this functionality into iReport with minimal effort. If I can track that down, then I'll update this post. But until then this at least covers all of the critical points.
A: The image expression should return any subclass of java.awt.Image. The easiest way to achieve this is to use your own helper class to generate the Image. You can create a static method that generates a barcode from a Stringand call that method from IReport.
In the case of ZXing I don't know the method to use, but I can tell what I use as ImageExpression using the Barbecue library.
net.sourceforge.barbecue.BarcodeImageHandler.getImage(
MyBarcodeGenerator.getFromString($F{field})
MyBarcodeGenerator class contains the method getFromString(...) that returns a net.sourceforge.barbecue.Barcode in my case a net.sourceforge.barbecue.linear.code39.Code39Barcode
The Expression Class is ignored.
--Edited:
To encode an Image in zxing you should use MatrixToImageWriter
The following code will encode a QRCode into a BufferedImage which you can use in the Image Expression field:
MatrixToImageWriter.toBufferedImage(new QRCodeWriter().encode("BARCODE CONTENT", BarcodeFormat.QR_CODE, 400 /*Width*/, 400/*Height*/));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: JSF List Converter How do I write a converter for a list of items of class A in JSF2? I have written a converter for class A, but the items show up using the default toString() function: "A@hashcode".
I need to use a converter rather than a backing bean method so that validation can take place (Hibernate Validator).
more info
This is how I use the list:
<h:inputText id="destinations" value="#{rule.destinations}" converter="gr.panayk.vinyls.Destination"/>
Where #{rule.destinations} is of List<Destination> type. I am expecting a comma separated list of converted Destinations.
solution
I attach the List converter that BalusC proposed.
@FacesConverter(value="gr.panayk.vinyls.converter.DestinationList")
public class DestinationListConverter implements Converter
{
@Override
public Object getAsObject(final FacesContext context, final UIComponent component, final String values)
{
final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
final List<Destination> result = new ArrayList<Destination>();
for (String value : values.split(",", -1))
{
final String trimmedValue = value.trim();
final Set<ConstraintViolation<Destination>> violations = validator.validateValue(Destination.class, "data", trimmedValue);
if (!violations.isEmpty())
{
throw new ConverterException(new FacesMessage(violations.iterator().next().getMessage()));
}
result.add(new Destination(trimmedValue));
}
final Set<ConstraintViolation<Rule>> violations = validator.validateValue(Rule.class, "destinations", result);
if (!violations.isEmpty())
{
throw new ConverterException(new FacesMessage(violations.iterator().next().getMessage()));
}
return result;
}
@Override
public String getAsString(final FacesContext context, final UIComponent component, final Object value)
{
if (value instanceof List<?>)
{
final StringBuffer result = new StringBuffer();
final List<?> list = (List<?>) value;
for (int i = 0; i < list.size()-1; i++)
{
if (list.get(i) instanceof Destination)
{
result.append(((Destination) list.get(i)).getData());
result.append(", ");
}
else
{
throw new IllegalArgumentException( "Cannot convert " + value + " object to Destination in DestinationConverter." );
}
}
if (!list.isEmpty())
{
if (list.get(list.size()-1) instanceof Destination)
{
result.append(((Destination) list.get(list.size()-1)).getData());
}
else
{
throw new IllegalArgumentException( "Cannot convert " + value + " object to Destination in DestinationConverter." );
}
}
return result.toString();
}
else
{
throw new IllegalArgumentException( "Cannot convert " + value + " object to List in DestinationConverter." );
}
}
}
A:
I have written a converter for class A, but the items show up using the default toString() function: "A@hashcode".
That can happen if you didn't explicitly declare the converter on the component. In for example <h:selectManyCheckbox> and <h:selectManyListbox> explicitly declaring the converter is mandatory as all JSF/EL knows is that the value is of type List, not List<A> (generic types are lost during runtime). If you don't declare a converter, then the values will be treated as String (as that's what HTML output and HTTP request parameter values default to).
E.g.
<h:selectManyCheckbox converter="aConverter">
with
@FacesConverter(value="aConverter", forClass=A.class)
public class AConverter implements Converter {
// ...
}
Explicitly declaring the above converter is not necessary when you're using single-item inputs like <h:selectOneMenu> as the forClass would match it anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Storyboard to alternate Opacity between two controls I'm trying to come up with a XAML based StoryBoard that alternates the opacity between two Label controls.
e.g.
Label1 and Label2. When the window loads, Label2 has the Opacity set to 0 by default.
I want to achieve something like:
Label1 = Opacity 1 (pause for 10 seconds)
Fade Label1 Out
When Label1 is Opacity 0, fade in Label2 (pause for 10 seconds again)
Fade Label2 out
Then loop this.
I've tried using Storyboard Repeats, AutoReverse and DataTriggers bound to between the two Labels but I just can't seem to get it to function this way.
A: You can use a key frames animation for each label, something like that
<Label Content="LABEL1" Name="Label1">
<Label.Triggers>
<EventTrigger RoutedEvent="Label.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" RepeatBehavior="Forever">
<LinearDoubleKeyFrame Value="1" KeyTime="0:0:10"></LinearDoubleKeyFrame>
<LinearDoubleKeyFrame Value="0" KeyTime="0:0:11"></LinearDoubleKeyFrame>
<LinearDoubleKeyFrame Value="0" KeyTime="0:0:22"></LinearDoubleKeyFrame>
<LinearDoubleKeyFrame Value="1" KeyTime="0:0:23"></LinearDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Label.Triggers>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: web development e-mail protection Currenty, web sites gives generic messages to the users on invalid login attemps such as:
The username or password you entered is not valid
to protect e-mails from spammers. However, I read somewhere that this is not enough because sign up forms will warn user if the e-mail address is already taken. Therefore spammers can find valid e-mails by trying to fill registration forms not login forms.
The question: how can we prevent this? Is there a good way of handling this situation?
A: One quite nice way to prevent brute forcing is to add an increasing delay before checking.
A fairly good way is to add a 1 second delay before showing the error implying that the email is taken, then double that to 2 seconds, then 4 then 8 etc for the user. You could max this out at 16 seconds, or block the IP for 10 minutes after this for instance.
This way, real users get a 1, 2 or 4 second delay (not much), but bruteforcing becomes too laborious.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a property with known and fixed values for a user-defined button? I have a user-defined button, and it may have a Style property which I choose in properties window a value for it and depending on that value its Image and style will change.
How can I make this property to have some predefined and fixed values in a drop down list in properties window? and selecting a value causes running a method
-details:
this button may gets specified appearance such pause and play styles. so I made a class for styles:
// style of the button; pause, play, reset, etc
public abstract class ButtonStyle
{
public abstract Image GetImage();
}
// inherited classes of class ButtonStyle
public class PauseButtonStyle : ButtonStyle
{
public override Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PauseButton;
}
}
public class PlayButtonStyle : ButtonStyle
{
public override Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PlayButton;
}
}
And there is a method in the button for setting the specified style (pause,play,...):
public void SetStyle(ButtonStyle style)
{
button1.Image = style.GetImage();
}
Now how can I have a property for this custom button in properties window that this property has some default values like pause, play,etc and selecting it causes changing the button's style (with running SetStyle method)
A: I would make an enum and expose that as the Style property. Then, have a internal dictionary that keys off the enum value to choose the appropriate ButtonStyle object to pass to your SetStyle method.
A: I think all you need to do is inherit the Button class and add your Enum:
public class ButtonEx : Button
{
public enum ButtonStateStyles
{
None,
Pause,
Play,
}
private ButtonStateStyles _ButtonStateStyle = ButtonStateStyles.None;
public ButtonStateStyles ButtonStateStyle
{
get { return _ButtonStateStyle; }
set
{
_ButtonStateStyle = value;
switch (_ButtonStateStyle)
{
case ButtonStateStyles.Pause:
{
base.Image = new PauseButtonStyle().GetImage();
break;
}
case ButtonStateStyles.Play:
{
base.Image = new PlayButtonStyle().GetImage();
break;
}
default:
{
base.Image = null;
break;
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Comparison of Strings
Possible Duplicate:
How do I compare strings in Java?
Am I am comparing strings in the wrong way? Please show me how to compare correctly?
Thanks.
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
String selectedVal = (String) jList1.getSelectedValue();
AbstractListModel model = (AbstractListModel) jList1.getModel();
int numberElements = model.getSize();
final String[] allElements = new String[numberElements + 1];
for (int i = 0; i < numberElements - 1; i++) {
String val = (String) model.getElementAt(i);
***if (selectedVal != val)*** {
allElements[i] = (String) model.getElementAt(i);
}
}
controller.deleteButtonClicked(selectedVal);
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = allElements;
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
A: You need to use:
selectedVal.equals( val )
!= / == only checks the reference.
A: Remember that the string construct "foo" is a syntactic convenience, but is really equivalent to:
char[] foo = {'f', 'o', 'o'}
new String(foo)
So the first time I type "foo" I get a new (anonymous) object of the String class and the second time I type "foo", I get a new (anonymous) object of the String class. As long as you keep that in your head, you'll remember what user968951 explained, and that is that "==" will only tell you that "foo" and "foo" are two different objects. The String class overloads "equals" so that it returns true if the characters constructing the two different String objects are the same.
"foo" == "foo" returns false because these are two different objects (that they are Strings doesn't matter to "==")
"foo".equals("foo") returns true because these are two different String objects but with the same character sequence
Remember too that objects of the String class (including anonymous objects like String literals) are not mutable, that is, they can't be changed once created. Changing a String means throwing it away and creating a new one, every time.
So the expression "foo"+"bar" does not add "bar" to "foo", but creates a "foo" String object, creates a "bar" String object, then creates a third String object that stores the result of concatenating "foo" and "bar", then gives over "foo" and "bar" to be garbage collected. If you were forced to type new String "foo" and new String "bar" and new String result, and so on, you'd probably give some thought to how expensive your code was in terms of object creation. String literals are a bit deceptive that way.
You can look at StringBuffer and StringBuilder for classes that manipulate String-like objects that can be altered instead of being thrown away and replaced with new objects with every manipulation. Honestly, though, most people just use String literals and let the garbage collector get a workout.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Comparing multiple very large csv files against each other I have n csv files which I need to compare against each other and modify them afterwards.
The Problem is that each csv file has around 800.000 lines.
To read the csv file I use fgetcsv and it works good. Get some memory pikes but in the end it is fast enough. But if I try to compare the array against each other it takes ages.
One other Problem is that I have to use a foreach to get the csv data with fgetcsv because of the n amount of files. I end up with one ultra big array and can't compare it with array_diff. So i need to compare it with nested foreach loops and that take ages.
a code snippet for better understanding:
foreach( $files as $value ) {
$data[] = $csv->read( $value['path'] );
}
my csv class use fgetcsv to add the output to the array:
fgetcsv( $this->_fh, $this->_lengthToRead, $this->_delimiter, $this->_enclosure )
Every data of all the csv files are stored in the $data array. This is probably the first big mistake to use only one array, but I have no clue how to stay flexible with the files without to use an foreach. I tried to use flexible variable names but I stucked there as well :)
Now I have this big array. Normally if I try to compare the values against each other and to find out if the data from file one exists in file two and so on, I use array_diff or array_intersect. But in this case I have only this one big array. And as I said, to run an foreach over it takes ages.
Also after only 3 files I have an array with 3 * 800.000 entries. I guess latest after 10 files my memory will explode.
So is there any better way to use PHP to compare n amount of very large csv files?
A: Use SQL
*
*Create a table with the same columns as your CSV files.
*Insert the data from the first CSV file.
*Add indexes to speed up queries.
*Compare with other CSV files by reading a line and issuing a SELECT.
You did not describe how you compare n files, and there are several ways to do so. If you just want to find the line that are in A1 but not in A2,...,An, then you'll just have to add a boolean column diff in your table. If you want to know in which files a line is repeated, you'll need a text column, or a new table if a line can be in several files.
Edit: a few words on performance if you're using MySQL (I do not now much about other RDBMS).
Inserting lines one by one would be too slow. You probably can't use LOAD DATA unless you can put the CSV files directly onto the DB server's filesystem. So I guess the best solution is to read a few hundreds of lines in the CSV then send a multiple insert query INSERT INTO mytable VALUES (..1..), (..2..).
You can't issue a SELECT for each line you read in your other files, so you'd better put them in another table. Then issue a multiple-table update to mark the rows that are identical in the tables t1 and t2: UPDATE t1 JOIN t2 ON (t1.a = t2.a AND t1.b = t2.b) SET t1.diff=1
Maybe you could try using sqlite. No concurrency problems here, and it could be faster than the client/server model of MySQL. And you don't need to setup much to use sqlite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to call a method of a locked object from another thread? when thread 1 has the intrinsic lock of an object because of
synchronized(object) {
...
}
is it possible to call
object.method()
from thread 2 or not respectively do I need to type
synchronized(object) {
object.method();
}
in thread 2 to prevent it from calling the method while thread 1 is holding the lock?
In my case I got ConcurrentModificationExceptions while iterating over a Map and I tried to prevent modifications from other threads by locking the map. And I know that often the reason for ConcurrentModificationExceptions is that the map is changed during iteration but I'm quite sure that this is not the case in my case because there are only "get"-statements and one method call in the iteration, so there can't happen any modification.
Thanks in advance.
Binabik
A: Synchronization in Java is entirely co-operative - if the second thread doesn't choose to try to acquire the monitor (and if there's nothing in the method which tries to do so) then it won't automatically lock.
It's not that the object "is locked" - it's that one thread owns the lock associated with the object. The object itself can still be accessed; if it doesn't need the lock, it won't block.
Note that you can get a ConcurrentModificationException even within a single thread if you try to iterate over it and change it within the same loop, e.g.
// Not safe: will throw an exception
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().equals("foo")) {
map.put("bar", "Hello");
}
}
It's possible that this is what's going on in your code, but we can't tell as you haven't shown us any code. If you can present a short but complete program demonstrating the problem, we're much more likely to be able to work out what's going on.
A: When you acquire a lock, it only prevents other threads from acquiring the same lock. It does not lock the object as such and you can access its methods.
If you got a ConcurrentModicationException, then you have a concurrent modification. If you don't know where this is happening, you need to investigate further.
A: Unless object.method() is synchronized you can call it from an other thread. You have to be careful when using a iteration over a non-synchronized map. You should use a synchronzied map and synchronize over the iteration; otherwise you have to synchronize all write actions as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laying out divs of different heights in a grid I have a site that I'd like to layout like this image:
Red is the desktop version and yellow is the mobile version. I can easily switch between the two using media queries.
My problem is how to write the CSS for the desktop version - I only include the mobile version because the layout precludes some layout techniques for the desktop version.
The content within each pair (e.g. A and B) can be of different heights, but they're similar enough that I'd like to lay them out as equal heights so the next pairs headers line up.
The easiest way I guess is to hardcode the heights for each pair, but I'd rather avoid that if possible.
A: You should use a container for those elements.
for example a <ul> and the elements themselves be <li> elements.
example html
<ul class="container">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
</ul>
desktop CSS
ul.container li{
width:45%;
margin-right:5%;
float:left;
}
ul.container li:nth-child(odd){
clear:left;
}
mobile CSS
ul.container li{
width:100%;
}
Demo at http://jsfiddle.net/gaby/AgNjB/1
notice
The above code works if you only want to line-up their headers (the left and right tops are at the same place). But it will need alterations if you want their actual height to line up as well (for a bottom border for instance)..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CC-Mode 5.32.1 with Latest Emacs I'm trying cc-mode 5.32.1 with Emacs trunk. When I compile I get these errors
cc-mode.el:596:29:Error: Symbol's function definition is void: byte-compile-obsolete
Compiling file /home/per/pnw/emacs/cc-mode-5.32.1/cc-styles.el at Sun Oct 2 12:28:53 2011
cc-styles.el:654:29:Error: Symbol's function definition is void: byte-compile-obsolete
Load completes without erros but I when I try to edit in my new version of c-mode I get these errors:
Error during redisplay: (void-function buffer-syntactic-context) [2 times]
byte-code: End of buffer [3 times]
ad-Orig-c-indent-line: Wrong type argument: listp, cc-bytecomp-ignore-var:c-syntactic-contextError during redisplay: (void-function buffer-syntactic-context) [2 times]
c-in-literal: Symbol's function definition is void: buffer-syntactic-context
ad-Orig-c-indent-line: Wrong type argument: listp, cc-bytecomp-ignore-var:c-syntactic-contextError during redisplay: (void-function buffer-syntactic-context)
c-in-literal: Symbol's function definition is void: buffer-syntactic-context
ad-Orig-c-indent-line: Wrong type argument: listp, cc-bytecomp-ignore-var:c-syntactic-contextError during redisplay: (void-function buffer-syntactic-context)
c-in-literal: Symbol's function definition is void: buffer-syntactic-context [2 times]
Is there an easy way out of this problem or should I wait for the emacs developers to fix this. I know quit a lot about Emacs-Lisp but this problem beats me.
Maybe a hint: When I lookup buffer-syntactic-context i get
buffer-syntactic-context is an alias for `cc-bytecomp-ignore-fun:buffer-syntactic-context',
which is not defined. Please make a bug report.
A: This has been fixed in CC-Mode version 5.32.2 meaning it's now compatible with Emacs trunk. Thanks Alan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery Ajax FileUploader & asp.net I am trying to create a File Uploader with progress bar with Asp.net + Jquery.
important thing is I do not have a MVC webpage.
I have followed the instructions here:
http://blog.stevensanderson.com/2008/11/24/jquery-ajax-uploader-plugin-with-progress-bar/
However It just skips over the whole handler I need to create..
so far I have:
<script src="../../Scripts/swfupload.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-asyncUpload-0.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#yourID").makeAsyncUploader({
upload_url: "/Controls/UploadHandler.ashx", // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database).
flash_url: '../../Scripts/swfupload.swf',
button_image_url: '../../Scripts/blankButton.png'
});
});
</script>
and it all works as it should. However it obviously doesn't upload because I don't have a handler.. But I have no idea where to start with a ASHX handler..
I have tried unsuccessfully searching the net. Can someone point me in the right direction how to create this handler?
A: I sorted it
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string strLocation = context.Server.MapPath("~/SaveFile") + "/" + strFileName;
context.Request.Files[0].SaveAs(strLocation);
context.Response.ContentType = "text/plain";
context.Response.Write("OK");
}
public bool IsReusable {
get {
return false;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the bluetooth connection time out in mobile/j2me? Im developing a mobile application in j2me.In my application i connect the mobile with some other device with respect to bluetooth.After connection established i send the command from the mobile to that other device to perform some operations via bluetooth.
Here i does not know how long bluetooth connection remains.Im using javax.bluetooth package.
So please tell me how long (with respect to seconds/minutes,etc) bluetooth connection is remains after connection establishment,Or is there is any bluetooth connection time out in mobile/j2me.H
Here im using nokia s40 series is my targetted device in mobile side.
Im fresh to bluetooth technology.So please forgive my mistakes in the questions.All of them are welcome to provide their ideas.
Thanks and regards,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 2.3/3.1 TimeZone calculation/parsing performace gap Why does this code
500.times { Time.now.in_time_zone('Helsinki') }
take several seconds with Rails 3.1 while it takes only a split second in Rails 2.3 (both with Ruby 1.9.2-p290)?
I discovered this by searching for a cause for an extremely slow loading page after upgrading from Rails 2.3 to 3.1.
Any ideas? Also, how to fix it? Haven't found a workaround yet.
A: Okay, this was an issue in TZInfo and has been fixed now in the Rails 3.1.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Approaches to implement macro definitions in html I would be great doing things like
<define tag="myTag" options="3">
<h1> #1 </h1>
<ul>
<li> #2
<li> #3
</ul>
</define>
and then use it:
<myTag option="foo" option="bar" option="bean" />
I regard macros as
really big advantage.
A work-around is using a macro processor like m4, or using php to simulate the macros efect. Any other technique to consider?
A: Perhaps obvious, but the C preprocessor can do the job.
index._html
#define _em(a) <em> a </em>
#define _image(a, b) <img src="a" b/>
#define _list(a, b, c) <h1> a </h1> \
<ul> \
<li> b </li> \
<li> c </li> \
</ul>
<!-- ___________________________________________________ -->
<!doctype html>
<html>
#define _theTile The Bar Title
#include "head._html"
<body>
_list(foo, bar, bean)
This is really _em(great)
_image(media/cat.jpg, )
_image(media/dog.jpg, width="25%" height="10px")
</body>
</html>
Being head._html
<head>
<meta charset="utf-8"/>
<title> _theTile </title>
<!-- more stuff ... -->
</head>
Then,
cpp -P index._html > index.html
produces:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> The Bar Title </title>
<!-- more stuff ... -->
</head>
<body>
<h1> foo </h1> <ul> <li> bar </li> <li> bean </li> </ul>
This is really <em> great </em>
<img src="media/cat.jpg" />
<img src="media/dog.jpg" width="25%" height="10px"/>
</body>
</html>
A: If you want to do it in the text-editor level, consider using Zen Coding.
A: In javascript
<!doctype html>
<html>
<script>
function em(a) {
var text = " <em> $a </em>".replace("$a", a);
document.write(text);
}
function image(a, b) {
var text = '<img src="$a" $b />'.replace("$a", a).replace("$b", b);
document.write( text );
}
function list(a, b, c) {
var text = '<h1> $a </h1> \
<ul> \
<li> $b </li> \
<li> $c </li> \
</ul>'
.replace("$a", a).replace("$b", b).replace("$c", c);
document.write (text);
}
</script>
<body>
<p>
<script> list("foo", "bar", "bean") </script>
<p> This is really <script> em("great") </script>
<p>
<script> image ("prosper.jpg", 'width="35%"') </script>
</body>
</html>
Pros: no prepocessing needed.
Cons: A bit annoying (always write <script> </script>). No direct way to include external html (afaik).
A: Now with php:
<!-- index.php -->
<?php
function list_($a, $b, $c) {
echo "
<h1> $a </h1>
<ul>
<li> $b </li>
<li> $c </li>
</ul>
";
}
function em($a) {
echo "<em> $a </em>";
}
function image($a, $b) {
echo "<img src=\"$a\" $b/>";
}
?>
<!doctype html>
<html>
<?php
$theTitle='The Bar Title';
include 'head.php';
?>
<body>
<? list_(foo, bar, bean) ?>
This is really <? em(great) ?>
<? image('media/cat.jpg', '' ) ?>
<? image('media/dog.jpg', 'width="25%" height="10px"') ?>
</body>
</html>
<head>
<meta charset="utf-8"/>
<title> <? echo "$theTitle"; ?> </title>
<!-- more stuff ... -->
</head>
Then
$ php index.php > index.html
gives
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> The Bar Title </title>
<!-- more stuff ... -->
</head>
<body>
<h1> foo </h1>
<ul>
<li> bar </li>
<li> bean </li>
</ul>
This is really <em> great </em>
<img src="media/cat.jpg" />
<img src="media/dog.jpg" width="25%" height="10px"/>
</body>
</html>
A: I've written a single-class, zero-installation macro system aimed straight at HTML coding. You'll find it here:
aa_macro.py
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Cannot write text as UTF-8 to file using python I am working on a program that reads a downloaded webpage (stored as 'something'.html) and parses it accordingly. I am having some trouble getting the encoding and decoding correct for this program. It's my understanding most webpages are encoded in ISO-8859-1 and I checked the response from this page and that is the charset I was given:
>>> print r.info()
Content-Type: text/html; charset=ISO-8859-1
Connection: close
Cache-Control: no-cache
Date: Sun, 20 Feb 2011 15:16:31 GMT
Server: Apache/2.0.40 (Red Hat Linux)
X-Accel-Cache-Control: no-cache
However, in the meta tags of the page it declares 'utf-8' as it's encoding set:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
So, in python I've tried a number of approaches to read these pages, parse them, and write utf-8 including reading the file in normally and writing normally:
with open('../results/1.html','r') as f:
page = f.read()
...
with open('../parsed.txt','w') as f:
for key in fieldD:
f.write(key+'\t'+fieldD[key]+'\n')
I have tried explicitly telling the file which encoding to use during the read & write process:
with codecs.open('../results/1.html','r','utf-8') as f:
page = f.read()
...
with codecs.open('../parsed.txt','w','utf-8') as f:
for key in fieldD:
f.write(key+'\t'+fieldD[key]+'\n')
Explicitly telling the file to read from 'iso-8849-1' and write to 'utf-8':
with codecs.open('../results/1.html','r','iso_8859_1') as f:
page = f.read()
...
with codecs.open('../parsed.txt','w','utf-8') as f:
for key in fieldD:
f.write(key+'\t'+fieldD[key]+'\n')
As well as all the permutations of these ideas, including writing as utf-16, encoding each string separately before they are added to the dictionary, and other erroneous ideas. I'm not sure what the best approach here is. It seems I've had the best luck not using ANY encoding because that at least will result in SOME text editors viewing the results correctly (emacs, textwrangler)
I've read through a couple posts on here regarding this topic and still can't seem to make heads or tails of what is going on.
Thanks.
A: I followed your instructions. The displayed page is NOT encoded in UTF-8; decoding using UTF-8 fails. According to an experimental character set detector that I muck about with occasionally, it is encoded in a Latin-based encoding ... one of ISO-8859-1, cp1252, and ISO-8859-15, and the language appears to be 'es' (Spanish) or 'fr' (French). According to me looking at it, it's Spanish. Firefox (View >>> view encoding) says it's ISO-8859-1.
So now what you need to do is experiment with what tools will display your saved files correctly. If you can't find one, you will need to transcode your files to UTF-8 i.e. data.decode('ISO-8859-1').encode('UTF-8') and find a tool that displays UTF-8 correctly. Shouldn't be too hard. Firefox can nut out the encoding and display it correctly for just about any encoding that I've thrown at it.
Update after request for "intuition":
In your 3rd block of code, you include only the the input and the output, with "..." between. The input code should produce unicode objects OK. However in the output code, you use the str function (why???). Assuming that you still have unicode objects after the "...", applying str() to them would raise an exception if your system's default encoding is 'ascii' (as it should be) or silently mangle your data if it is 'utf8' (as it shouldn't be). Please publish (1) the contents of "..." (2) the result of doing import sys; print sys.getdefaultencoding() (3) what you "see" in the output file instead of the expected ó in "Iglesia Católica" -- is it ó? (4) the actual byte(s) in the file (use print repr(the data)) instead of the expected ó
SOLVED You say in a comment that you see Iglesia Católica ... note that there are FOUR characters displayed instead of the ONE expected. This is symptomatic of encoding in UTF-8 twice. The next puzzle was what was displaying those characters, two of which are not mapped in ISO-8859-1 nor cp1252. I tried the old DOS codepages cp437 and cp850, still used in Windows' Command Prompt window, but it didn't fit. koi8r wasn't going to fit either; it needs a Latin-based character set. Hmm what about macroman? Tada!! You sent the doubly-encoded guff to stdout on your Mac Terminal. See the demonstration below.
>>> from unicodedata import name
>>> oacute = u"\xf3"
>>> print name(oacute)
LATIN SMALL LETTER O WITH ACUTE
>>> guff = oacute.encode('utf8').decode('latin1').encode('utf8')
>>> guff
'\xc3\x83\xc2\xb3'
>>> for c in guff.decode('macroman'):
... print name(c)
...
SQUARE ROOT
LATIN CAPITAL LETTER E WITH ACUTE
NOT SIGN
GREATER-THAN OR EQUAL TO
>>>
Inspecting the saved file I too saved the web page to a file (plus a directory containin *.jpg, a css file etc) -- using Firefox "save page as". Try this with your saved page and publish the results.
>>> data = open('g0.htm', 'rb').read()
>>> uc = data.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb7 in position 1130: invalid start byte
>>> pos = data.find("Iglesia Cat")
>>> data[pos:pos+20]
'Iglesia Cat\xf3lica</a>'
>>> # Looks like one of ISO-8859-1 and its cousins to me.
Note carefully: If your file is encoded in UTF-8, then reading it with the UTF-8 codec will produce unicode. If you don't mangle the data somehow when parsing, and write the parsed unicode with the UTF-8 codec, it will NOT be doubly encoded. You need to look carefully at your code for instances of "str" (remember the "typo"?), "unicode", "encode", "decode", "utf", "UTF", etc. Do you call a 3rd-party library to do the parsing? What do you see when you do print repr(key), repr(field[key]) just before writing to the output file?
This is becoming tedious. Consider putting your code and saved page on the web somewhere we can look at it instead of guessing.
32766.html: I've just realised that you are the guy who had blown all his inodes trying to write too many files to a folder on a vfat file system (or something like that). So you are not doing a manual "save as". Please publish the code that you have used to "save" these files.
A: >>> url = 'http://213.97.164.119/ABSYS/abwebp.cgi/X5104/ID31295/G0?ACC=DCT1'
>>> data = urllib2.urlopen(url).read()[4016:4052]; data
'Iglesia+Cat%f3lica">Iglesia Cat\xf3lica'
>>> data.decode('latin-1')
u'Iglesia+Cat%f3lica">Iglesia Cat\xf3lica'
>>> data.decode('latin-1').encode('utf-8')
'Iglesia+Cat%f3lica">Iglesia Cat\xc3\xb3lica'
What do you get?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: display:table in a div not showing like a table http://img580.imageshack.us/img580/1811/sinttulooh.png
I have the problem you see in the picture. That's a div with three columns. This div has a display:table property, and every column has a display:table-cell property. The problem is that, as you see, the left and right columns begin their content when the middle one has finished its content, and they should start writing from the top, as the middle column.
I don't know why it behaves like that, because there is no conflict with any other rule in the rest of the CSS. And I've seen in other examples that it is not necessary to define table-column or table-row to get that style.
How should I declare the divs to get the desired structure?
Here is the code: http://jsfiddle.net/3fMM3/2/
A: You don't need tables there and also you don't need to make put display:table.
Just use css styling to make a three column layout, this is what appears you want to achive.
Check this link for example :
http://matthewjamestaylor.com/blog/perfect-3-column.htm
A: Here's a working example :
http://jsfiddle.net/NyqGQ/1/
Note the "border-collapse" property, to merge container's and children border.
A: Try to set the vertical-align property to top on your table-cells.
.your-table-cells
{
vertical-align:top;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Partials for HABTM I have the following models:
user.rb
has_and_belongs_to_many :comps
comp.rb
has_and_belongs_to_many :users
And my comps_controller.rb is:
def index
@user = User.find(current_user.id)
@comps = @user.comps
end
and my comps/index file is:
<%= render @comps %>
and my partial comps/_comp file is:
<tr>
<span class="content"><%= comp.name %></span>
<td>
<%= link_to "delete", comp, :method => :delete,
:confirm => "You sure?",
:title => comp.name %>
</td>
</tr>
However, I get the error "undefined method `model_name' for NilClass:Class"
I'm not sure what is causing this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DatagramPacket not transmitting the right message I'm implementing a client/server application using UDP transmissions. Here is my part of my code :
Client :
InetAddress serverAddress = ...
int serverPort = ...
DatagramSocket socket = new DatagramSocket(9999);
...
String message = "<HELLO>";
byte[] outbuffer = new byte[1000];
outbuffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(outbuffer, outbuffer.length, serverAddress, serverPort);
socket.send(this.packet);
Server :
DatagramSocket serverSocket = new DatagramSocket(9876);
...
byte[] inbuffer = new byte[1000];
DatagramPacket packet = new DatagramPacket(inbuffer, inbuffer.length);
serverSocket.receive(packet);
String response = new String(packet.getData(), 0, packet.getLength());
System.out.println(response);
if("<HELLO>".equals(response)){
System.out.println("OK");
} else {
System.out.println("ERROR");
}
My problem is the following: if I print the response String on the client side that is comming from the client, everything looks fine ("").
But for some reasons when I trie to compare the response coming from the server using .equals or a RegExp it fails !
May be it's related to String encoding but I don't know where and why it fails. Both client and server are running on the same host right now, so it might not be related to JVM differences.
A: You're currently using the platform default encoding to both encode and decode strings. You should absolutely not do that. Specify the encoding both in the getBytes() call and the constructor call, e.g.
byte[] outBuffer = message.getBytes("UTF-8");
Also note that your current code creates a byte array of length 1000 and then immediately throws it away:
byte[] outbuffer = new byte[1000];
// Byte array created on previous line is now useless!
outbuffer = message.getBytes();
... don't do that.
We can't really tell much more from the code you've given us - if you could produce short but complete programs demonstrating the problem, that would really help.
For debugging, I would suggest you log the contents of the datagram packet you receive, while still in binary. Presumably it's not what you expected, but that doesn't help to show what it was.
EDIT: Here's a pair of short but complete programs which do work:
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(9999);
byte[] inbuffer = new byte[1000];
DatagramPacket packet = new DatagramPacket(inbuffer, inbuffer.length);
socket.receive(packet);
String response = new String(packet.getData(), 0,
packet.getLength(), "UTF-8");
System.out.println(response);
if("<HELLO>".equals(response)){
System.out.println("OK");
} else {
System.out.println("ERROR");
}
}
}
// Client.java
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
byte[] output = "<HELLO>".getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(output, output.length,
InetAddress.getLocalHost(),
9999);
socket.send(packet);
}
}
A: You have a variable response and reponse.
I am assuming that they won't be the same and your test should fail.
This is the sort of thing you should be able to see in a debugger.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hebrew - english layouts selction in android application What is the best way to provide the ability to switch between hebrew/english layouts in Android applications?
Is it commonly done - or usually just providing hebrew or english applications.
I know there is abikty to use localiztions - but is there Hebrew support for this?
Also my application should be for iPhone as well and I want to keep it the same.
How should do it in the code? Where to place the layouts?
Yoav
A: For orientation (right-to-left) you need: android.text.Layout.Direction
A hebrew TrueTypefont can then be called from a resource in your app by including TextView.
Instead of pushing 2 layout files you could use a class for hebrew and another for english...
or you could push the text to string values file for highest cleanliness
If it is a block of text that could be called from resource txt file (practical for prayers)
It all depends on how much text you have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Background function in asp.net Is it possible to write a background function in a master page that triggers after a specific period of time, say 5 hours?
function()
{
execute code from the clsGeneral Class
}
Please suggest how this can be implemented.
A: Pre IIS 7.5 you don't. (technically you can, but it's stupid). IIS is free to terminate your app whenever he wants, and when IIS is restarted, apps are restarted "lazily" (until someone opens a page of your web app, the web app isn't started).
From IIS 7.5 onward you could using the Application Warm-Up Module (sadly the beta was removed :-) ). With it you create a Thread that waits the specified time and does something. Quite easy.
The "right" solution is normally to create a Windows Service and use Quartz. Read here for example Scheduler for ASP.NET?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is effect of "System.gc()" in J2ME? I'm developing a mobile application in J2ME. Here I'm facing memory problem. I'm facing out of memory error. So please give the ideas of how it get rid out of this kind of error/exception, garbage collection, memory management in J2ME.
I had one doubt what is the effect System.gc() in the J2ME.
What is the difference between System.gc() and Runtime.getRuntime().gc() in J2ME/Java.
Thanks & Regards,
A: Calling System.gc() will not fix an "OutOfMemoryError". An OOME only happens after the system has made a "best effort" attempt to release memory by garbage collecting (and other means) ... and failed to free enough memory to continue.
The way to fix OOME errors is to find out what is using all of the memory and try to do something about it.
Possible problems that can lead to OOMEs include:
*
*Memory leaks; i.e. something in your app is causing lots of objects to remain "reachable" after they are no longer required.
*Memory hungry data structures or algorithms.
*Not enough memory to run the app with that input data.
Your first step to solving this problem should be to use a profiler to see if there are any significant leaks, and to find out more generally what data structures are using all of the memory.
A:
Runs the garbage collector.
Calling the gc method suggests that the Java Virtual Machine expend
effort toward recycling unused objects in order to make the memory
they currently occupy available for quick reuse. When control returns
from the method call, the Java Virtual Machine has made a best effort
to reclaim space from all discarded objects.
The call System.gc() is effectively equivalent to the call:
Runtime.getRuntime().gc()
-> http://download.oracle.com/javase/6/docs/api/java/lang/System.html#gc%28%29
A: System.gc() and Runtime.getRuntime().gc() are equivalent. They suggest a garbage collection, but there is no guarantee that this will actually happen.
So, don't rely on it, and in fact, it is very rare that you want to call this at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make a frame1 in the timeline, to be my startpage, when I already have a frame on the first timeline? I have 3 layers in the timeline, and I want to make a new layer, and then use the new layer to be my first frame (like a startpage).
How do I do that?
A: Flash does not support show/hide of layers. Learn about working with Movieclips. You should find a lot by just searching for it.
myStartClip.visible = true;
A "shaking screen" means you probably have compile errors.
A: Don't use layers or frames (aside from the first frame where you put all your code as usual of course).
It's an AS3 exercise, which means you should be working mainly in AS3 code, and not in frames and layers.
You put the "start page" in a container, which can be a Sprite or a MovieClip.
The "start page" can contain for instance a background, a textfield with some instructions and a start button.
This means that you have to create a new container for instance
var startContainer:Sprite = new Sprite();
addChild(startContainer); // and maybe position it with x and y
Then you create the things you need on your start page
var infoTf:TextField = new TextField();
infoTf.text = "some game description and how to play";
var bg:SomeBackground = new SomeBackground();
var startBtn:SomeBtn = new SomeBtn();
startBtn.addEventListener(MouseClick.CLICK, handleMClick_startGame);
And then you add these things to the container.
startContainer.addChild(bg); // add the other things too of course
Then when you press the startBtn, you use removeChild on the entire container and don't forget to remove the eventListener for the startBtn
After that you add the content for the game either directly on the stage, or to another mainContainer if you so prefer.
And in the end you use the same technique for the game over page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python/Django: sending emails in the background Imagine a situation in which a user performs an action on a website and admins are notified.
Imagine there are 20 admins to notify. By using normal methods for sending emails with Django the user will have to wait until all the emails are sent before being able to proceed.
How can I send all the emails in a separate process so the user doesn't have to wait? Is it possible?
A: Another option is django-mailer. It queues up mail in a database table and then you use a cron job to send them.
https://github.com/pinax/django-mailer
A: A thread may be a possible solution. I use threads intensively in my application for haevy tasks.
# This Python file uses the following encoding: utf-8
#threading
from threading import Thread
...
class afegeixThread(Thread):
def __init__ (self,usuari, parameter=None):
Thread.__init__(self)
self.parameter = parameter
...
def run(self):
errors = []
try:
if self.paramenter:
....
except Exception, e:
...
...
n = afegeixThread( 'p1' )
n.start()
A: Use celery as a task queue and django-celery-email which is an Django e-mail backend that dispatches e-mail sending to a celery task.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to set current date and time using prepared statement? I have a column in database having datatype DATETIME. I want to set this column value to current date and time using `PreparedStatement. How do I do that?
A: Use PreparedStatement#setTimestamp() wherein you pass a java.sql.Timestamp which is constructed with System#currentTimeMillis().
preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports now() for this. E.g.
String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())";
Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as TIMESTAMP instead of DATETIME in MySQL.
A: conn = getConnection();
String query = "insert into your_table(id, date_column) values(?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, "0001");
java.sql.Date date = getCurrentDatetime();
pstmt.setDate(2, date);
Where the function getCurrentDatetime() does the following:
public java.sql.Date getCurrentDatetime() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: MapReduceBase and Mapper deprecated public static class Map extends MapReduceBase implements Mapper
MapReduceBase, Mapper and JobConf are deprecated in Hadoop 0.20.203.
What should we use now?
Edit 1 - for the Mapper and the MapReduceBase, I found that we just need to extends the Mapper
public static class Map extends Mapper
<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
Edit 2 - For JobConf we should use configuration like this:
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = new Job(conf);
job.setMapperClass(WordCount.Map.class);
}
Edit 3 - I found a good tutorial according to the new API : http://sonerbalkir.blogspot.com/2010/01/new-hadoop-api-020x.html
A: Javadoc contains info what to use instaed of this depraceated classes:
e.g. http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/JobConf.html
Deprecated. Use Configuration instead
Edit: When you use maven and open class declaration (F3) maven can automatically download source code and you'll see content of javadoc comments with explanations.
A: There is not much different functionality wise between the old and the new API, except that the old API supports push to the map/reduce functions, while the new API supports both push and pull API. Although, the new API is much cleaner and easy to evolve.
Here is the JIRA for the introduction of the new API. Also, the old API has been un-deprecated in 0.21 and will be deprecated in release 0.22 or 0.23.
You can find more information about the new API or sometimes called the 'context objects' here and here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Get browser history and search result in android I am trying to get the history and search results from the android browser.
In the following code I get all the bookmarks, which works great:
public void getBrowser(){
String[] requestedColumns = {
Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.VISITS,
Browser.BookmarkColumns.BOOKMARK
};
Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null, Browser.BookmarkColumns.VISITS);
Log.d(DEBUG_TAG, "Bookmarks count: " + faves.getCount());
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
int visitsIdx = faves.getColumnIndex(Browser.BookmarkColumns.VISITS);
int bmIdx = faves.getColumnIndex(Browser.BookmarkColumns.BOOKMARK);
faves.moveToFirst();
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx) + " visited " + faves.getInt(visitsIdx) + " times : " + (faves.getInt(bmIdx) != 0 ? "true" : "false"));
faves.moveToNext();
}
}
When I am trying to only get the history from the browser I am trying following code:
public void getBrowserHist() {
Cursor mCur = managedQuery(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, null);
mCur.moveToFirst();
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
Log.v("titleIdx", mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
Log.v("urlIdx", mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
mCur.moveToNext();
}
}
}
The problem is that I now get all the bookmarks, history and top visited pages. And I only want the history columns. I also wan´t the search results from google search. I have tried the SEARCHES_URI object but I can´t get it to work.
Does anyone have any suggestion hove I can solve my problem?
A: For some strange reason, Google decided to mix bookmarks and history calling them "Bookmarks" in the SDK.
Try the following code, the important thing is to filter by "bookmark" type.
String[] proj = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0"; // 0 = history, 1 = bookmark
mCur = this.managedQuery(Browser.BOOKMARKS_URI, proj, sel, null, null);
this.startManagingCursor(mCur);
mCur.moveToFirst();
String title = "";
String url = "";
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false && cont) {
title = mCur.getString(mCur.getColumnIndex(Browser.BookmarkColumns.TITLE));
url = mCur.getString(mCur.getColumnIndex(Browser.BookmarkColumns.URL));
// Do something with title and url
mCur.moveToNext();
}
}
A: Try this:
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
import android.database.Cursor;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
Browser.BookmarkColumns.TITLE
, Browser.BookmarkColumns.URL
};
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null
);
mCur.moveToFirst();
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
while (mCur.isAfterLast() == false) {
view.append("n" + mCur.getString(titleIdx));
view.append("n" + mCur.getString(urlIdx));
mCur.moveToNext();
}
}
}
extracted from here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: java regex tricky pattern I'm stucked for a while with a regex that does me the following:
*
*split my sentences with this: "[\W+]"
*but if it finds a word like this: "aaa-aa" (not "aaa - aa" or "aaa--aaa-aa"), the word isnt splitted, but the whole word.
Basically, i want to split a sentece per words, but also considering "aaa-aa" is a word. I'have sucessfully done that by creating two separate functions, one for spliting with \w, and other to find words like "aaa-aa". Finally, i then add both, and subctract each compound word.
For example, the sentence:
"Hello my-name is Richard"
First i collect {Hello, my, name, is, Richard}
then i collect {my-name}
then i add {my-name} to {Hello, my, name, is, Richard}
then i take out {my} and {name} in here {Hello, my, name, is, Richard}.
result: {Hello, my-name, is, Richard}
this approach does what i need, but for parsing large files, this becomes too heavy, because for each sentence there's too many copies needed. So my question is, there is anything i can do to include everything in one pattern? Like:
"split me the text using this pattern "[\W+], but if you find a word like this "aaa-aa", consider it a word and not two words.
A: Why not to use pattern \\s+? This does exactly what you want without any tricks: splits text by words separated by whitespace.
A: Almost the same regular expression as in your previous question:
String sentence = "Hello my-name is Richard";
Pattern pattern = Pattern.compile("(?<!\\w)\\w+(-\\w+)?(?!\\w)");
Matcher matcher = pattern.matcher(sentence);
while (matcher.find()) {
System.out.println(matcher.group());
}
Just added the option (...)? to also match non-hypened words.
A: Your description isn't clear enough, but why not just split it up by spaces?
A: I am not sure whether this pattern would work, because I don't have developer tools for Java, you might try it though, it uses character class substraction, which is supported only in Java regex as far as I know:
[\W&&[^-]]+
it means match characters if they are [\W] and [^-], that is characters are [\W] and not [-].
A: If you want to use a split() rather than explicitly matching the words you are interested in, the following should do what you want: [\s-]{2,}|\s To break that down, you first split on two or more whitespaces and/or hyphens - so a single '-' won't match so 'one-two' will be left alone but something like 'one--two', 'one - two' or even 'one - --- - two' will be split into 'one' and 'two'. That still leaves the 'normal' case of a single whitespace - 'one two' - unmatched, so we add an or ('|') followed by a single whitespace (\s). Note that the order of the alternatives is important - RE subexpressions separated by '|' are evaluated left-to-right so we need to put the spaces-and-hyphens alternative first. If we did it the other way around, when presented with something like 'one -two' we'd match on the first whitespace and return 'one', '-two'.
If you want to interactively play around with Java REs I can thoroughly recommend http://myregexp.com/signedJar.html which allows you to edit the RE and see it matching against a sample string as you edit the RE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to invoke powershell Set-Location command silently? I would like to cd to some directory without the path to that directory being displayed by powershell. No matter what I try - nothing works:
PS C:\dev\windows\nc> cd .\NC.Server.Host | Out-Null
C:\dev\windows\nc\NC.Server.Host
PS C:\dev\windows\nc\NC.Server.Host> cd .. > $null
C:\dev\windows\nc
PS C:\dev\windows\nc> cd .\NC.Server.Host 2> $null
C:\dev\windows\nc\NC.Server.Host
PS C:\dev\windows\nc\NC.Server.Host> $x=cd ..
C:\dev\windows\nc
PS C:\dev\windows\nc>
As you can see the target directory path is always displayed. Is it a way to avoid it? Thanks.
EDIT
Here is my prompt function:
PS Z:\dev\3rd_party> gc Function:prompt
$(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '
A: You probably use the PowerShell Community Extensions. In those cd is defined as an alias to Set-LocationEx which exhibits this behaviour:
PS Home:\> Set-Location ..
PS Home:\> Set-LocationEx ..
Home:\
Either use Set-Location instead of cd, or don't load PSCX or redefine cd to its usual alias after loading PSCX in your profile.
(Those are the reasons I load PSCX only occasionally if I actually need a command from there; redefining core commands or aliases with slightly different semantics is evil and should never be done.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ASP.NET C# Generate Table Dynamically doesn't work I've been trying to generate a table with n number of rows. Being used to PHP makes this all the worst. I tried the following code:
using System.Data;
// Create a DataTable instance
DataTable dTbl = new DataTable("myDynamicTable");
// Create a DataColumn instances
DataColumn dValue = new DataColumn();
DataColumn dMember = new DataColumn();
dValue.ColumnName = "Id";
dValue.DataType = Type.GetType("System.Int32");
dMember.ColumnName = "Name";
dMember.DataType = Type.GetType("System.String");
// Add these DataColumns into the DataTable
dTbl.Columns.Add(dValue);
dTbl.Columns.Add(dMember);
DataRow myrow = dTbl.NewRow();
myrow["Id"] = 1;
myrow["Name"] = "Tux";
// Add the row into the table
dTbl.Rows.Add(myrow);
but nothing displayed. Any idea why?
All I need is to display a table with 3 columns and n number of rows. This number will of rows will be dependent on number of records in database satisfying a certain conditions.
I also tried this:
HtmlTable table1 = new HtmlTable();
// Set the table's formatting-related properties.
table1.Border = 1;
table1.CellPadding = 3;
table1.CellSpacing = 3;
table1.BorderColor = "red";
// Start adding content to the table.
HtmlTableRow row;
HtmlTableCell cell;
for (int i = 1; i <= 5; i++)
{
// Create a new row and set its background color.
row = new HtmlTableRow();
row.BgColor = (i % 2 == 0 ? "lightyellow" : "lightcyan");
for (int j = 1; j <= 4; j++)
{
// Create a cell and set its text.
cell = new HtmlTableCell();
cell.InnerHtml = "Row: " + i.ToString() +
"<br>Cell: " + j.ToString();
// Add the cell to the current row.
row.Cells.Add(cell);
}
// Add the row to the table.
table1.Rows.Add(row);
}
// Add the table to the page.
this.Controls.Add(table1);
but it didn't work!
A: Instead of doing "this.Controls.Add(table1)" add the table to the .aspx page, and then modify it through the code.
Even better - use a databound GridView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No known package when getting value for resource number Everything looks like ok. But :
No known package when getting value for resource number 0x7f040001
exception is throwing.
A: My code was:
Resources res = getResources();
InputStream is = res.openRawResource(R.xml.questions);
then I changed it to:
is = getApplicationContext().getResources().openRawResource(R.xml.questions);
Now it works correctly :o
BTW, I had another problem is:
WARN/System.err(577): org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: not well-formed (invalid token)
This link solved: Android parsing an xml with saxparser
A: Try:
menu Project -> Clean
If it doesn't runs close project , close eclipse , and repeat...
and a tip , don't touch gen code , it must be only change by eclipse itself.
MOD
sometimes eclipse goes crazy with code . When it happens i usually change code order in res.
It happens to me with Strings , eclipse change the string to another one , and bug change when i change the order of some few strings there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: ARM LPC1751 pins configured as I/O How can I configure one pin for input and another for the output?
If I am not wrong this could be done with GPIO registers that controlls device pins that are not connected to peripherical functions.
A: Look in UM10360.PDF, Chapter 9: GPIO. There you can find the description for the FIOxDIR direction registers, as well as the reigisters for querying, setting and clearing GPIO pins.
I also strongly recommend looking at the CMSIS Standard Peripherial Driver Library that NXP offers for 175x/176x, look in microcontroller support documents. Edit: There are lots of sample code in this Library.
A: https://github.com/dwelch67
I have a number of lpc based examples. You are looking for the IODIR register, depending on the port and flavor of LPC, there are now what they call fast I/O registers. a one in a bit location means that pin is an output, a zero an input.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get page size using AlivePDF Is it possible to get the page width and page height for a PDF during creation with AlivePDF?
I need this to place a shape to the right side of the page, no margin or padding, sticked to the right side.
A: Hopefully this will help you. Looking at the AlivePDF API documentation for the Page object (See here) I've found the public properties "width" and "height".
In my code, given a PDF object called myPDF, I use:
var sizeWidth:int = myPDF.getPage(i).width;
var sizeHeight:int = myPDF.getPage(i).height;
to get the width and height of page i.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What does Array as Object mean in Basic4Android? SQL1.ExecNonQuery2("INSERT INTO table1 VALUES(?,?,?)",Array As Object("def",3,4))
I don't seem to understand why the argument list in the above statement is declared in the form of Array as Object('xx','xx''xx').How is it exactly being converted into a list parameter ?
A: Array As xxx is a shorthand syntax for declaring a new array and assigning the values.
Array As Object("def", 3, 4)
Is equivalent to:
Dim arr As Object(3)
arr(0) = "def" : arr(1) = 3 : arr(1) = 4
Basic4android automatically wraps arrays as lists when needed. The items are not copied, it is the whole array that is wrapped in a list. Therefore the above code is valid as it creates an array which is then wrapped as a List.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image upload doesn't work in mozilla and Internet Explorer - asks to save files I have implemented upload feature in ASP.MVC. I am using jQuery.BlockUI and JQuery.Form plugins (but I don't know is this important). And everything works perfect in Google Chrome.
But in Mozilla and Internet Explorer it doesn't. When I try to upload image it asks me in popup window:
Upload. You have chosen to open Upload which is a: application/json
from http://localhost:2993 What should Firefox do with this file?
And I have open with/save and browse options.
In my upload method I am returning JSon here is the code:
[HttpPost]
public JsonResult Upload()
{
string savedFileName = null;
string hName = null;
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase hpf = Request.Files[i] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileNameThumb = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Content", "Images", "Thumb",
Path.GetFileName(hpf.FileName));
savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Content", "Images", "Full",
Path.GetFileName(hpf.FileName));
hName = hpf.FileName;
ImageModel.ResizeAndSave(savedFileName, hpf.FileName, hpf.InputStream, int.MaxValue, false);
// for cropping
ImageModel.ResizeAndSave(savedFileName, hpf.FileName, hpf.InputStream, 540, false);
}
string r = string.Format("../../Content/Images/Full/{0}", hName);
return Json(new { foo = r });
}
What produce this error?
A: You are returning JSON as the page to the user following the upload. The JSON won't make any sense to a regular user, so most browsers doesn't have any predefined way to display the JSON.
If the returned page is displayed somewhere, you should return a regular HTML page that means something to the user. If the page isn't really displayed somewhere (e.g. loaded in a hidden frame), you should return an empty HTML page that all browsers know how to display.
A: Here's the actual fix. In the case that you're doing an asynchronous iframe upload (which is the standard AJAX way of uploading files in the background) you have to set the response type on the server side to "text/html" not "text/json"
http://www.sencha.com/forum/archive/index.php/t-120201.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ICS timezone not working I have made an ICS feed containing a long list of events. My timezone does not seem to work.
In the sample below you see that my event should start 07:55:00 and end 09:30:00. This is what it should show in my calendar. Instead it shows 09:55:00 and 11:30:00 - an offset of two hours. The timezone should be set to Europe/Copenhagen but this does not have any effect.
Can anyone tell me how I can achieve the right times?
BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Test Calendar
X-WR-TIMEZONE:Europe/Copenhagen
X-WR-CALDESC:Test Calendar
BEGIN:VEVENT
DTSTART:20110926T075500Z
DTEND:20110926T093000Z
DTSTAMP:20111002T133505Z
UID:E9QNQ30EG-5SRB7-QQKL3-2JUUZ-477LBRV4IMSJ78
CREATED:20111002T133505Z
LAST-MODIFIED:20111002T133505Z
LOCATION:B34
SEQUENCE:3
SUMMARY:2abc3c Ma3 CD (B34)
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR
A: You've specified that your event starts at 07:55 in UTC - that's what the Z at the end shows. If you want it to be in local time, you shouldn't have the Z, and you should probably specify the time zone there too:
DTSTART;TZID=Europe/Copenhagen:20110926T075500
DTEND;TZID=Europe/Copenhagen:20110926T093000
Alternatively, specify the UTC start and end time using Z, but taking account for the relevant time zone difference - so an event that starts at 07:55 in Europe/Copenhagen at the moment is actually 05:55 in UTC.
A: You need also to add your time zone TZID in a VTIMEZONE calendar component.
Add this before VEVENT
BEGIN:VTIMEZONE
TZID:Europe/Copenhagen
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
You can go to link form more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: How to pass object to function in c++? Can anyone tell me how I can pass an object to a C++ function?
Any better solution than mine?
#include<iostream>
using namespace std;
class abc
{
int a;
public:
void input(int a1)
{
a=a1;
}
int display()
{
return(a);
}
};
void show(abc S)
{
cout<<S.display();
}
int main()
{
abc a;
a.input(10);
show(a);
system("pause");
return 0;
}
A: You can pass by value, by reference or by pointer. Your example is passing by value.
Reference
void show(abc& S)
{
cout<<S.display();
}
Or, better yet since you don't modify it make it int display() const and use:
void show(const abc& S)
{
cout<<S.display();
}
This is normally my "default" choice for passing objects, since it avoids a copy and can't be NULL.
Pointer
void show(abc *S)
{
cout<<S->display();
}
Call using:
show(&a);
Normally I'd only use pointer over reference if I deliberately wanted to allow the pointer to be NULL.
Value
Your original example passes by value. Here you effectively make a local copy of the object you are passing. For large objects that can be slow and it also has the side effect that any changes you make will be made on the copy of the object and not the original. I'd normally only use pass by value where I'm specifically looking to make a local copy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: the picture can't be attached when I publish a new feed on facebook by graph I was publishing a new feed to the wall on facebook using graph api in ruby, and it works except the picuture is blank.
here is a arguments I attached
{
:message => "Hello, world",
:name=> "name here",
:link=> "http://blabla.com",
:caption=> "Note: stars",
:description => " a long sentence",
:picture => "http://www.fbrell.com/f8.jpg",
:source => "another url"
}
but if I do the same things with graph api using javascript sdk, the picture can be posted to the wall.
here is the same questions the other guys asked. any help? thank you very much.
Problem with post a picture in Facebook Wall with Graph API
Picture posting NOT working with facebook Graph API anymore
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: asp.net MVC3 Custom Validation I am new to MVC so this question may be naive
I know you can add validation attributes to model properties and the framework will provide appropriate server side and client side validation.However I am forced to use a legacy database structure where one of the properties in the model is either "int" or "string"
and the other property(Value) data type is determined by the first property.This means that I cannot use Annotations for validation. But is there any simple way of programatically "annotating" the properties after values are fetched from the database and the model class is constructed.If this can be done then it will do effective (client Side) validation without much hassle.
thanks
A: This answer shows one way to inject attributes at runtime. Another answer shows how to use validations that are only checked sometimes.
In your case it would be pretty easy to do model-based validation.
For server-side validation:
public class MyModel: IValidatableObject
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public IEnumerable<ValidationResult>
Validate(ValidationContext validationContext)
{
var relevantFields = new [] {"Prop2"};
if (Prop1 == "Int" && NotValidInt(Prop2))
yield return new ValidationResult("Prop2 must be convertable to int", relevantFields);
else if (prop1 == "String" && NotValidString(Prop2))
yield return new ValidationResult("Prop2 must be convertible to string", relevantFields);
}
}
For client-side validation, it's a bit more involved but details are available here:
*
*MSDN article on adding support for clientside validation
*A Good StackOverflow answer on the topic
See the custom validation section of the free Pluralsight training on validation for more information on server-side validation.
A: You are falling into the normal newbie error of thinking of your database as the M in MVC. Any non-trivial app is going to require that you seperate your database model from your view model. So apply your attributes to a view model, then use business logic to copy the values to your database model when your view is properly validated.
MVC is a User Interface pattern, and databases do not belong in it... I know, every sample application under the sun passes your data objects to the view, but that's just not the way it should be done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Need a syntax highlighter for inserting code into a web page I have tried Google but I can't find the websit /utility I'm looking for. A while ago I found a website which lets you paste in Javascript and then it will produce html/css which you can copy and paste into your webpage which then displays the Javascript with syntax highlighting and proper indentation. Does anyone know what website this is or know of a similar website? Thanks.
A: See ToHTML.com. Another options is Highlight.js.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP form submission I've built mini content management system. In my page add form i'm using ckeditor. for text are named content
<textarea id="content" style="width:100%" name="content"></textarea>
Adding all data from form into db table with following php code. (Function filter used for sanitizing data)
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
if(isset($_POST['submit'])&&$_POST['submit']=='ok'){
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
header("location:".$wsurl."admin/?page=add");
}
?>
FUNCTION FILTER (data sanitization)
function filter($data, $db)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = $db->escape_string($data);
return $data;
}
I got questions about it. (I'm newbie to ajax.)
*
*Currently i'm submitting data with standart php (page refreshes
every time). How to modify code for ajax submission?
*I have only one button for submitting data. I want to create second
button "save" which will update db fields via ajax
*How can i create autosave function (which periodically saves form in the background and informss user about it, just like on Stackoverflow) via ajax?
Thx in advance
A: Let's suppose you want to use jQuery to do the ajax business for you, you need to setup a periodic POST of the data in the textarea (note that in some browsers GET requests have a limit).
On the first POST, you need to tell the PHP script "this is the first POST" so that it knows to INSERT the data, it should then return to you some identifying characteristic. Every other time you POST data, you should also send this identifying characteristic, let's just use the primary key (PK). When you POST data + PK, the PHP script should run an update query on the SQL.
When constructing these, the thing to think about is sending data from the browser using JavaScript to a PHP script. The PHP script gets only whatever packet of data you send, and it can return values by producing, for instance, JSON. Your JavaScript code can then use those return values to decide what to do next. Many beginners often make the mistake of thinking the PHP can make calls to the JS, but in reality it's the other way around, always start, here, with the JS.
In this instance, the PHP is going to save data in the database for you, so you need to ship all the data you need to save to the PHP. In JS, this is like having some magic function you call "saveMyData", in PHP, it's just like processing a form submission.
The JavaScript side of this looks something like this (untested):
<script type="text/javascript">
var postUpdate = function(postKey){
postKey = postKey || -1;
$.post("/myscript.php",
/* note that you need to send some other form stuff
here that I've omitted for brevity */
{ data: $("#content").value(), key: postKey },
function(reply){
if(reply.key){
// if we got a response containing the primary key
// then we can schedule the next update in 1s
setTimeout(function(){postUpdate(reply.key);}, "1000");
}
}
});
};
// first invocation:
postUpdate();
</script>
The PHP side will look something like this (untested):
Aside: your implementation of filter should use mysql_real_escape_string() instead of striptags, mysql_real_escape_string will provide precisely the escaping you need.
<?php
require '../../core/includes/common.php';
$name = filter($_POST['name'], $db);
$title = filter($_POST['title'], $db);
$parentcheck = filter($_POST['parentcheck'],$db);
if(isset($_POST['parent'])){
$parent = filter($_POST['parent'],$db);
}else{
$parent = $parentcheck;
}
$menu = filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$pk = intval($_POST['key']);
if($pk == -1 || (isset($_POST['submit']) && $_POST['submit']=='ok')){
$result = $db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')")
or die($db->error);
$new_id = $db->insert_id;
$result2 = $db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')")
or die($db->error);
$pk = $db->insert_id;
echo "{\"key\": ${pk}}";
// header("location:".$wsurl."admin/?page=add");
}else if($pk > 0){
$result2 = $db->query("UPDATE pages SET content='$content' WHERE id='$pk')")
or die($db->error);
echo "{\"key\": ${pk}}";
}
A: For AJAX, you can use jQuery's ajax API. It is very good and is cross-browser.
And for saving and auto-saving: you can use a temporary table to store your data. When the user presses the save button or when your data is auto-saved, you save your data to the table using AJAX and return a key for the newly created row. Upon future auto-save/save button events, you update the temporary table using AJAX.
And one word of advice, use a framework for your PHP and Javascript. I personally use Symfony and Backbone.js. Symfony checks for CSRF and XSS automatically and using Doctrine prevents SQL-injection too. There are other frameworks available (such as CodeIgniter, CakePHP and etc.) but I think Symfony is the best.
Edit: For the auto-save functionality, you can use Javascript SetTimeout to call your AJAX save function, when the page loads for the first time.
A: With regard to security issues:
Your silver bullet function is fundamentally flawed, it does not work, will never work and can never work.
SQL has different escaping needs than hmtl.
The functions you use counteract each other. escape_string adds \, stripslashes removes them.
Never mind the order of the functions, you need to use a specialized escape function for one and only one purpose.
On top of that you are using depreciated functions.
For MySQL this is mysql_real_escape_string. Note that escape_string (without the real) is depreciated, because it is not thorough enough. Use real_escape_string instead. On mysqli escape_string is an alias for real_escape_string.
See:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
The ultimate clean/secure function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.