Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
It's been a while since I was in college and knew how to calculate a best fit line, but I find myself needing to. Suppose I have a set of points, and I want to find the line that is the best of those points.
What is the equation to determine a best fit line?
How would I do that with PHP? | Of additional interest is probably how good of a fit the line is.
For that, use the Pearson correlation, here in a PHP function:
```
/**
* returns the pearson correlation coefficient (least squares best fit line)
*
* @param array $x array of all x vals
* @param array $y array of all y vals
*/
function pearson(array $x, array $y)
{
// number of values
$n = count($x);
$keys = array_keys(array_intersect_key($x, $y));
// get all needed values as we step through the common keys
$x_sum = 0;
$y_sum = 0;
$x_sum_sq = 0;
$y_sum_sq = 0;
$prod_sum = 0;
foreach($keys as $k)
{
$x_sum += $x[$k];
$y_sum += $y[$k];
$x_sum_sq += pow($x[$k], 2);
$y_sum_sq += pow($y[$k], 2);
$prod_sum += $x[$k] * $y[$k];
}
$numerator = $prod_sum - ($x_sum * $y_sum / $n);
$denominator = sqrt( ($x_sum_sq - pow($x_sum, 2) / $n) * ($y_sum_sq - pow($y_sum, 2) / $n) );
return $denominator == 0 ? 0 : $numerator / $denominator;
}
``` | Here's an [article](http://www.johndcook.com/blog/2008/10/20/comparing-two-ways-to-fit-a-line-to-data/) comparing two ways to fit a line to data. One thing to watch out for is that there is a direct solution that is correct in theory but can have numerical problems. The article shows why that method can fail and gives another method that is better. | Find a "best fit" equation | [
"",
"php",
"math",
""
] |
I have some data of the form
```
Key ID Link
1 MASTER 123
2 AA 123
3 AA 123
4 BB 123
5 MASTER 456
6 CC 456
```
I would like to be able to select in the same select all linked items matching the selection criteria, plus the linked master. For example, if I have an ID of 'AA', I want the rows with ID = 'AA' to be returned, plus the row with ID = 'MASTER' and a link of 123:
```
1 MASTER 123
2 AA 123
3 AA 123
```
I'm using Oracle 10.2g, so if any special Oracle syntax will make this easier, then that would be ok. | Here's one method.
```
SELECT DISTINCT key, id, link
FROM the_table
START WITH id = 'AA'
CONNECT BY id = 'MASTER' and link = PRIOR link and 'AA' = PRIOR ID
``` | SELECT \* FROM table\_name WHERE ID=your\_id UNION ALL SELECT \* FROM table\_name WHERE ID='MASTER' AND link = (SELECT link FROM table\_name WHERE ID=your\_id)
That should answer to the question I understood ;) | How to select a related group of items in Oracle SQL | [
"",
"sql",
"oracle",
""
] |
I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
```
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
``` | Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
```
[i for i,x in enumerate(testlist) if x == 1]
```
Example:
```
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
```
Update:
Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:
```
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
```
Now we'll construct a generator...
```
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
```
and niftily enough, we can assign that to a variable, and use it from there...
```
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
```
And to think I used to write FORTRAN. | What about the following?
```
print testlist.index(element)
```
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
```
if element in testlist:
print testlist.index(element)
```
or
```
print(testlist.index(element) if element in testlist else None)
```
or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,
```
try:
print testlist.index(element)
except ValueError:
pass
``` | How to get item's position in a list? | [
"",
"python",
"list",
""
] |
I want to know the basic principle used for WYSIWYG pages on the web. I started coding it and made it using a text area, but very soon I realized that I cannot add or show images or any HTML in the text area. So I made it using DIV, but I did not understand how I could make it editable.
So, in gist, **I want to know how(in principle) to make an editable DIV section on a web page, something similar to Google docs or FCKEditor or TinyMCE.**
I would be very grateful for any pointers and info.
Thanks! | There's the `contentEditable` flag that can be added to any element on a page to make it editable, eg.
```
<div contentEditable>I am editable!!!!</div>
```
Should work in all major browsers nowadays, and things like shortcuts keys (cmd/ctrl-b, etc) will Just Work.
Form submission can then be done by pulling innerHTML out of the editable region. | *What you see is what you mean* is the way - don't follow the WYSIWYG path as it is full of traps.
[WYMeditor](http://www.wymeditor.org/) is the best when it comes to outputting semantic and clean HTML. | How to make a WYSIWYG section on a web page? | [
"",
"javascript",
"html",
"dom",
"wysiwyg",
""
] |
In jQuery, if I assign `class=auto_submit_form` to a form, it will be submitted whenever any element is changed, with the following code:
```
/* automatically submit if any element in the form changes */
$(function() {
$(".auto_submit_form").change(function() {
this.submit();
});
});
```
However, if I want to the form to submit only when specified elements are changed:
```
/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
$(".auto_submit_item").change(function() {
$(this).parents().filter("form").submit();
});
});
```
I'm just learning jQuery. Is there a better way to do this? | ```
/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
$(".auto_submit_item").change(function() {
$("form").submit();
});
});
```
Assumes you only have one form on the page. If not, you'll need to do select the form that is an ancestor of the current element using `$(this).parents("form").submit()` | You can use an expression in the `parents()` method to filter the parents. Hence this might be a little more efficient:
```
/* submit if elements of class=auto_submit_item in the form changes */
$(".auto_submit_item").change(function() {
$(this).parents("form").submit();
});
``` | submit form when elements change | [
"",
"javascript",
"jquery",
""
] |
I'm trying to run Python scripts using Xcode's User Scripts menu.
The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't do things like
```
#!/usr/bin/python
import myScript
myScript.foo()
```
Where myScript is a module in a folder I've added to my path.
I can append a specific path to os.sys.path manually easily enough, but I have to do it in every single script for every single path I want to use modules from
Is there a way to set this up so it uses the same path I use everywhere else?
EDIT: After looking into things a bit more, it seems like scripts executed from Xcode use a completely different PATH than normal. The path I get by running a script in Xcode is:
```
PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
and I'm sure my regular path doesn't have /Developer/usr/bin in it. Does anybody have any idea where this path is coming from? | On the mac, environment variables in your .profile aren't visible to applications outside of the terminal.
If you want an environment variable (like PATH, PYTHONPATH, etc) to be available to xcode apps, you should add it to a new plist file that you create at ~/.MacOSX/environment.plist.
See the [EnvironmentVars](http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html) doc on the apple developer website for more details. | A quick but hackish way is to have a wrapper script for python.
```
cat > $HOME/bin/mypython << EOF
#!/usr/bin/python
import os
os.path = ['/list/of/paths/you/want']
EOF
```
and then start all your XCode scripts with
```
#!/Users/you/bin/mypython
``` | How do I use my standard python path when running python scripts from xcode macros | [
"",
"python",
"xcode",
"macos",
"path",
""
] |
I have an array filled with values (twitter ids) and I would like to find the missing data between the lowest id and the highest id? Any care to share a simple function or idea on how to do this?
Also, I was wondering if I can do the same with mySQL? I have the key indexed. The table contains 250k rows right now, so a temporary table and then a join wouldn't be very fast or efficient. I could do a PHP loop to loop through the data, but that would also take a long time, and a great deal of memory. Is there a specific mysql query I can run? or can I somehow use the function from above with this?
Thanks,
James Hartig
<http://twittertrend.net> | I had a similar requirement and wrote a function that would return a list of missing IDs.
```
---------------------------
create function dbo.FreeIDs ()
---------------------------
returns @tbl table (FreeID int)
as
begin
declare @Max int
declare @i int
select @Max = MAX(ID) from [TheTable]
set @i = 0
while @i < @Max begin
set @i = @i + 1
if not exists (select * from [TheTable] where ID = @i)
insert into @tbl select @i
end
return
end
``` | Do you mean sequential ID's?
In that case
```
$new_ids = range($lowid, $highid, 1);
$ids = array_merge($ids, $new_ids);
$ids = array_unique($ids);
sort($ids);
```
And in SQL (with placeholders)
```
SELECT key, other_data from `table` WHERE key > :low_id AND key < :high_id
``` | How to find missing data either in array or in mySQL table? | [
"",
"php",
"mysql",
""
] |
so i have a winforms apps that downloads a set of data syncronously on startup. This obviously takes a while but then when any of the services or GUI classes load, they all have this data. I could change this to put on a background thread but then every component that needs access to this data would continuously have to get notified when this data was ready. This seems like bad design for every one of my classes that depends on this data to be loaded to have a If (Loaded) check or have to subscribe to a loaded event . . . any ideas?
Any other ideas? | I've written a number of applications that have similar behaviour to what you describe, and have three suggestions for you ...
**Splash Screen**
Add a splash screen to your application that displays the status of a number of startup steps. I've used this in the past when an application has a number of steps that have to occur on startup, before the user gets to use the application - confirmation of identity and authorisation of access through Active Directory, contact database for system information, loading static data, initial contact with specified web services, checking that prerequisites (like Crystal reports) are installed and working, etc etc.
**Subscription**
Have each component register interest with your data loader, and be notified when the data is available. This is the observer pattern, nothing wrong with it, though managing the subscriptions can be a bit messy.
**Lazy Loading**
Design the rest of your application to request the data as late as possible, giving as wide an opportunity for background loading to complete as possible. Users who are quick off the mark after startup have to wait for necessary data to load; users who take their time (maybe they started the application and then switched to Outlook) find response is immediate. | I would suggest you use the Observer Pattern and setup all the classes that rely on the data set being loaded. To minimize the amount of time the user needs to wait you could also consider implemented two categories of classes those that need the entire dataset to function and those that can function once a subset of the data has been loaded.
[Observer Design Pattern](http://www.dofactory.com/Patterns/PatternObserver.aspx) | Loading lots of upfront data. . sync or async . | [
"",
"c#",
"winforms",
"multithreading",
""
] |
I'd like to call a function in python using a dictionary with matching key-value pairs for the parameters.
Here is some code:
```
d = dict(param='test')
def f(param):
print(param)
f(d)
```
This prints `{'param': 'test'}` but I'd like it to just print `test`.
I'd like it to work similarly for more parameters:
```
d = dict(p1=1, p2=2)
def f2(p1, p2):
print(p1, p2)
f2(d)
```
Is this possible? | Figured it out for myself in the end. It is simple, I was just missing the \*\* operator to unpack the dictionary
So my example becomes:
```
d = dict(p1=1, p2=2)
def f2(p1,p2):
print(p1, p2)
f2(**d)
``` | ```
In[1]: def myfunc(a=1, b=2):
In[2]: print(a, b)
In[3]: mydict = {'a': 100, 'b': 200}
In[4]: myfunc(**mydict)
100 200
```
A few extra details that might be helpful to know (questions I had after reading this and went and tested):
1. The function **can** have parameters that are *not* included in the dictionary
2. You **can not** override a function parameter that is already in the dictionary
3. The dictionary **can not** have values that aren't in the function.
**Examples:**
***Number 1:** The function can have parameters that are not included in the dictionary*
```
In[5]: mydict = {'a': 100}
In[6]: myfunc(**mydict)
100 2
```
***Number 2:** You can not override a function parameter that is already in the dictionary*
```
In[7]: mydict = {'a': 100, 'b': 200}
In[8]: myfunc(a=3, **mydict)
TypeError: myfunc() got multiple values for keyword argument 'a'
```
***Number 3:** The dictionary can not have values that aren't in the function.*
```
In[9]: mydict = {'a': 100, 'b': 200, 'c': 300}
In[10]: myfunc(**mydict)
TypeError: myfunc() got an unexpected keyword argument 'c'
```
---
**How to use a dictionary with more keys than function arguments:**
A solution to #3, above, is to accept (and ignore) additional kwargs in your function (note, by convention `_` is a variable name used for something being discarded, though technically it's just a valid variable name to Python):
```
In[11]: def myfunc2(a=None, **_):
In[12]: print(a)
In[13]: mydict = {'a': 100, 'b': 200, 'c': 300}
In[14]: myfunc2(**mydict)
100
```
Another option is to filter the dictionary based on the keyword arguments available in the function:
```
In[15]: import inspect
In[16]: mydict = {'a': 100, 'b': 200, 'c': 300}
In[17]: filtered_mydict = {k: v for k, v in mydict.items() if k in [p.name for p in inspect.signature(myfunc).parameters.values()]}
In[18]: myfunc(**filtered_mydict)
100 200
```
---
**Example with both positional and keyword arguments:**
Notice further than you can use positional arguments and lists or tuples in effectively the same way as kwargs, here's a more advanced example incorporating both positional and keyword args:
```
In[19]: def myfunc3(a, *posargs, b=2, **kwargs):
In[20]: print(a, b)
In[21]: print(posargs)
In[22]: print(kwargs)
In[23]: mylist = [10, 20, 30]
In[24]: mydict = {'b': 200, 'c': 300}
In[25]: myfunc3(*mylist, **mydict)
10 200
(20, 30)
{'c': 300}
``` | Passing a dictionary to a function as keyword parameters | [
"",
"python",
"function",
"dictionary",
"parameters",
"keyword",
""
] |
My first instinct is to say each key is an object, and has a hash code, which is what is used to determine if a duplicate is being inserted. However, I can't find anything to back that up for sure. Can someone provide a link that says that, or provide the real answer here? Thanks! | The `Map` interface specifies that if two keys are `null` they are duplicates, otherwise if there's a key `k` such that `key.equals(k)`, then there is a duplicate. See the contains or get method here:
<http://java.sun.com/javase/6/docs/api/java/util/Map.html#containsKey(java.lang.Object)>
However, it's up to the `Map` implementation how to go about performing that check, and a `HashMap` will use a hash code to narrow the potential keys it will check with the `equals` method. So in practice, for a typical hash based map, to check for duplicates a map will take the hashcode (probably mod some size), and use `equals` to compare against any keys whose hashcode mod the same size gives the same remainder. | Read the question wrong, but the person's answer above is correct and my link provides the answer as to how it is determined (the equals method). Look at the contains and get methods in the link.
How a map inserts:
There cannot be a duplicate key in a Map. It will replace the old value with the new value if you find a duplicate key. Here is a [link](http://java.sun.com/javase/6/docs/api/java/util/Map.html) to the Map Interface. In addition, if you look at the put(K key, V value) method, it also explains how a map works. Hope that helps. | What does Java use to determine if a key is a duplicate in a Map? | [
"",
"java",
"dictionary",
""
] |
I have an exe that I know was written in java. I understand that java programs can be made into an exe and there are tools to convert jar files to exe but is it possible to convert back? AFAIK jar files can be run on any platform that can run java and I would like to use a windows compiled java program on mac without using any extra virtualisation (wine,vmware) | It depends how the exe has been built:
* If it has simply wrapped, with a tool like [JSmooth](http://jsmooth.sourceforge.net/docs/jsmooth-doc.html#N1034F), the same tool can [extract the jar](http://jsmooth.sourceforge.net/docs/jsmooth-doc.html#N1034F)
* If it it has been compiled, with for instance gcj (as illustrated by [this question](https://stackoverflow.com/questions/53845/java-compiler-options-to-produce-exe-files)),... I am not sure.
* If it has been compiled by a static compiler (or [AOT - Ahead-Of-Time](http://www.excelsior-usa.com/articles/java-to-exe.html#aot) -), I believe it is not possible to extract the orignial jars. | If your application was wrapped using JSmooth, you can look in your default temp directory (C:\Documents and Settings\Username\Local Settings\Temp) while the application is running.
Open a windows explorer window to the temp dir, then start up your application. You should see a jar file show up (Temp#.jar). Just make a copy of this and you should be on your way. | How can I extract java exe to jar | [
"",
"java",
""
] |
I put together a class yesterday to do some useful task. I started alpha testing, and at some point realized I was adding alpha test related methods to the class itself. It hit me that they don't belong there. After a bit of head scratching I derived a test class from the base class that has access to the protected members as well. I put all of the testing related methods, and set up and tear down in the test class, and left the base class lean and mean as the old saying goes.
After browsing around here awhile I found one comment that suggested using this sort of technique by making the testing class a friend of the real class.
In retrospect both of those techniques should have been obvious to me.
**What I am looking for, are techniques for specifically alpha testing/unit testing classes, without adding to the weight of the class being tested.**
**What techniques have you personally used, and recommend?** | One of the goals of unit testing is to verify the *interface* to your classes. This means that, generally speaking, you shouldn't be testing the dirty innards of your class. The unit test is supposed to interact with the public inputs and outputs of your class, and verify that the behaviour is as expected. You are thus able to change the internal implementation of your class without affecting all of the other objects that depend on it. Obviously, I don't know the details in your situation but I would say that, as a general rule, if your unit test is trying to figure out the private details of the class, you are doing something wrong.
**edit:** See also: [This SO question](https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods). Notice that it can be done (top answer), but also notice that the second-place answer (by a short margin) says more or less the same thing as I mention above. | It sounds like you don't want Unit testing, which is correctly the verification that the interface of a class works. You shouldn't have to change your class at all in order to do unit testing. If you are looking for a way to verify the internal state of your object so that it remains consistent, you should look into [Design by Contract](http://en.wikipedia.org/wiki/Design_by_contract) methods, which can verify internal state from within the object. | testing classes | [
"",
"c++",
"unit-testing",
""
] |
I'm selecting 1 field from 1 table and storing it into a temp table.
Sometimes that table ends up with 0 rows.
I want to add that field onto another table that has 20+ fields
Regular union won't work for me because of the field # mismatch.
Outer wont work for me because there is nothing to compare.
NVL doesn't work on the first temp table.
Anyone know how to do it?
**UPDATED:**
I failed to mention.... When the table that retrieves 1 field finds a match in other cases, this code that I'm using now works....
```
SELECT DISTINCT reqhead_rec.resp_name<br>
FROM reqhead_rec, biglist<br>
WHERE reqhead_rec.req_no = biglist.req_no
AND reqhead_rec.frm = biglist.req_frm<br>
INTO TEMP grabname with no log;
SELECT biglist.*, grabname.resp_name<br>
FROM biglist, grabname<br>
ORDER BY prnt_item, account_amt<br>
INTO TEMP xxx with no log;
``` | What field would it match with? BTW, here's how to line them up:
```
SELECT NULL, NULL, NULL, NULL, MySingleField, NULL, NULL, NULL... FROM #temp
UNION ALL
SELECT Col1, Col2, Col3, Col4, Col5, Col6,... FROM OtherTable
```
UPDATE:
OK, after reading your update... I don't think you want a UNION at all, but rather, and incredibly simple SUBSELECT
```
SELECT
*,
(SELECT TOP 1 Name FROM Blah WHERE Blah.SomeID = MyTable.SomeID) AS ExtraCol
FROM
MyTable
``` | It sounds like you do want a join, not a union.
You don't need to compare anything to do a join. You end up with a cross product if you specify no join condition:
```
SELECT t20.*, t1.*
FROM table_with_20_columns AS t20
LEFT OUTER JOIN temp_table_with_1_column AS t1 ON (1=1);
```
When there are zero rows in the temp table, it'll be reported as NULL in the result of the above query.
However, if there are multiple rows in the temp table, you'll get the cross product with the first table. I can't tell from your question what you want.
**edit:** The join condition expressed in the `ON` or `USING` clause should be optional according to the SQL standard, but at least as I test it in MySQL 5.0, it's a syntax error to omit that clause. But you can use `ON (1=1)`.
**edit:** Answering your question in the comment:
```
SELECT COALESCE(reqhead_rec.resp_name, dflt.resp_name) AS resp_name
FROM (SELECT 'default name' AS resp_name) dflt
LEFT OUTER JOIN reqhead_rec ON (1=1)
WHERE reqhead_rec.req_no = biglist.req_no AND reqhead_rec.frm = biglist.req_frm
INTO TEMP grabname WITH NO LOG;
```
Actually, you may be able to skip the temp table altogether. Just LEFT JOIN your main table to `reahead_rec`. Put those conditions into the `ON` clause of the join, not in the `WHERE` clause. Then use `COALESCE()` in the select-list of that query to give a default name when one is not found in the other table.
```
SELECT b.*, COALESCE(r.resp_name, 'default name') AS resp_name
FROM biglist AS b
LEFT OUTER JOIN reqhead_rec AS r
ON (b.req_no = r.req_no AND r.frm = b.req_frm)
INTO TEMP xxx WITH NO LOG;
``` | Simple SQL code evades me.. Unionize two mismatched tables | [
"",
"sql",
"join",
"union",
"sql-update",
""
] |
What does generator comprehension do? How does it work? I couldn't find a tutorial about it. | Do you understand list comprehensions? If so, a generator expression is like a list comprehension, but instead of finding all the items you're interested and packing them into list, it waits, and yields each item out of the expression, one by one.
```
>>> my_list = [1, 3, 5, 9, 2, 6]
>>> filtered_list = [item for item in my_list if item > 3]
>>> print(filtered_list)
[5, 9, 6]
>>> len(filtered_list)
3
>>> # compare to generator expression
...
>>> filtered_gen = (item for item in my_list if item > 3)
>>> print(filtered_gen) # notice it's a generator object
<generator object <genexpr> at 0x7f2ad75f89e0>
>>> len(filtered_gen) # So technically, it has no length
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()
>>> # We extract each item out individually. We'll do it manually first.
...
>>> next(filtered_gen)
5
>>> next(filtered_gen)
9
>>> next(filtered_gen)
6
>>> next(filtered_gen) # Should be all out of items and give an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> # Yup, the generator is spent. No values for you!
...
>>> # Let's prove it gives the same results as our list comprehension
...
>>> filtered_gen = (item for item in my_list if item > 3)
>>> gen_to_list = list(filtered_gen)
>>> print(gen_to_list)
[5, 9, 6]
>>> filtered_list == gen_to_list
True
>>>
```
Because a generator expression only has to yield one item at a time, it can lead to big savings in memory usage. Generator expressions make the most sense in scenarios where you need to take one item at a time, do a lot of calculations based on that item, and then move on to the next item. If you need more than one value, you can also use a generator expression and grab a few at a time. If you need all the values before your program proceeds, use a list comprehension instead. | A generator comprehension is the lazy version of a list comprehension.
It is just like a list comprehension except that it returns an iterator instead of the list ie an object with a next() method that will yield the next element.
If you are not familiar with list comprehensions see [here](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and for generators see [here](http://docs.python.org/tutorial/classes.html#generators). | How does a generator comprehension works? | [
"",
"python",
"generator",
""
] |
I have a situation where in a web application a user may need a variable list of PDFs to be printed. That is, given a large list of PDFs, the user may choose an arbitrary subset of that list to print. These PDFs are stored on the file system. I need a method to allow users to print these batches of PDFs relatively easily (thus, asking the user to click each PDF and print is not an option) and without too much of a hit on performance.
A couple of options I've thought about:
1) I have a colleague who uses a PDF library that I could use to take the PDFs and combine them on the fly and then send that PDF to the user for printing. I don't know if this method will mess up any sort of page numbering. This may be an "ok" method but I worry about the performance hit of this.
2) I've thought about creating an ActiveX that I would pass the PDFs off to and let it invoke the printing features. My concern is that this is needlessly complex and may present some odd user interactions.
So, I'm looking for the best option to use in this scenario, which is probably not one of the ones I've gone through. | The best solution I have for you is number 1. There are plenty of libraries that will merge documents. From the one I've used the numbering should not be an issue since all the pages are all ready rendered.
If you go with ActiveX you are going to limit yourself to IE which might be acceptable. The only other idea would be to use a smart client so you can have more control...then you could serve up the PDF's via a web service. | I think concatenating the documents is the way to go.
For tools I recommend iText#. Its free
You can download here [iTextSharp](http://sourceforge.net/projects/itextsharp/)
> iText# (iTextSharp) is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform. Use the iText mailing list to get support. | Batch Printing PDFs from ASP.NET | [
"",
"c#",
"asp.net",
"pdf",
"printing",
""
] |
I have a project that builds fine If I build it manually but it fails with CC.NET.
The error that shows up on CC.NET is basically related to an import that's failing because file was not found; one of the projects (C++ dll) tries to import a dll built by another project. Dll should be in the right place since there's a dependency between the projects - indeeed when I build manually everything works fine (Note that when I say manually I am getting everything fresh from source code repository then invoking a Rebuild from VS2005 to simulate CC.NET automation).
looks like dependencies are ignored when the build is automated through CC.NET.
I am building in Release MinDependency mode.
Any help would be highly appreciated! | Can you change CC to use msbuild instead of devenv? That seems like the optimal solution to me, as it means the build is the same in both situations. | After a long investigation - my understanding on this at current stage is that the problem is related to the fact that I am using devenv to build through CruiseControl.NET but when I build manually VisualStudio is using msbuild.
Basically this causes dependencies to be ignored (because of some msbuild command arg that I am not reproducing using devenv).
I think the fact that dependencies are set between C++ projects is relevant too to some extent, since I've been able in other occasions to build properly with CC.NET setting dependencies between .NET projects and C++ projects.
In order to figure out exactly what is generating this different
behavior I'd have to follow [this lead](https://stackoverflow.com/questions/280559/how-to-get-cmd-line-build-command-for-vs-solution).
I'd like to hear other people's opinions on this. | Why Build Fails with CruiseControl.NET but it builds fine manually with same settings? | [
"",
"c++",
"dll",
"cruisecontrol.net",
""
] |
If I have records:
```
Row Date, LocationID, Account
1 Jan 1, 2008 1 1000
2 Jan 2, 2008 1 1000
3 Jan 3, 2008 2 1001
4 Jan 3, 2008 1 1001
5 Jan 3, 2008 3 1001
6 Jan 4, 2008 3 1002
```
I need to get the row (`date`, `locatinid`, `account`) where the row has the most recent date for each distinct `locationid`:
```
4 Jan 3, 2008 1 1001
3 Jan 3, 2008 2 1001
6 Jan 4, 2008 3 1002
``` | I think this would work:
```
SELECT t1.*
FROM table t1
JOIN (SELECT MAX(Date), LocationID
FROM table
GROUP BY Date, LocationID) t2 on t1.Date = t2.Date and t1.LocationID = t2.LocationID
``` | Try something like:
```
select *
from mytable t1
where date = (select max(date) from mytable t2
where t2.location = t1.location);
``` | help with distinct rows and data ordering | [
"",
"sql",
"sql-server",
""
] |
I have a query to the effect of
```
SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
LIMIT 10,20
```
I want to know to many total rows this query would return without the LIMIT (so I can show pagination information).
Normally, I would use this query:
```
SELECT COUNT(t3.id) FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
```
However the GROUP BY changes the meaning of the COUNT, and instead I get a set of rows representing the number of unique t3.id values in each group.
Is there a way to get a count for the total number of rows when I use a GROUP BY? I'd like to avoid having to execute the entire query and just counting the number of rows, since I only need a subset of the rows because the values are paginated. I'm using MySQL 5, but I think this pretty generic. | There is a nice solution in MySQL.
Add the keyword SQL\_CALC\_FOUND\_ROWS right after the keyword SELECT :
```
SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3
WHERE (associate t1,t2, and t3 with each other)
GROUP BY t3.id
LIMIT 10,20
```
After that, run another query with the function FOUND\_ROWS() :
```
SELECT FOUND_ROWS();
```
It should return the number of rows without the LIMIT clause.
Checkout this page for more information : <http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows> | Are the "bunch of other stuff" all aggregates? I'm assuming so since your GROUP BY only has t3.id. If that's the case then this should work:
```
SELECT
COUNT(DISTINCT t3.id)
FROM...
```
The other option of course is:
```
SELECT
COUNT(*)
FROM
(
<Your query here>
) AS SQ
```
I don't use MySQL, so I don't know if these queries will work there or not. | Getting the number of rows with a GROUP BY query | [
"",
"sql",
"mysql",
""
] |
I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute.
```
CONSTRAINT film_rating_check CHECK
((((((((rating)::text = ''::text) OR
((rating)::text = 'G'::text)) OR
((rating)::text = 'PG'::text)) OR
((rating)::text = 'PG-13'::text)) OR
((rating)::text = 'R'::text)) OR
((rating)::text = 'NC-17'::text)))
```
I think it would be nice to use a Java enum to map the constraint into the object world. But it's not possible to simply take the allowed values because of the special char in "PG-13" and "NC-17". So I implemented the following enum:
```
public enum Rating {
UNRATED ( "" ),
G ( "G" ),
PG ( "PG" ),
PG13 ( "PG-13" ),
R ( "R" ),
NC17 ( "NC-17" );
private String rating;
private Rating(String rating) {
this.rating = rating;
}
@Override
public String toString() {
return rating;
}
}
@Entity
public class Film {
..
@Enumerated(EnumType.STRING)
private Rating rating;
..
```
With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:
> [TopLink Warning]: 2008.12.09
> 01:30:57.434--ServerSession(4729123)--Exception [TOPLINK-116] (Oracle
> TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))):
> oracle.toplink.essentials.exceptions.DescriptorException Exception
> Description: No conversion value provided for the value [NC-17] in
> field [FILM.RATING]. Mapping:
> oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING]
> Descriptor: RelationalDescriptor(de.fhw.nsdb.entities.Film -->
> [DatabaseTable(FILM)])
cheers
timo | Sounds like you need to add support for a custom type:
[Extending OracleAS TopLink to Support Custom Type Conversions](http://www.oracle.com/technetwork/middleware/ias/index-097678.html) | have you tried to store the ordinal value. Store the string value works fine if you don't have an associated String to the value:
```
@Enumerated(EnumType.ORDINAL)
``` | How to use enums with JPA | [
"",
"java",
"jpa",
"enums",
"toplink",
""
] |
The top of my `web.xml` file looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
```
But I still get the warning from Eclipse (Ganymede) that no XML schema is detected, and schema violations are not being warned about. Other XML files in my project ([Spring Framework](http://en.wikipedia.org/wiki/Spring_Framework) configuration files for example) don't have the warning and do give correct warnings about schema violations.
How do I get the schema checking working and hopefully the warning to go away? The server does run correctly. It just appears to be an IDE issue. | Perhaps try:
```
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
```
Instead of:
```
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd
```
---
Also, the `<!DOCTYPE ...>` is missing:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- ... -->
</web-app>
``` | I hate that warning too. Specially because it appears in XML files that you haven't written but appear in your project for whatever reason (if you use MAVEN it's hell).
With Eclipse 3.5+ you can easily remove this validation rule. Go to Preferences-->XML-->XML FILES --> Validation and Select "ignore".
You may also have to do a Project -> Clean for the validation warnings to go away.
 | Bogus Eclipse warning for web.xml: "No grammar constraints (DTD or XML schema) detected for the document." | [
"",
"java",
"eclipse",
"xsd",
"warnings",
""
] |
I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this:
```
public string GetCheckboxHtml()
{
return ("<input type="checkbox" name="somename" />");
}
```
Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead:
```
var checkbox = new HtmlCheckbox(attributes);
return checkbox.Html();
```
I just can't think of the correct namespace to look for this or the correct search term to use in Google. | Well, if you download the [ASP.NET MVC](http://www.codeplex.com/aspnet/Wiki/View.aspx?title=MVC&referringTitle=Home) DLL's (which you can use in *any* type of project... including Console apps)... then you can use the many HTML helpers they have. | One option is to use [XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) [functional construction](http://msdn.microsoft.com/en-us/library/bb387019.aspx). See [this blog post](http://jacobcarpenter.wordpress.com/2008/04/16/pc1-a-solution/) for an example calendar generator.
In your case, your Html could be generated with:
```
var input = new XElement("input",
new XAttribute("type", "checkbox"),
new XAttribute("name", "somename"));
return input.ToString();
``` | In C# 3.0, are there any classes that help me generate static html? | [
"",
"c#",
"html",
""
] |
I have an API call in my application where I am checking the time taken for a single call. I have put this in a FOR loop and using 10000 calls to get the average times of all calls. Now the issue which came up was that the actual application using the API, is multi-threaded. If I wish to make my application also do the same, how would I go about doing this?
The platform is REL and my aim is to send multiple calls in the same time with either the same parameters or different parameters. Can this be implemented in C++ and if so, what library functions to use and can an example be provided for the same? | Probably the best C++ library to use for threading is the thread library in Boost, but like all C++ threading, you will be forced to manually do your synchronization. You will need to use mutex and lock types to make it work properly. Your question isn't very clear, so I can't really help you any more (though I think you don't actually need threading, but I could be completely misunderstanding). | If you read the Miranda IM source code, it should get you started. It's very well done and there are some nice hints in the code for how to rebase the memory offsets of other executables (on Windows) to make them load faster.
<http://www.miranda-im.org/development/> | Implementing threads using C++ | [
"",
"c++",
"multithreading",
""
] |
I have three tables in the many-to-many format. I.e, table A, B, and AB set up as you'd expect.
Given some set of A ids, I need to select only the rows in AB that match all of the ids.
Something like the following won't work:
"SELECT \* FROM AB WHERE A\_id = 1 AND A\_id = 2 AND A\_id = 3 AND ... "
As no single row will have more than one A\_id
Using, an OR in the sql statment is no better as it yields results all results that have at least one of the A ids (whereas I only want those rows that have all of the ids).
**Edit:**
Sorry, I should explain. I don't know if the actual many-to-many relationship is relevant to the actual problem. The tables are outlined as follows:
```
Table People
int id
char name
Table Options
int id
char option
Table peoples_options
int id
int people_id
int option_id
```
And so I have a list of people, and a list of options, and a table of options and people.
So, given a list of option ids such as (1, 34, 44, ...), I need to select only those people that have all the options. | A bit of a hacky solution is to use IN with a group by and having filter. Like so:
```
SELECT B_id FROM AB
WHERE A_id IN (1,2,3)
GROUP BY B_id
HAVING COUNT(DISTINCT A_id) = 3;
```
That way, you only get the B\_id values that have exactly 3 A\_id values, and they have to be from your list. I used DISTINCT in the COUNT just in case (A\_id, B\_id) isn't unique. If you need other columns, you could then join to this query as a sub-select in the FROM clause of another select statement. | Your database doesn't appear to be normalized correctly. Your `AB` table should have a single `A_id` and a single `B_id` in each of its rows. If that were the case, your `OR`-version should work (although I would use `IN` myself).
Ignore the preceding paragraph. From your edit, you really wanted to know all the `B`'s that have all of a subset of `A`'s in the many-to-many table - see below for the query.
Please tell us the actual schema details, it's a little hard to figure out what you want without that.
I'd expect to see something like:
```
table a:
a_id integer
a_payload varchar(20)
table b:
b_id integer
b_payload varchar(20)
table ab:
a_id integer
b_id integer
```
Based on your description, the only thing I can think of is that you want a list of all the `B`'s that have all of a set of `A`'s in the `AB` table. In which case, you're looking at something like (to get the list of `B`'s that have `A`'s of 1, 3 and 4):
```
select distinct b_id from ab n1
where exists (select b_id from ab where a_id = 1 and b_id = n1.b_id)
and exists (select b_id from ab where a_id = 3 and b_id = n1.b_id)
and exists (select b_id from ab where a_id = 4 and b_id = n1.b_id);
```
This works in DB2 but I'm not sure how much of SQL your chosen server implements. | MySQL strict select of rows involving many to many tables | [
"",
"sql",
"mysql",
"many-to-many",
""
] |
I need to write a 'simple' util to convert from ASCII to EBCDIC?
The Ascii is coming from Java, Web and going to an AS400. I've had a google around, can't seem to find a easy solution (maybe coz there isn't one :( ). I was hoping for an opensource util or paid for util that has already been written.
Like this maybe?
```
Converter.convertToAscii(String textFromAS400)
Converter.convertToEBCDIC(String textFromJava)
```
Thanks,
Scott | [JTOpen](http://jt400.sourceforge.net/), IBM's open source version of their Java toolbox has a collection of classes to access AS/400 objects, including a FileReader and FileWriter to access native AS400 text files. That may be easier to use then writing your own conversion classes.
From the JTOpen homepage:
> Here are just a few of the many i5/OS and OS/400 resources you can access using JTOpen:
>
> * Database -- JDBC (SQL) and record-level access (DDM)
> * Integrated File System
> * Program calls
> * Commands
> * Data queues
> * Data areas
> * Print/spool resources
> * Product and PTF information
> * Jobs and job logs
> * Messages, message queues, message files
> * Users and groups
> * User spaces
> * System values
> * System status | Please note that a String in Java holds text in Java's native encoding. When holding an ASCII or EBCDIC "string" in memory, prior to encoding as a String, you'll have it in a byte[].
```
ASCII -> Java: new String(bytes, "ASCII")
EBCDIC -> Java: new String(bytes, "Cp1047")
Java -> ASCII: string.getBytes("ASCII")
Java -> EBCDIC: string.getBytes("Cp1047")
``` | Convert String from ASCII to EBCDIC in Java? | [
"",
"java",
"ascii",
"ibm-midrange",
"ebcdic",
""
] |
I've got a collection of records to process, and the processing can be parallelized, so I've created an [ExecutorService](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html) (via [Executors#newCachedThreadPool()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool())). The processing of an individual record is, itself, composed of parallelizable steps, so I'd like to use another `ExecutorService`. Is there an easy way to make this new one use the same underlying thread pool? Is it even desirable? Thanks. | To answer your question: **no**, two `ExecutorService` objects **cannot** share a thread pool. However you can share an `ExecutorService` between your objects, or alternatively create several Executors, as necessary, though this is less recommended.
Best solution: share the `Executor` between your objects. | Short answer: No.
Longer answer: You will need your own implementation to do that. `ExecutorService` is an interface and `AbstractExecutorService` is quite easy to implement.
If you want two `ExecutorService` sharing same ThreadPool (e.g. with different maximum active thread value), you may use proxy pattern to make ThreadPool sharing `ExecutorService`. | Is it possible for two ExecutorServices to share a thread pool? | [
"",
"java",
"concurrency",
"threadpool",
""
] |
When designing tables, I've developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements:
1. Identity integer column that auto increments.
2. Unique identifier (GUID)
3. A short character(x) or integer (or other relatively small numeric type) column that can serve as a row identifier column
Number 3 would be used for fairly small lookup, mostly read tables that might have a unique static length string code, or a numeric value such as a year or other number.
For the most part, all other tables will either have an auto-incrementing integer or unique identifier primary key.
# The Question :-)
I have recently started working with databases that have no consistent row identifier and primary keys are currently clustered across various columns. Some examples:
* datetime/character
* datetime/integer
* datetime/varchar
* char/nvarchar/nvarchar
Is there a valid case for this? I would have always defined an identity or unique identifier column for these cases.
In addition there are many tables without primary keys at all. What are the valid reasons, if any, for this?
I'm trying to understand why tables were designed as they were, and it appears to be a big mess to me, but maybe there were good reasons for it.
A third question to sort of help me decipher the answers: In cases where multiple columns are used to comprise the compound primary key, is there a specific advantage to this method vs. a surrogate/artificial key? I'm thinking mostly in regards to performance, maintenance, administration, etc.? | I follow a few rules:
1. Primary keys should be as small as necessary. Prefer a numeric type because numeric types are stored in a much more compact format than character formats. This is because most primary keys will be foreign keys in another table as well as used in multiple indexes. The smaller your key, the smaller the index, the less pages in the cache you will use.
2. Primary keys should never change. Updating a primary key should always be out of the question. This is because it is most likely to be used in multiple indexes and used as a foreign key. Updating a single primary key could cause of ripple effect of changes.
3. Do NOT use "your problem primary key" as your logic model primary key. For example passport number, social security number, or employee contract number as these "natural keys" can change in real world situations. Make sure to add UNIQUE constraints for these where necessary to enforce consistency.
On surrogate vs natural key, I refer to the rules above. If the natural key is small and will never change it can be used as a primary key. If the natural key is large or likely to change I use surrogate keys. If there is no primary key I still make a surrogate key because experience shows you will always add tables to your schema and wish you'd put a primary key in place. | Natural verses artifical keys is a kind of religious debate among the database community - see [this article](https://web.archive.org/web/20171109021306/http://r937.com:80/natural-or-surrogate-key.html) and others it links to. I'm neither in favour of **always** having artifical keys, nor of **never** having them. I would decide on a case-by-case basis, for example:
* US States: I'd go for state\_code ('TX' for Texas etc.), rather than state\_id=1 for Texas
* Employees: I'd usually create an artifical employee\_id, because it's hard to find anything else that works. SSN or equivalent may work, but there could be issues like a new joiner who hasn't supplied his/her SSN yet.
* Employee Salary History: (employee\_id, start\_date). I would **not** create an artifical employee\_salary\_history\_id. What point would it serve (other than ["foolish consistency"](http://en.wikiquote.org/wiki/Consistency))
Wherever artificial keys are used, you should always also declare unique constraints on the natural keys. For example, use state\_id if you must, but then you'd better declare a unique constraint on state\_code, otherwise you are sure to eventually end up with:
```
state_id state_code state_name
137 TX Texas
... ... ...
249 TX Texas
``` | What's the best practice for primary keys in tables? | [
"",
"sql",
"sql-server",
"database",
"relational",
""
] |
Ok we have a number of solutions all with a lot of shared binaries:
what we do is the following.
In a shared drive we have this following layout where there is a directory for every binary dependency and a sub directory for every version
BinaryDep1
-----------Volatile
-----------1.0
-----------1.1
-----------1.2
BinaryDep3
-----------Volatile
-----------1.0
-----------1.1
-----------2.2
BinaryDep3
-----------Volatile
-----------1.0
-----------1.1
-----------1.2
In our solutions we have a XML file that lists out all of the dependencies and versions. We have a script that then goes tothe shared drive and download the dependencies into a sub folder of a solution called /ext
This works very well but has a few flaws that we are looking to improve and i wanted to get people's feedback.
1. We have many solutions so if they all depend on the same version of a binary dependency then we get one copy per solution (as its supposed to be self contained). So if i have 5 solutions that all depend on Syncfusion, i get 5 copies of syncfusion on my desktop. The two issues here are 1) slow download time (5x more than i need to) and takes up lots of disk space.
We like the model where have a local sub directory per solution with /ext so we never have to change project references but these seem like competing forces.
any ideas on how to normalize teh download so we are not downloading 5x the data and same the disk size without having to go to manually updating project references where i have to change reference in VS for every version upgrade. | What about the same struture in all developer machines?
Like:
d:/projects
d:/projects/ext (the shared libraries you need here)
d:/projects/project1
d:/projects/project2
d:/projects/project3
d:/projects/project4
...
ps: I love conventions. | You may want to have a look at [DEVPATH](http://msdn.microsoft.com/en-us/library/cskzh7h6.aspx).
Other StackOverflow reference : [Support for DEVPATH](https://stackoverflow.com/questions/1186892/support-for-devpath) | Managing shared binary dependencies for multiple solutions | [
"",
"c#",
"winforms",
"dependencies",
""
] |
I'm doing a PHP site which displays code examples in various languages (C#, PHP, Perl, Ruby, etc.). Are there any PHP functions which add syntax coloring for these and other languages?
If not, I would at least like to find that one built-in PHP function which does syntax coloring for PHP code, can't find it anymore. Thanks. | Why not do the syntax coloration in the client side?
Use [prettify.js](http://code.google.com/p/google-code-prettify/), its really versatile, Google Code and StackOverflow use it!
Check the [test page](http://google-code-prettify.googlecode.com/svn/trunk/tests/prettify_test.html) for the supported languages. | You'd probably be better off formatting it in javascript actually. There are a few mature javascript syntax colors.
* [highlight.js](http://softwaremaniacs.org/soft/highlight/en/)
* [google highlighter](http://code.google.com/p/syntaxhighlighter/)
* [prettify](http://code.google.com/p/google-code-prettify/) | PHP function which does syntax color parsing for multiple languages? | [
"",
"php",
"syntax-highlighting",
""
] |
There's this Excel file I want users to be able to download from my server. There must be an easy way to initiate the download of the file after a click on the "Download" button... but I have no clue how to make that happen.
I have this so far: (VBscript and ASP)
```
<head>
<script type="text/javascript" src="overzicht.js"></script>
</head>
Set fs=Server.CreateObject("Scripting.FileSystemObject")
if (fs.FileExists("c:\file.xls"))=true then 'fake filename D:
response.write("<input type='button' value='Download Masterfile' class='button' onclick='exportmasterfile();' /><br />")
else
response.write("Masterfile not found. <br />")
end if
set fs=nothing
```
The javascript function is empty. | you're not going to believe this.
Found it...
```
function exportmasterfile()
{ var url='../documenten/Master-File.xls';
window.open(url,'Download');
}
```
Sorry guys! | Actually, if you want a 'more-efficient' (and sexier) way, use:
```
location.href = your_url;
```
That way, you will save the compiler some time in going up to the `location`'s prototype chain up to the `window` object. | Download a file using Javascript | [
"",
"javascript",
"asp-classic",
"vbscript",
""
] |
Here's my scenario:
I've got a table of (let's call them) nodes. Primary key on each one is simply "node\_id".
I've got a table maintaining a hierarchy of nodes, with only two columns: parent\_node\_id and child\_node\_id.
The hierarchy is maintained in a separate table because nodes can have an N:N relationship. That is to say, one node can have multiple children, and multiple parents.
If I start with a node and want to get all of its ancestors (i.e. everything higher up the hierarchy), I could either do several selects, or do it all in one stored procedure.
Anyone with any practical experience with this question know which one is likely to have the best performance? I've read things online that recommend both ways. | "which one is likely to have the best performance? " : No one can know ! The only thing you can do is try both and MEASURE. That's sadly enough the main answer to all performance related questions... except in cases where you clearly have a O(n) difference between algorithms.
And, by the way, "multiple parents" does not make a hierarchy (otherwise I would recommend to read some books by Joe Celko) but a DAG (Direct Acyclic Graph) a much harder beast to tame... | If performance is your concern, then that schema design is not going to work as well for you as others could.
See [More Trees & Hierarchies in SQL](http://www.sqlteam.com/article/more-trees-hierarchies-in-sql) for more info. | MySQL stored procedure vs. multiple selects | [
"",
"php",
"mysql",
"performance",
"apache",
"stored-procedures",
""
] |
If I have a function that needs to work with a `shared_ptr`, wouldn't it be more efficient to pass it a reference to it (so to avoid copying the `shared_ptr` object)?
What are the possible bad side effects?
I envision two possible cases:
1) inside the function a copy is made of the argument, like in
```
ClassA::take_copy_of_sp(boost::shared_ptr<foo> &sp)
{
...
m_sp_member=sp; //This will copy the object, incrementing refcount
...
}
```
2) inside the function the argument is only used, like in
```
Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here
{
...
sp->do_something();
...
}
```
I can't see in both cases a good reason to pass the `boost::shared_ptr<foo>` by value instead of by reference. Passing by value would only "temporarily" increment the reference count due to the copying, and then decrement it when exiting the function scope.
Am I overlooking something?
Just to clarify, after reading several answers: I perfectly agree on the premature-optimization concerns, and I always try to first-profile-then-work-on-the-hotspots. My question was more from a purely technical code-point-of-view, if you know what I mean. | The point of a distinct `shared_ptr` instance is to guarantee (as far as possible) that as long as this `shared_ptr` is in scope, the object it points to will still exist, because its reference count will be at least 1.
```
Class::only_work_with_sp(boost::shared_ptr<foo> sp)
{
// sp points to an object that cannot be destroyed during this function
}
```
So by using a reference to a `shared_ptr`, you disable that guarantee. So in your second case:
```
Class::only_work_with_sp(boost::shared_ptr<foo> &sp) //Again, no copy here
{
...
sp->do_something();
...
}
```
How do you know that `sp->do_something()` will not blow up due to a null pointer?
It all depends what is in those '...' sections of the code. What if you call something during the first '...' that has the side-effect (somewhere in another part of the code) of clearing a `shared_ptr` to that same object? And what if it happens to be the only remaining distinct `shared_ptr` to that object? Bye bye object, just where you're about to try and use it.
So there are two ways to answer that question:
1. Examine the source of your entire program very carefully until you are sure the object won't die during the function body.
2. Change the parameter back to be a distinct object instead of a reference.
General bit of advice that applies here: don't bother making risky changes to your code for the sake of performance until you've timed your product in a realistic situation in a profiler and conclusively measured that the change you want to make will make a significant difference to performance.
**Update for commenter JQ**
Here's a contrived example. It's deliberately simple, so the mistake will be obvious. In real examples, the mistake is not so obvious because it is hidden in layers of real detail.
We have a function that will send a message somewhere. It may be a large message so rather than using a `std::string` that likely gets copied as it is passed around to multiple places, we use a `shared_ptr` to a string:
```
void send_message(std::shared_ptr<std::string> msg)
{
std::cout << (*msg.get()) << std::endl;
}
```
(We just "send" it to the console for this example).
Now we want to add a facility to remember the previous message. We want the following behaviour: a variable must exist that contains the most recently sent message, but while a message is currently being sent then there must be no previous message (the variable should be reset before sending). So we declare the new variable:
```
std::shared_ptr<std::string> previous_message;
```
Then we amend our function according to the rules we specified:
```
void send_message(std::shared_ptr<std::string> msg)
{
previous_message = 0;
std::cout << *msg << std::endl;
previous_message = msg;
}
```
So, before we start sending we discard the current previous message, and then after the send is complete we can store the new previous message. All good. Here's some test code:
```
send_message(std::shared_ptr<std::string>(new std::string("Hi")));
send_message(previous_message);
```
And as expected, this prints `Hi!` twice.
Now along comes Mr Maintainer, who looks at the code and thinks: Hey, that parameter to `send_message` is a `shared_ptr`:
```
void send_message(std::shared_ptr<std::string> msg)
```
Obviously that can be changed to:
```
void send_message(const std::shared_ptr<std::string> &msg)
```
Think of the performance enhancement this will bring! (Never mind that we're about to send a typically large message over some channel, so the performance enhancement will be so small as to be unmeasureable).
But the real problem is that now the test code will exhibit undefined behaviour (in Visual C++ 2010 debug builds, it crashes).
Mr Maintainer is surprised by this, but adds a defensive check to `send_message` in an attempt to stop the problem happening:
```
void send_message(const std::shared_ptr<std::string> &msg)
{
if (msg == 0)
return;
```
But of course it still goes ahead and crashes, because `msg` is never null when `send_message` is called.
As I say, with all the code so close together in a trivial example, it's easy to find the mistake. But in real programs, with more complex relationships between mutable objects that hold pointers to each other, it is easy to *make* the mistake, and hard to construct the necessary test cases to detect the mistake.
The easy solution, where you want a function to be able to rely on a `shared_ptr` continuing to be non-null throughout, is for the function to allocate its own true `shared_ptr`, rather than relying on a reference to an existing `shared_ptr`.
The downside is that copied a `shared_ptr` is not free: even "lock-free" implementations have to use an interlocked operation to honour threading guarantees. So there may be situations where a program can be significantly sped up by changing a `shared_ptr` into a `shared_ptr &`. But it this is not a change that can be safely made to all programs. It changes the logical meaning of the program.
Note that a similar bug would occur if we used `std::string` throughout instead of `std::shared_ptr<std::string>`, and instead of:
```
previous_message = 0;
```
to clear the message, we said:
```
previous_message.clear();
```
Then the symptom would be the accidental sending of an empty message, instead of undefined behaviour. The cost of an extra copy of a very large string may be a lot more significant than the cost of copying a `shared_ptr`, so the trade-off may be different. | I found myself disagreeing with the highest-voted answer, so I went looking for expert opinons and here they are.
From <http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-Scott-Andrei-and-Herb-Ask-Us-Anything>
Herb Sutter: "when you pass shared\_ptrs, copies are expensive"
Scott Meyers: "There's nothing special about shared\_ptr when it comes to whether you pass it by value, or pass it by reference. Use exactly the same analysis you use for any other user defined type. People seem to have this perception that shared\_ptr somehow solves all management problems, and that because it's small, it's necessarily inexpensive to pass by value. It has to be copied, and there is a cost associated with that... it's expensive to pass it by value, so if I can get away with it with proper semantics in my program, I'm gonna pass it by reference to const or reference instead"
Herb Sutter: "always pass them by reference to const, and very occasionally maybe because you know what you called might modify the thing you got a reference from, maybe then you might pass by value... if you copy them as parameters, oh my goodness you almost never need to bump that reference count because it's being held alive anyway, and you should be passing it by reference, so please do that"
Update: Herb has expanded on this here: <http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/>, although the moral of the story is that you shouldn't be passing shared\_ptrs at all "unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership." | C++ - passing references to std::shared_ptr or boost::shared_ptr | [
"",
"c++",
"boost",
"pass-by-reference",
"pass-by-value",
"shared-ptr",
""
] |
Does anyone have any good suggestions for creating a Pipe object in Java which *is* both an InputStream and and OutputStream since Java does not have multiple inheritance and both of the streams are abstract classes instead of interfaces?
The underlying need is to have a single object that can be passed to things which need either an InputStream or an OutputStream to pipe output from one thread to input for another. | It seems the point of this question is being missed. If I understand you correctly, you want an object that functions like an InputStream in one thread, and an OutputStream in another to create a means of communicating between the two threads.
Perhaps one answer is to use composition instead of inheritance (which is recommended practice anyway). Create a Pipe which contains a PipedInputStream and a PipedOutputStream connected to each other, with getInputStream() and getOutputStream() methods.
You can't directly pass the Pipe object to something needing a stream, but you can pass the return value of it's get methods to do it.
Does that work for you? | java.io.PipedOutputStream and java.io.PipedInputStream look to be the classes to use for this scenario. They are designed to be used together to pipe data between threads.
If you really want some single object to pass around it would need to contain one of each of these and expose them via getters. | Input and Output Stream Pipe in Java | [
"",
"java",
"input",
"multiple-inheritance",
""
] |
I am giving link of a pdf file on my web page for download, like below
```
<a href="myfile.pdf">Download Brochure</a>
```
The problem is when user clicks on this link then
* If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader.
* If the Adobe Acrobat is not installed then it pop-up to the user for Downloading the file.
But I want it always pop-up to the user for download, irrespective of "Adobe acrobat" is installed or not.
Please tell me how i can do this? | Instead of linking to the .PDF file, instead do something like
```
<a href="pdf_server.php?file=pdffilename">Download my eBook</a>
```
which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf\_server.php should look like this:
```
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
```
PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value | This is a common issue but few people know there's a simple HTML 5 solution:
```
<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>
```
Where `newfilename` is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, like this:
```
<a href="./directory/yourfile.pdf" download>Download the pdf</a>
```
Compatibility: I tested this on Firefox 21 and Iron, both worked fine. It might not work on HTML5-incompatible or outdated browsers. The only browser I tested that didn't force download is IE...
Check compatibility here: <http://caniuse.com/#feat=download> | How to make PDF file downloadable in HTML link? | [
"",
"php",
"pdf",
"xhtml",
"download",
"markup",
""
] |
I have a set of conditions in my where clause like
```
WHERE
d.attribute3 = 'abcd*'
AND x.STATUS != 'P'
AND x.STATUS != 'J'
AND x.STATUS != 'X'
AND x.STATUS != 'S'
AND x.STATUS != 'D'
AND CURRENT_TIMESTAMP - 1 < x.CREATION_TIMESTAMP
```
Which of these conditions will be executed first? I am using oracle.
Will I get these details in my execution plan?
(I do not have the authority to do that in the db here, else I would have tried) | Are you **sure** you "don't have the authority" to see an execution plan? What about using AUTOTRACE?
```
SQL> set autotrace on
SQL> select * from emp
2 join dept on dept.deptno = emp.deptno
3 where emp.ename like 'K%'
4 and dept.loc like 'l%'
5 /
no rows selected
Execution Plan
----------------------------------------------------------
----------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
----------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 62 | 4 (0)|
| 1 | NESTED LOOPS | | 1 | 62 | 4 (0)|
|* 2 | TABLE ACCESS FULL | EMP | 1 | 42 | 3 (0)|
|* 3 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)|
|* 4 | INDEX UNIQUE SCAN | SYS_C0042912 | 1 | | 0 (0)|
----------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("EMP"."ENAME" LIKE 'K%' AND "EMP"."DEPTNO" IS NOT NULL)
3 - filter("DEPT"."LOC" LIKE 'l%')
4 - access("DEPT"."DEPTNO"="EMP"."DEPTNO")
```
As you can see, that gives quite a lot of detail about how the query will be executed. It tells me that:
* the condition "emp.ename like 'K%'" will be applied first, on the full scan of EMP
* then the matching DEPT records will be selected via the index on dept.deptno (via the NESTED LOOPS method)
* finally the filter "dept.loc like 'l%' will be applied.
This order of application has nothing to do with the way the predicates are ordered in the WHERE clause, as we can show with this re-ordered query:
```
SQL> select * from emp
2 join dept on dept.deptno = emp.deptno
3 where dept.loc like 'l%'
4 and emp.ename like 'K%';
no rows selected
Execution Plan
----------------------------------------------------------
----------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
----------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 62 | 4 (0)|
| 1 | NESTED LOOPS | | 1 | 62 | 4 (0)|
|* 2 | TABLE ACCESS FULL | EMP | 1 | 42 | 3 (0)|
|* 3 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)|
|* 4 | INDEX UNIQUE SCAN | SYS_C0042912 | 1 | | 0 (0)|
----------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("EMP"."ENAME" LIKE 'K%' AND "EMP"."DEPTNO" IS NOT NULL)
3 - filter("DEPT"."LOC" LIKE 'l%')
4 - access("DEPT"."DEPTNO"="EMP"."DEPTNO")
``` | The database will decide what order to execute the conditions in.
Normally (but not always) it will use an index first where possible. | Execution order of conditions in SQL 'where' clause | [
"",
"sql",
"oracle",
"where-clause",
""
] |
I am currently doing some socket programming using C/C++. To be able to use a somewhat cleaner interface, and a more OO structure, I decided to write a few simple wrapper classes around parts of the C socket API, but while doing so I stumbled upon a problem:
Given the following code:
```
// Global method
int foo(int x)
{
return x;
}
// Class that calls the global method
class FooBar
{
public:
void foo() { return; };
void baz() { foo(1); }
};
```
g++ gives the following error message:
```
test.cpp: In member function ‘void FooBar::baz()’:
test.cpp:10: error: no matching function for call to ‘FooBar::foo(int)’
test.cpp:9: note: candidates are: void FooBar::foo()
```
Renaming the class method solves the problem.
Why is it that there is some kind of naming conflict even though the method signatures are different? What is the best way to fix this?
Thanks
/Erik | The problem is that it first looks in the scope of your class, and finds a foo function. The lookup will stop then, and the compiler tries to match arguments. Since it only has the one foo function in that scope in your class, calling the function fails.
You need to explicitly state that you want to call the free function:
```
::foo(1);
```
Another solution is to declare the function within baz:
```
void baz() { int foo(int); foo(1); }
```
The scope that the foo function is assumed to be defined in is the surrounding namespace of your class. | You must use the scope resolution try:
::foo(1); | How to resolve name collision when using c headers? | [
"",
"c++",
"c",
"scope",
""
] |
I would like to manipulate the HTML inside an iframe using jQuery.
I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:
```
$(function(){ //document ready
$('some selector', frames['nameOfMyIframe'].document).doStuff()
});
```
However this doesn't seem to work. A bit of inspection shows me that the variables in `frames['nameOfMyIframe']` are `undefined` unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get `permission denied`-type errors).
Does anyone know of a work-around to this? | I think what you are doing is subject to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy). This should be the reason why you are getting *permission denied type* errors. | If the `<iframe>` is from the same domain, the elements are easily accessible as
```
$("#iFrame").contents().find("#someDiv").removeClass("hidden");
```
More on the [jQuery `.contents()` method](https://api.jquery.com/contents/) and ["how to access an iframe in jQuery"](https://web.archive.org/web/20180608003357/http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/) | How can I access the contents of an iframe with JavaScript/jQuery? | [
"",
"javascript",
"jquery",
"iframe",
"same-origin-policy",
""
] |
My application is already developed and now we are going to change the connection string whatever stored in the session object (Bcoz of Distributed Database Management System (DDBMS))
Problem is here.....
> ```
> In that application There are so many **ObjectDataSource** which are
> ```
>
> initialize with the using **.XSD**
> file. which is related to the
> **TableAdapter** and in which connection string of **TableAdapter**
> is assign from the Web.Config File.
> Now How to change the connection
> string to whatever stored in session
> object?
Thanks in advance. | To change the connection of an XSD at runtime you'll need to set the ConnectionModifier property of the table adapter to Public. If they're created by the "wizard" they will be set to Friend/Internal (VB/C#) by default.
I had trouble finding the ConnectionModifier property (it's not listed in my vs2005 documentation)! If you click the lower area of the XSD (where the queries are) then it should be visible in the properties window to change.
Then you can set the Connection property (it takes an object not a string) where ever you declare your table adapter. | This is one of the reasons I hate Typed Datasets, and is actually one of the short-comings of LinqToSQL as well (but is more easily worked around).
I think you're stuck either regenerating all your typed datasets once you change the connection string, or going in and "customizing" them to use the connection string out of the web.config file at run-time rather than copying it from the web.config at design-time. If you "customize" you then have to worry about losing your customized code whenever you make any changes that cause the typed dataset to be recreated. Such are the pros/cons.
EDIT: I misunderstood the question slightly. Solution is still the same, but only my second proposed solution is viable. You'll have to customize your TableAdapter code and then be careful to maintain it when you make changes to your typed datasets. | Assign connection string to table adapter from session | [
"",
"c#",
"asp.net",
"xsd",
""
] |
The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call `os.system()`. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(`0`). Alternately somebody could show be how to properly use `urllib`. | From [Dive into Python:](http://diveintopython.net/html_processing/extracting_data.html)
```
import urllib
sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
htmlsource = sock.read()
sock.close()
print htmlsource
```
That will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.
Example using urllib2 from the [Python Library Reference:](http://www.python.org/doc/2.5.2/lib/urllib2-examples.html)
```
import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)
```
Edit: Also you might want to take a look at [wget.](http://en.wikipedia.org/wiki/Wget#Using_Wget)
Edit2: Added urllib2 example based on S.Lott's advice | Answering the question,
Python has a subprocess module which allows you to interact with spawned processes.<http://docs.python.org/library/subprocess.html#subprocess.Popen>
It allows you to read the stdout for the invoked process, and even send items to the stdin.
however as you said urllib is a much better option. if you [search](https://stackoverflow.com/search?q=urllib) stackoverflow i am sure you will find at least 10 other related questions... | How do I get data from stdin using os.system() | [
"",
"python",
"shell",
"curl",
"urllib",
"os.system",
""
] |
I need to find the smallest power of two that's greater or equal to a given value. So far, I have this:
```
int value = 3221; // 3221 is just an example, could be any number
int result = 1;
while (result < value) result <<= 1;
```
It works fine, but feels kind of naive. Is there a better algorithm for that problem?
---
Related: *[Rounding up to next power of 2](https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2)* has some C answers; [C++20 `std::bit_ceil()`](https://en.cppreference.com/w/cpp/numeric/bit_ceil) isn't available in C, so the ideas could be useful for older C++ code, too.
Most of the answers to this question predate C++20, but could still be useful if implementing a C++ standard library or compiler.
Also related: language-agnostic *[Given an integer, how do I find the next largest power of two using bit-twiddling?](https://stackoverflow.com/questions/1322510/given-an-integer-how-do-i-find-the-next-largest-power-of-two-using-bit-twiddlin)* has a C++17 `constexpr` answer using GNU extensions. | Here's my favorite. Other than the initial check for whether it's invalid (<0, which you could skip if you knew you'd only have >=0 numbers passed in), it has no loops or conditionals, and thus will outperform most other methods. This is similar to erickson's answer, but I think that my decrementing x at the beginning and adding 1 at the end is a little less awkward than his answer (and also avoids the conditional at the end).
```
/// Round up to next higher power of 2 (return x if it's already a power
/// of 2).
inline int
pow2roundup (int x)
{
if (x < 0)
return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x+1;
}
```
An answer on *[Given an integer, how do I find the next largest power of two using bit-twiddling?](https://stackoverflow.com/questions/1322510/given-an-integer-how-do-i-find-the-next-largest-power-of-two-using-bit-twiddlin/1322548#1322548)* presents some explanation of how this common algorithm works, and examples of the bit-patterns for a couple inputs. (That versions uses `unsigned`, which allows avoiding the `x<0` check and is generally better as discussed in comments.)
The same dec / shift/OR / inc strategy is found in:
* [http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2](http://graphics.stanford.edu/%7Eseander/bithacks.html#RoundUpPowerOf2)
* "Hacker's Delight." by Henry S. Warren, Jr. | ```
ceil(log2(value))
```
`ilog2()` can be calculated in 3 asm instructions e.g., [http://www.asterisk.org/doxygen/1.4/log2comp\_8h-source.html](https://web.archive.org/web/20081205054906/http://www.asterisk.org/doxygen/1.4/log2comp_8h-source.html) | Algorithm for finding the smallest power of two that's greater or equal to a given value | [
"",
"c++",
"algorithm",
"assembly",
"bit-manipulation",
""
] |
I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?
Here my last non-working code:
```
SomeClass = function(id) {
this._id = id;
}
(function() {
function intFun() {
return this._id;
}
SomeClass.prototype.extFun = function() {
return incFun();
}
})();
``` | All **vars** are private:
```
SomeClass = function (id) {
var THIS = this; // unambiguous reference
THIS._id = id;
var intFun = function () { // private
return THIS._id;
}
this.extFun = function () { // public
return intFun();
}
}
```
Use **`THIS`** within private methods since **`this`** won't equal what you might expect. | This is my usual approach:
```
MyClass = function(x, y, z) {
// This is the constructor. When you use it with "new MyClass(),"
// then "this" refers to the new object being constructed. So you can
// assign member variables to it.
this.x = x;
...
};
MyClass.prototype = {
doSomething: function() {
// Here we can use the member variable that
// we created in the constructor.
return this.x;
},
somethingElse: function(a) {
}
};
var myObj = new MyClass(1,2,3);
alert(myObj.doSomething()); // this will return the object's "x" member
alert(myObj.x); // this will do the same, by accessing the member directly
```
Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".
---
An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,
```
myDiv.onclick = myObj.doSomething;
```
In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:
```
myDiv.onclick = function() {
myObj.doSomething.call(myObj);
}
```
It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on. | Encapsulation in javascript | [
"",
"javascript",
""
] |
I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions
I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data.
So I have two problems:
1. The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that?
2. When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it?
If anyone want's any clarifications, just ask.
-- Thank you
---
**Edit:** I'm not quite happy with it, but that's what I managed:
Packet.h: <http://pastebin.com/f512e52f1>
Packet.cpp: <http://pastebin.com/f5d535d19>
PacketFactory.h: <http://pastebin.com/f29b7d637>
PacketFactory.cpp: <http://pastebin.com/f689edd9b>
PacketAcknowledge.h: <http://pastebin.com/f50f13d6f>
PacketAcknowledge.cpp: <http://pastebin.com/f62d34eef>
If someone has the time to look at it and suggest any improvements, I'd be thankful.
---
Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid. | For copying you need to write a clone function, since a constructor cannot be virtual:
```
virtual Packet * clone() const = 0;
```
Which each Packet implementation implement like this:
```
virtual Packet * clone() const {
return new StatePacket(*this);
}
```
for example for StatePacket. Packet classes should be immutable. Once a packet is received, its data can either be copied out, or thrown away. So a assignment operator is not required. Make the assignment operator private and don't define it, which will effectively forbid assigning packages.
For de-serialization, you use the factory pattern: create a class which creates the right message type given the message id. For this, you can either use a switch statement over the known message IDs, or a map like this:
```
struct MessageFactory {
std::map<Packet::IdType, Packet (*)()> map;
MessageFactory() {
map[StatePacket::Id] = &StatePacket::createInstance;
// ... all other
}
Packet * createInstance(Packet::IdType id) {
return map[id]();
}
} globalMessageFactory;
```
Indeed, you should add check like whether the id is really known and such stuff. That's only the rough idea. | Why do we, myself included, always make such simple problems so complicated?
---
Perhaps I'm off base here. But I have to wonder: Is this really the best design for your needs?
By and large, function-only inheritance can be better achieved through function/method pointers, or aggregation/delegation and the passing around of data objects, than through polymorphism.
Polymorphism is a very powerful and useful tool. But it's only one of many tools available to us.
---
It looks like each subclass of Packet will need its own Marshalling and Unmarshalling code. Perhaps inheriting Packet's Marshalling/Unmarshalling code? Perhaps extending it? All on top of handle() and whatever else is required.
That's a lot of code.
While substantially more kludgey, it might be shorter & faster to implement Packet's data as a struct/union attribute of the Packet class.
Marshalling and Unmarshalling would then be centralized.
Depending on your architecture, it could be as simple as write(&data). Assuming there are no big/little-endian issues between your client/server systems, and no padding issues. (E.g. sizeof(data) is the same on both systems.)
Write(&data)/read(&data) **is a bug-prone technique**. But it's often a very fast way to write the first draft. Later on, when time permits, you can replace it with individual per-attribute type-based Marshalling/Unmarshalling code.
*Also:* I've taken to storing data that's being sent/received as a struct. You can bitwise copy a struct with operator=(), which at times has been VERY helpful! Though perhaps not so much in this case.
---
Ultimately, you are going to have a *switch* statement somewhere on that subclass-id type. The factory technique (which is quite powerful and useful in its own right) does this switch for you, looking up the necessary clone() or copy() method/object.
**OR** you could do it yourself in Packet. You could just use something as simple as:
( getHandlerPointer( id ) ) ( this )
---
Another advantage to an approach this kludgey (function pointers), aside from the rapid development time, is that you don't need to constantly allocate and delete a new object for each packet. You can re-use a single packet object over and over again. Or a vector of packets if you wanted to queue them. (Mind you, I'd clear the Packet object before invoking read() again! Just to be safe...)
Depending on your game's network traffic density, allocation/deallocation could get expensive. Then again, **premature optimization is the root of all evil.** And you could always just roll your own new/delete operators. (Yet more coding overhead...)
---
What you lose (with function pointers) is the clean segregation of each packet type. Specifically the ability to add new packet types without altering pre-existing code/files.
---
Example code:
```
class Packet
{
public:
enum PACKET_TYPES
{
STATE_PACKET = 0,
PAUSE_REQUEST_PACKET,
MAXIMUM_PACKET_TYPES,
FIRST_PACKET_TYPE = STATE_PACKET
};
typedef bool ( * HandlerType ) ( const Packet & );
protected:
/* Note: Initialize handlers to NULL when declared! */
static HandlerType handlers [ MAXIMUM_PACKET_TYPES ];
static HandlerType getHandler( int thePacketType )
{ // My own assert macro...
UASSERT( thePacketType, >=, FIRST_PACKET_TYPE );
UASSERT( thePacketType, <, MAXIMUM_PACKET_TYPES );
UASSERT( handlers [ thePacketType ], !=, HandlerType(NULL) );
return handlers [ thePacketType ];
}
protected:
struct Data
{
// Common data to all packets.
int number;
int type;
union
{
struct
{
int foo;
} statePacket;
struct
{
int bar;
} pauseRequestPacket;
} u;
} data;
public:
//...
bool readFromSocket() { /*read(&data); */ } // Unmarshal
bool writeToSocket() { /*write(&data);*/ } // Marshal
bool handle() { return ( getHandler( data.type ) ) ( * this ); }
}; /* class Packet */
```
---
PS: You might dig around with google and grab down cdecl/c++decl. They are very useful programs. Especially when playing around with function pointers.
E.g.:
```
c++decl> declare foo as function(int) returning pointer to function returning void
void (*foo(int ))()
c++decl> explain void (* getHandler( int ))( const int & );
declare getHandler as function (int) returning pointer to function (reference to const int) returning void
``` | C++ design - Network packets and serialization | [
"",
"c++",
"inheritance",
"serialization",
""
] |
Let's say that I'm writing a library in C# and I don't know who is going to consume it.
The public interface of the library has some unsigned types - uint, ushort. Apparently those types are not CLS-compliant and, theoretically speaking, there may be languages that will not be able to consume them.
Are there in reality languages like that? | I believe in the original version of VB.NET, unsigned types were usable but there was no support for them built into the language. This has been addressed in later versions, of course.
Additionally, I suspect that the now-defunct J# has no support for unsigned types (given that Java doesn't have any). | .NET compatibility and CLS compliance are two different things. Anything that can work in some way with the .NET framework could be said to be compatible with it. CLS compliance is more strict. It provides a set of rules for language implementors and library designers to follow so as to create an ecosystem of mutually compatible languages and libraries.
The whole point of a thing like the CLS is to allow you to avoid having to research every example of a language and figure out how to support them all. If you want to do that, you can, but the alternative is to comply with the CLS and therefore know that you will be compatible with anything else (from the past present or future) that also complies with the CLS. | Are there languages compatible with .NET that don't support unsigned types? | [
"",
"c#",
".net",
"programming-languages",
"unsigned",
""
] |
I am considering Smarty as my web app templating solution, and I am now concerned with its performance against plain PHP.
The Smarty site says it should be the same, however, I was not able to find anyone doing real benchmarking to prove the statement right or wrong.
Did anyone do some benchmarking of Smarty vs plain PHP? Or maybe come across some resources on such tests?
Thanks | Because in the end, Smarty compiles and caches the templates files to native PHP-code, there is indeed no theoretical performance difference.
Of course there will always be some performance loss due to the chunk of Smarty-code that needs to be interpreted every time. | You might also want to take at a new template library that is similar to Smarty called [Dwoo](http://dwoo.org) | Smarty benchmark, anyone? | [
"",
"php",
"smarty",
"template-engine",
""
] |
I need to increment a String in java from "aaaaaaaa" to "aaaaaab" to "aaaaaac" up through the alphabet, then eventually to "aaaaaaba" to "aaaaaabb" etc. etc.
Is there a trick for this? | It's not much of a "trick", but this works for 4-char strings. Obviously it gets uglier for longer strings, but the idea is the same.
```
char array[] = new char[4];
for (char c0 = 'a'; c0 <= 'z'; c0++) {
array[0] = c0;
for (char c1 = 'a'; c1 <= 'z'; c1++) {
array[1] = c1;
for (char c2 = 'a'; c2 <= 'z'; c2++) {
array[2] = c2;
for (char c3 = 'a'; c3 <= 'z'; c3++) {
array[3] = c3;
String s = new String(array);
System.out.println(s);
}
}
}
}
``` | You're basically implementing a [Base 26 number system](http://en.wikipedia.org/wiki/Base_26) with leading "zeroes" ("a").
You do it the same way you convert a int to a base-2 or base-10 String, but instead of using 2 or 10, you use 26 and instead of '0' as your base, you use 'a'.
In Java you can easily use this:
```
public static String base26(int num) {
if (num < 0) {
throw new IllegalArgumentException("Only positive numbers are supported");
}
StringBuilder s = new StringBuilder("aaaaaaa");
for (int pos = 6; pos >= 0 && num > 0 ; pos--) {
char digit = (char) ('a' + num % 26);
s.setCharAt(pos, digit);
num = num / 26;
}
return s.toString();
}
```
The basic idea then is to not store the String, but just some counter (int an int or a long, depending on your requirements) and to convert it to the String as needed. This way you can easily increase/decrease/modify your counter without having to parse and re-create the String. | How to increment a java String through all the possibilities? | [
"",
"java",
"string",
""
] |
I'm not a JS guy so I'm kinda stumbling around in the dark. Basically, I wanted something that would add a link to a twitter search for @replies to a particular user while on that person's page.
Two things I am trying to figure out:
1. how to extract the user name from the page so that I can construct the right URL. ie. if I am on <http://twitter.com/ev> , I should get "ev" back.
2. how to manipulate the DOM to insert things at the right place
Here's the HTML fragment I'm targetting:
```
<ul id="tabMenu">
<li>
<a href="/ev" id="updates_tab">Updates</a> </li>
<li>
<a href="/ev/favourites" id="favorites_tab">Favorites</a> </li>
</ul>
```
And here is the script (so far):
```
// ==UserScript==
// @name Twitter Replies Search
// @namespace http://jauderho.com/
// @description Find all the replies for a particular user
// @include http://twitter.com/*
// @include https://twitter.com/*
// @exclude http://twitter.com/home
// @exclude https://twitter.com/home
// @author Jauder Ho
// ==/UserScript==
var menuNode = document.getElementById('tabMenu');
if (typeof(menuNode) != "undefined" && menuNode != null)
{
var html = [];
html[html.length] = '<li>';
html[html.length] = '<a href="http://search.twitter.com/search?q=to:ev" class="section-links" id="replies_search_tab">@Replies Search</a>';
html[html.length] = '</li>';
// this is obviously wrong
var div = document.createElement('div');
div.className = 'section last';
div.innerHTML = html.join('');
followingNode = menuNode.parentNode;
followingNode.parentNode.insertBefore(div, followingNode);
}
``` | Here's a pure-DOM method of the above -- and for kicks, I played with the extraction of the username as well:
```
var menuNode = document.getElementById('tabMenu');
if (menuNode!=null)
{
// extract username from URL; matches /ev and /ev/favourites
var username = document.location.pathname.split("/")[1];
// create the link
var link = document.createElement('a');
link.setAttribute('href', 'http://search.twitter.com/search?q=to:'+username);
link.setAttribute('id', 'replies_search_tab');
link.appendChild(document.createTextNode('@Replies Search'));
// create the list element
var li = document.createElement('li');
// add link to the proper location
li.appendChild(link);
menuNode.appendChild(li);
}
```
This is equivalent to (based on the original code snippet):
```
<ul id="tabMenu">
<li>
<a href="/ev" id="updates_tab">Updates</a> </li>
<li>
<a href="/ev/favourites" id="favorites_tab">Favorites</a> </li>
<li>
<a href="http://search.twitter.com/search?q=to:ev" id="replies_search_tab">@Replies Search</a></li>
</ul>
```
If you want the added link to show up in a different location, you'll need to futz around with `insertBefore` a bit.
PS. Took the liberty of ignoring the "section-links" class, as that's formatting for x following, y followers, z updates links. | Here is a way to do it, not really tested (no twitter account).
```
var userName = window.location.href.match(/^http:\/\/twitter\.com\/(\w+)/)
if (userName == null)
return; // Problem?
userName = userName[1];
var menuNode = document.getElementById('tabMenu');
if (menuNode != null)
{
var html = '<a href="http://search.twitter.com/search?q=to:' +
userName +
'" class="section-links" id="replies_search_tab">@Replies Search</a>';
var li = document.createElement('li');
li.className = 'section last';
li.innerHTML = html;
menuNode.appendChild(li);
}
```
It adds the li to the end, and I dropped the div because I doubt it is correct to put a li in a div. If you really need to put the li at the start of the ul, try `menuNode.insertBefore(li, menuNode.firstChild)` | A little help with DOM manip and GreaseMonkey | [
"",
"javascript",
"twitter",
"greasemonkey",
""
] |
I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's [On packaging](http://www.b-list.org/weblog/2008/dec/14/packaging/) post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest it. I would count myself among them, but I do actually use it.
I've used setuptools for enough projects to be aware of its deficiencies, and I would prefer something better. I don't particularly like the egg format and how it's deployed. With all of setuptools' problems, I haven't found a better alternative.
My understanding of tools like [pip](http://pip.openplans.org/) is that it's meant to be an easy\_install replacement (not setuptools). In fact, pip uses some setuptools components, right?
Most of my packages make use of a setuptools-aware setup.py, which declares all of the dependencies. When they're ready, I'll build an sdist, bdist, and bdist\_egg, and upload them to pypi.
If I wanted to switch to using pip, what kind of changes would I need to make to rid myself of easy\_install dependencies? Where are the dependencies declared? I'm guessing that I would need to get away from using the egg format, and provide just source distributions. If so, how do i generate the egg-info directories? or do I even need to?
How would this change my usage of virtualenv? Doesn't virtualenv use easy\_install to manage the environments?
How would this change my usage of the setuptools provided "develop" command? Should I not use that? What's the alternative?
I'm basically trying to get a picture of what my development workflow will look like.
Before anyone suggests it, I'm not looking for an OS-dependent solution. I'm mainly concerned with debian linux, but deb packages are not an option, for the reasons Ian Bicking outlines [here](http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/). | pip uses Setuptools, and doesn't require any changes to packages. It actually installs packages with Setuptools, using:
```
python -c 'import setuptools; __file__="setup.py"; execfile(__file__)' \
install \
--single-version-externally-managed
```
Because it uses that option (`--single-version-externally-managed`) it doesn't ever install eggs as zip files, doesn't support multiple simultaneously installed versions of software, and the packages are installed flat (like `python setup.py install` works if you use only distutils). Egg metadata is still installed. pip also, like easy\_install, downloads and installs all the requirements of a package.
*In addition* you can also use a requirements file to add other packages that should be installed in a batch, and to make version requirements more exact (without putting those exact requirements in your `setup.py` files). But if you don't make requirements files then you'd use it just like easy\_install.
For your `install_requires` I don't recommend any changes, unless you have been trying to create very exact requirements there that are known to be good. I think there's a limit to how exact you can usefully be in `setup.py` files about versions, because you can't really know what the future compatibility of new libraries will be like, and I don't recommend you try to predict this. Requirement files are an alternate place to lay out conservative version requirements.
You can still use `python setup.py develop`, and in fact if you do `pip install -e svn+http://mysite/svn/Project/trunk#egg=Project` it will check that out (into `src/project`) and run `setup.py develop` on it. So that workflow isn't any different really.
If you run pip verbosely (like `pip install -vv`) you'll see a lot of the commands that are run, and you'll probably recognize most of them. | For starters, pip is really new. New, incomplete and largely un-tested in the real world.
It shows great promise but until such time as it can do everything that easy\_install/setuptools can do it's not likely to catch on in a big way, certainly not in the corporation.
Easy\_install/setuptools is big and complex - and that offends a lot of people. Unfortunately there's a really good reason for that complexity which is that it caters for a huge number of different use-cases. My own is supporting a large ( > 300 ) pool of desktop users, plus a similar sized grid with a frequently updated application. The notion that we could do this by allowing every user to install from source is ludicrous - eggs have proved themselves a reliable way to distribute my project.
My advice: Learn to use setuptools - it's really a wonderful thing. Most of the people who hate it do not understand it, or simply do not have the use-case for as full-featured distribution system.
:-) | Questions about Setuptools and alternatives | [
"",
"python",
"packaging",
"setuptools",
"pip",
""
] |
I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways. | ```
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
```
returns
```
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
```
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: [msdn:CREATE TABLE (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms174979.aspx) and [CREATE TABLE (SQL Server 2000)](http://msdn.microsoft.com/en-us/library/aa258255%28SQL.80%29.aspx):
> Only one identity column can be created per table. | You can use Sequence for second column with default value IF you use SQL Server 2012
```
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
```
<http://technet.microsoft.com/en-us/library/ff878058.aspx> | Can a sql server table have two identity columns? | [
"",
"sql",
"sql-server",
"identity-column",
""
] |
I have a database (NexusDB (supposedly SQL-92 compliant)) which contains and Item table, a Category table, and a many-to-many ItemCategory table, which is just a pair of keys. As you might expect, Items are assigned to multiple categories.
I am wanting to all the end user to select all items which are
ItemID | CategoryID
--------------------------------
01 | 01
01 | 02
01 | 12
02 | 01
02 | 02
02 | 47
03 | 01
03 | 02
03 | 14
etc...
I want to be able to select all ItemID's that are assigned to Categories X, Y, and Z but NOT assigned to Categories P and Q.
For the example data above, for instance, say I'd like to grab all Items assigned to Categories 01 or 02 but NOT 12 (yielding Items 02 and 03). Something along the lines of:
SELECT ItemID WHERE (CategoryID IN (01, 02))
...and remove from that set SELECT ItemID WHERE NOT (CategoryID = 12)
This is probably a pretty basic SQL question, but it's stumping me at the moment. Any help w/b appreciated. | You could try with EXCEPT
```
SELECT ItemID FROM Table
EXCEPT
SELECT ItemID FROM Table
WHERE
CategoryID <> 12
``` | > I want to be able to select all
> ItemID's that are assigned to
> Categories X, Y, and Z but NOT
> assigned to Categories P and Q.
I can't confirm from the NexusDB documentation on [SELECT](http://www.nexusdb.com/support/index.php?q=node/384) that they support subqueries, but they do support LEFT OUTER JOIN and GROUP BY. So here's a query that works within these restrictions:
```
SELECT i1.ItemID
FROM ItemCategory i1
LEFT OUTER JOIN ItemCategory i2
ON (i1.ItemID = i2.ItemID AND i2.CategoryID IN ('P', 'Q'))
WHERE i1.CategoryID IN ('X', 'Y', 'Z')
AND i2.ItemID IS NULL
GROUP BY i1.ItemID
HAVING COUNT(i1.CategoryID) = 3;
``` | SQL question: excluding records | [
"",
"sql",
"nexusdb",
"sql-match-all",
""
] |
The topic generically says it all. Basically in a situation like this:
```
boost::scoped_array<int> p(new int[10]);
```
Is there any appreciable difference in performance between doing: `&p[0]` and `p.get()`?
I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace p with a native pointer or array and not have to change anything else.
I am guessing since get is a one liner "`return ptr;`" that the compiler will inline that, and I hope that it is smart enough to to inline `operator[]` in such a way that it is able to not dereference and then immediately reference.
Anyone know? | OK, I've done some basic tests as per Martin York's suggestions.
It seems that g++ (4.3.2) is actually pretty good about this. At both -O2 and -O3 optimization levels, it outputs slightly different but functionally equivalent assembly for both `&p[0]` and `p.get()`.
At -Os as expected, it took the path of least complexity and emits a call to the `operator[]`. One thing to note is that the `&p[0]` version does cause g++ to emit a copy of the `operator[]` body, but it is never used, so there is a slight code bloat if you never use `operator[]` otherwise:
The tested code was this (with the `#if` both 0 and 1):
```
#include <boost/scoped_array.hpp>
#include <cstdio>
int main() {
boost::scoped_array<int> p(new int[10]);
#if 1
printf("%p\n", &p[0]);
#else
printf("%p\n", p.get());
#endif
}
``` | The only way to know is to actually measure it!
But if you have the source of the boost:scoped\_array you could llok at the code and see what it does. I am sure it is pretty similar.
```
T * scoped_array::get() const // never throws
{
return ptr;
}
T & scoped_array::operator[](std::ptrdiff_t i) const // never throws
{
BOOST_ASSERT(ptr != 0);
BOOST_ASSERT(i >= 0);
return ptr[i];
}
```
Write two versions of the code (one using get() the other using operator[]). Compile to assembley with optimizations turned on. See if your compiler actually manages to optimize away the ptr+0. | Performance implications of &p[0] vs. p.get() in boost::scoped_array | [
"",
"c++",
"performance",
"boost",
""
] |
why this is happen ?
When u create abstract class in c++ Ex: **Class A** (which has a pure virtual function)
after that **class B** is inherited from class **A**
And if **class A** has constructor called **A()**
suppose i created an **Object** of **class B** then the compiler initializes the base class first i.e.**class A** and then initialize the **class B** Then.......?
First thing is we can not access a constructor of any class without an Object then how it is initialize the constructor of abstract class if we can not create an object of abstract class . | Quick answer: constructors are special.
When the constructor of A is still running, then the object being constructed is not yet truly of type A. It's still being constructed. When the constructor finishes, it's now an A.
It's the same for the derived B. The constructor for A runs first. Now it's an A. Then the constructor for B starts running. During this, the object is still really an A. Only when B's constructor finishes does it become a B.
You can verify this by trying to call the pure virtual function from the constructors. If the function is defined in A, and B's constructor calls it, there will be a runtime error instead of running B's override, because the object is not of type B yet.
The compiler will not allow you to generate code that will construct an A, due to the pure virtual function. But it will generate code to construct an A as part of the process of constructing a B. There's no magic involved in this. The rule that you cannot construct an A is imposed by the language rules, not by physics. The language lifts that rule under the special circumstance of constructing objects of B. | `class A` is abstract but `class B` is not. In order to construct `class B`, it must implement all the pure virtual member functions of `class A`.
```
class A
{
public:
A() {}
virtual ~A() {}
virtual void foo() = 0; // pure virtual
int i;
};
class B : public A
{
public:
B() {}
virtual ~B() {}
virtual void foo() {}
int j;
};
```
The A class layout could be something like this:
```
+---------+ +---------+
| vftable | --> | ~A() | --> address of A::~A()
+---------+ +---------+
| i | | foo() | --> NULL, pure virtual
+---------+ +---------+
```
The B class layout could be something like this:
```
+---------+ +---------+
| vftable | --> | ~B() | --> address of B::~B()
+---------+ +---------+
| i | | foo() | --> address of B::foo()
+---------+ +---------+
| j |
+---------+
``` | Interesting C++ Abstract Function | [
"",
"c++",
"internals",
""
] |
At a recent discussion on Silverlight the advantage of speed was brought up. The argument for Silverlight was that it performed better in the browser than Javascript because it is compiled (and managed) code.
It was then stated that this advantage only applies to IE because IE interprets Javascript which is inefficient when compared to that of other browsers such as Chrome and FireFox which compile Javascript to machine code before execution and as such perform as well as Silverlight.
Does anybody have a definitive answer to this performance question. i.e. Do/will Silverlight and Javascript have comparable performance on Chrome and Firefox? | Speculating is fun. Or we could actually try a test or two...
That [Silverlight vs. Javascript chess sample](http://silverlight.net/samples/sl2/silverlightchess/run/Default.html) has been updated for Silverlight 2. When I run it, C# averages 420,000 nodes per second vs. Javascript at 23,000 nodes per second. I'm running the dev branch of Google Chrome (v. 0.4.154.25). That's still almost an 18x speed advantage for Silverlight.
Primes calculation shows a 3x advantage for Silverlight: calculating 1,000,000 primes in [Javascript](http://www.tobinharris.com/primes.html) takes 3.7 seconds, in [Silverlight](http://www.itwriting.com/primetest/index.html) takes 1.2 seconds.
So I think that for calculation, there's still a pretty strong advantage for Silverlight, and my gut feel is that it's likely to stay that way. Both sides will continue to optimize, but there are some limits to what you can optimize in a dynamic language.
Silverlight doesn't (yet) have an advantage when it comes to animation. For instance, the [Bubblemark](http://www.bubblemark.com/) test shows Javascript running at 170 fps, and Silverlight running at 100 fps. I think we can expect to see that change [when Silverlight 3 comes out, since it will include GPU support](http://weblogs.asp.net/scottgu/archive/2008/11/16/update-on-silverlight-2-and-a-glimpse-of-silverlight-3.aspx). | Javascript is ran in a virtual machine by most browsers. However, Javascript is still a funky language, and even a "fast" virtual machine like V8 is incredibly slow by modern standards.
I'd expect the CLR to be faster. | Does Silverlight have a performance advantage over JavaScript? | [
"",
"javascript",
"silverlight",
"performance",
""
] |
I'm currently writing some methods that do some basic operations on form controls eg Textbox, Groupbox, these operations are generic and can be used in any application.
I started to write some unit tests and was just wondering should I use the real form controls found in System.Windows.Forms or should I just mock up the sections that I'm trying to test. So for example:
Say I have this method which takes a control and if it is a textbox it will clear the text property like this:
```
public static void clearall(this Control control)
{
if (control.GetType() == typeof(TextBox))
{
((TextBox)control).Clear();
}
}
```
Then I want to test this method so I do something like this:
```
[TestMethod]
public void TestClear()
{
List<Control> listofcontrols = new List<Control>();
TextBox textbox1 = new TextBox() {Text = "Hello World" };
TextBox textbox2 = new TextBox() { Text = "Hello World" };
TextBox textbox3 = new TextBox() { Text = "Hello World" };
TextBox textbox4 = new TextBox() { Text = "Hello World" };
listofcontrols.Add(textbox1);
listofcontrols.Add(textbox2);
listofcontrols.Add(textbox3);
listofcontrols.Add(textbox4);
foreach (Control control in listofcontrols)
{
control.clearall();
Assert.AreEqual("", control.Text);
}
}
```
Should I be adding a referance to System.Window.Forms to my unit test and use the real Textbox object? or am I doing it wrong?
NOTE: The above code is only an example, I didn't compile or run it. | If you're trying to unit test the application logic by simulating interaction with the UI controls, you should do some abstraction using the [MVC pattern](http://en.wikipedia.org/wiki/Model-view-controller). Then you can just have a stub view and call the controller methods from your unit tests.
If it's the actual controls you're trying to unit test, you've got me. | There are several patterns that are useful for separating UI presentation from UI logic including Model-View-Controller and the various incarnations of Model-View-Presenter (AKA Humble Dialog). Humble Dialog was concocted specifically to make unit testing easier. You should definitely have one of these UI patterns in your design arsenal.
But I have found that for simple forms, when the framework supports it, it's quite straightforward to test directly against the real UI controls. I have built quite robust UIs completely test-first in Java Swing and Windows.Forms. I couldn't manage it in SWT or ASP.NET and reverted to MVP.
For testing things like this...
```
[Test] public void ShouldCopyFromAvailableToSelectedWhenAddButtonIsCLicked(){
myForm.AvailableList.Items.Add("red");
myForm.AvailableList.Items.Add("yellow");
myForm.AvailableList.Items.Add("blue");
myForm.AvailableList.SelectedIndex = 1;
myForm.AddButton.Click();
Assert.That(myForm.AvaiableList.Items.Count, Is.EqualTo(2));
Assert.That(myForm.SelectedList.Items[0], Is.EqualTo("yellow"));
}
```
...working directly against the UI controls works fine. But if you want to start testing mouse moves, keystrokes or drag and drop, you'd be better off choosing a more robust UI pattern like the one suggested by Brian. | Unit testing method that uses UI controls | [
"",
"c#",
"unit-testing",
"mocking",
""
] |
I have a function which launches a javascript window, like this
```
function genericPop(strLink, strName, iWidth, iHeight) {
var parameterList = "location=0,directories=0,status=0,menubar=0,resizable=no, scrollbars=no,toolbar=0,maximize=0,width=" + iWidth + ", height=" + iHeight;
var new_window="";
new_window = open(strLink, strName, parameterList);
window.self.name = "main";
new_window.moveTo(((screen.availWidth/2)-(iWidth/2)),((screen.availHeight/2)-(iHeight/2)));
new_window.focus();
}
```
This function is called about 52 times from different places in my web application.
I want to re-factor this code to use a DHTML modal pop-up window. The change should be as unobtrusive as possible.
To keep this solution at par with the old solution, I think would also need to do the following
1. Provide a handle to "Close" the window.
2. Ensure the window cannot be moved, and is positioned at the center of the screen.
3. Blur the background as an option.
I thought [this solution](http://particletree.com/features/lightbox-gone-wild/) is the closest to what I want, but I could not understand how to incorporate it.
Edit: A couple of you have given me a good lead. Thank you. But let me re-state my problem here. I am re-factoring existing code. I should avoid any change to the present HTML or CSS. Ideally I would like to achieve this effect by keeping the function signature of the genericPop(...) same as well. | Here is my solution using jQuery and jQuery UI libraries. Your API is not changed ~~, but parameter 'name' is ignored~~. I use `iframe` to load content from given `strLink` and then display that `iframe` as a child to generated `div`, which is then converted to modal pop-up using jQuery:
```
function genericPop(strLink, strName, iWidth, iHeight) {
var dialog = $('#dialog');
if (dialog.length > 0) {
dialog.parents('div.ui-dialog').eq(0).remove();
}
dialog = $(document.createElement('div'))
.attr('id', 'dialog')
.css('display', 'none')
.appendTo('body');
$(document.createElement('iframe'))
.attr('src', strLink)
.css('width', '100%')
.css('height', '100%')
.appendTo(dialog);
dialog.dialog({
draggable: false,
modal: true,
width: iWidth,
height: iHeight,
title: strName,
overlay: {
opacity: 0.5,
background: "black"
}
});
dialog.css('display', 'block');
}
// example of use
$(document).ready(function() {
$('#google').click(function() {
genericPop('http://www.google.com/', 'Google', 640, 480);
return false;
});
$('#yahoo').click(function() {
genericPop('http://www.yahoo.com/', 'Yahoo', 640, 480);
return false;
});
});
```
[Documentation for jQuery UI/Dialog](http://docs.jquery.com/UI/Dialog). | I use this [dialog code](http://www.leigeber.com/2008/04/custom-javascript-dialog-boxes/) to do pretty much the same thing.
If i remember correctly the default implementation does not support resizing the dialog. If you cant make with just one size you can modify the code or css to display multiple widths.
usage is easy:
```
showDialog('title','content (can be html if encoded)','dialog_style/*4 predefined styles to choose from*/');
```
Modifying the js to support multiple widths:
Add width and height as attributes to show dialog function and the set them to the dialog and dialog-content elements on line 68 | How to refactor from using window.open(...) to an unobtrusive modal dhtml window? | [
"",
"javascript",
"modal-dialog",
""
] |
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created?
Isn't that a bit silly? | I think you are fighting the framework. The data going into your views should be created at the Last Possible Minute (LPM).
Thinking this way, a `SelectList` is a type to feed the `DropDownList` HTML helper. It is NOT a place to store data while you decide how to process it.
A better solution would be to retrieve your data into a `List<T>` and then initialize the `SelectList`(s) when you need to. An immediate benefit of this practice is that it allows you to reuse your `List<T>` for more than one `DropDownList`, such as:
```
Country of birth
Country of residence
```
These `SelectLists` all use the Countries list of type `List<Country>`.
You can use your `List<T>` at the 'last minute' like in this example:
```
public class TaxCheatsFormViewModel
{
private List<Country> countries { get; set; }
public TaxCheat Cheat { get; private set; }
public SelectList CountryOfBirth { get; private set; }
public SelectList CountryOfResidence { get; private set; }
public SelectList CountryOfDomicile { get; private set; }
public TaxCheatsFormViewModel(TaxCheat baddie)
{
TaxCheat = baddie;
countries = TaxCheatRepository.GetList<Country>();
CountryOfBirth = new SelectList(countries, baddie.COB);
CountryOfResidence = new SelectList(countries, baddie.COR);
CountryOfDomicile = new SelectList(countries, baddie.COD);
}
}
```
The point being that you should keep your data in a `List<T>` till you really need to output it; the last possible minute (LPM). | Because this is such a high result in Google, I'm providing what I found to work here (despite the age):
If you are using a Strongly typed View (i.e. the Model has an assigned type), the SelectedValue provided to the Constructor of the SelectList is overwritten by the value of the object used for the Model of the page.
This works well on an edit page, but not for Create when you want to preselect a specific value, so one workaround is simply to assign the correct value on a default constructed object you pass to the view as the Model.
e.g.
```
var model = new SubjectViewModel()
{
Subject = new Subject(),
Types = data.SubjectTypes.ToList()
}
model.Subject.SubjectType = model.Types.FirstOrDefault(t => t.Id == typeId);
ViewData.Model = model;
return View();
```
so the code in my Create View that looks like this:
```
Html.DropDownListFor(model => model.Subject.SubjectTypeId, new SelectList(model.Types, "Id", "Name"))
```
returns the Drop Down List with the value I assigned as the SelectedValue in the list. | Set selected value in SelectList after instantiation | [
"",
"c#",
".net",
"asp.net-mvc",
"selectlist",
""
] |
As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information? | the [verbose name](http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names) of the field is the (optional) first parameter at field construction. | If your field is a property (a method) then you should use short\_description:
```
class Person(models.Model):
...
def address_report(self, instance):
...
# short_description functions like a model field's verbose_name
address_report.short_description = "Address"
``` | Can you change a field label in the Django Admin application? | [
"",
"python",
"python-3.x",
"django",
"django-forms",
"django-admin",
""
] |
I've been using [Rainlendar](http://www.rainlendar.net) for some time and I noticed that it has an option to put the window "on desktop". It's like a bottomMost window (as against topmost).
How could I do this on a WPF app?
Thanks | My answer is in terms of the Win32 API, not specific to WPF (and probably requiring P/Invoke from C#):
Rainlendar has two options:
* "On Desktop", it becomes a child of the Explorer desktop window ("Program Manager"). You could achieve this with the [SetParent](http://msdn.microsoft.com/en-us/library/ms633541(VS.85).aspx) API.
* "On Bottom" is what you describe - its windows stay at the bottom of the Z-order, just in front of the desktop. It's easy enough to put them there to begin with (see [SetWindowPos](http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx)) - the trick is to stop them coming to the front when clicked. I would suggest handling the [WM\_WINDOWPOSCHANGING](http://msdn.microsoft.com/en-us/library/ms632653(VS.85).aspx) message. | This is what I used so the window is always "on bottom":
```
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
```
...
```
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,
int Y, int cx, int cy, uint uFlags);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 SWP_NOACTIVATE = 0x0010;
static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
public static void SetBottom(Window window)
{
IntPtr hWnd = new WindowInteropHelper(window).Handle;
SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}
``` | Window "on desktop" | [
"",
"c#",
"wpf",
""
] |
I have an winforms application that was built using MVC. The controller is subscribing to all of the events from the view (button clicks, etc) and connects multiple views with the model.
The problem is that the controller is now about 3000 lines of (hard to unit test) code.
What is the best practice to avoid getting controllers to do everything and become so big? | One obvious thing to point out might be that one controller does not have to be implemented as one class. The MVC design pattern simply states that M, V and C are separate components, but not that each must be one, and only one, class. | ### Sub controller
Controller can be split in various **sub**-controller without broking the MVC pattern.
At 3k lines, it's for sure that the cohesion is broken somewhere. Try to group together same behavior and create new controller. This way, you will have a "main" controller that will invoke "sub" controller.
### Method without sub:
For my own experience, I do not have 1 controller for the whole WinForm application. How I created it is that I have mutiple module that are loaded from the menu. When those module are loaded (Form->View) it comes with its own Controller. This way, I only have 1 controller for each module. Those controller aren't over 500 lines of code usually. | How to fight against really big controllers . . | [
"",
"c#",
"winforms",
"model-view-controller",
""
] |
I keep on hearing this words '**callback**' and '**postback**' tossed around.
What is the difference between two ?
Is postback very specific to the ASP.NET pages ? | A Postback occurs when the data (the whole page) on the page is posted from the client to the server..ie the **data is posted-back to the server**, and thus the page is refreshed (redrawn)...think of it as '**sending the server the whole page (asp.net) full of data**'.
On the other hand, **a callback is also a special kind of postback**, but it is just a quick round-trip to the server to get a small set of data (normally), and thus the page is not refreshed, unlike with the postback...think of it as '**calling the server, and receiving *some* data back**'.
With Asp.Net, **the ViewState is not refreshed when a callback is invoked**, unlike with a postback.
The reason that the whole page is posted with ASP.Net is because ASP.Net encloses the whole page in a `<form>` with a **post method**, and so when a submit button is clicked in the page, the form is sent to the server with all of the fields that are in the form... basically the whole page itself.
If you are using *FireBug* (for Firefox), you can actually see callbacks being invoked to the server in the `Console`. That way, you will see what *specific data* is being sent to the server (`Request`) and also the data the server sent you back (`Response`).
---
The below image illustrates the Page Life Cycles of both a postback and a callback in a ASP.NET based Website:
[](https://i.stack.imgur.com/6kWWi.png)
(source: [esri.com](http://edndoc.esri.com/arcobjects/9.2/NET_Server_Doc/developer/ADF/graphics%5Cpage_lifecycle.png)) | A postback occurs when a request is sent from the client to the server for the same page as the one the user is currently viewing. When a postback occurs, the entire page is refreshed and you can see the typical progression on the progress bar at the bottom of the browser.
A callback, generally used with AJAX, occurs when a request is sent from the client to the server for which the page is not refreshed, only a part of it is updated without any flickering occuring on the browser | Difference between a Postback and a Callback | [
"",
"asp.net",
"javascript",
"postback",
"callback",
""
] |
When a pointer goes out of scope, its memory is freed, so why are `destructor`s created in c++? | If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example.
Also, 'unscoping' a pointer does *not* free the memory that it points to since other pointers may be referencing it.
If you have a pointer on the stack, exiting the function will free the memory used by the pointer but *not* that memory pointed to by the pointer. There's a subtle but very important distinction. | When a pointer goes out of scope, the memory taken by *the pointer* is released. The 4 or 8 bytes (usually) of memory that are taken by the pointer, that is.
The *object* (or other memory) that the pointer points to is *not* released when the pointer goes out of scope. You do that by *delete*'ing the pointer. And that invokes the destructor, if there is any. | Why are destructors required in C++? | [
"",
"c++",
""
] |
In Mootools, I'd just run `if ($('target')) { ... }`. Does `if ($('#target')) { ... }` in jQuery work the same way? | As the other commenters are suggesting the most efficient way to do it seems to be:
```
if ($(selector).length ) {
// Do something
}
```
If you absolutely must have an exists() function - which will be slower- you can do:
```
jQuery.fn.exists = function(){return this.length>0;}
```
Then in your code you can use
```
if ($(selector).exists()) {
// Do something
}
```
As answered [here](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) | no, jquery always returns a jquery object regardless if a selector was matched or not.
You need to use .length
```
if ( $('#someDiv').length ){
}
``` | How do you check if a selector matches something in jQuery? | [
"",
"javascript",
"jquery",
"jquery-selectors",
""
] |
I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this.
Can anyone help? | You are looking for:
```
final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser( ... );
browser.openURL(url);
``` | If you want it in an external browser, you don't need to create one. This is the way:
```
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL("http://www.example.com/"));
``` | Launching a URL from an Eclipse plugin | [
"",
"java",
"eclipse",
"eclipse-plugin",
""
] |
I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.
Does anyone have a preferred way to do Python code folding in Vim? I.e,
* Do you have a particular Vim plugin that you use and like?
* Do you use manual folding or do you place markers in comments?
* Any other recommended ways to do code folding for Python in Vim? | Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python!
```
set foldmethod=indent
nnoremap <space> za
vnoremap <space> zf
```
This maps the spacebar to open/close the current indented fold in normal mode. It also maps the spacebar to create a manual fold in visual mode. However, this doesn't work if foldmethod is set to indent so its purpose is a mystery. | I use [this](http://www.vim.org/scripts/script.php?script_id=2462 "this") syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else. | What is the recommended way to use Vim folding for Python code? | [
"",
"python",
"vim",
"folding",
""
] |
I have a small calculator that I am creating in C# (Sharp Develop). The user enters two values and the code returns the third. I am having trouble rounding the third value once it is returned. I have been through a couple of forums and the msdn site and I understand the code that is posted there, but I cant seem to make it work in my situation. Can anyone provide a little help? Reference the code below.
```
int y;
decimal x, z;
x = int.Parse(tb2_fla.Text);
y = int.Parse(tb2_e.Text);
z = (x * y * 1.732050808m) / 1000;
tb2_kva.Text = z.ToString();
```
I welcome both assistance and criticism
Greg | Try using Math.Round()
```
tb2_kva.Text = Math.Round(z, # Places).ToString();
``` | Use [Math.Round](http://msdn.microsoft.com/en-us/library/system.math.round.aspx). Or, since you're going into a string, you could use either the [Standard Numeric Format Strings](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx), or the [Custom ones](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx).
```
Math.Round(z, 2).ToString();
z.ToString("0.00");
``` | C# Round Value of a Textbox | [
"",
"c#",
"rounding",
""
] |
Here's some code I have:
```
MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
```
I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.
My question then is how to refer to this `instance` variable from a global scope. I've tried referring to it as `MyClass::getInstance::instance` but that doesn't work. I'm guessing `getInstance` has to be decorated somehow. Anyone know how?
This is in Visual Studio 2008. | Well, the function-scoped static `instance` variable doesn't show up in a `.map` file generated by `cl.exe /Fm`, and it doesn't show up when I use `x programname!*MyClass*` in WinDbg, so the mangled name doesn't seem to contain `MyClass` at all.
**Option 1: Disassemble `MyClass::getInstance`**
This approach seems easier:
```
0:000> uf programname!MyClass::getInstance
programname!MyClass::getInstance [programname.cpp @ 14]:
14 00401050 55 push ebp
14 00401051 8bec mov ebp,esp
15 00401053 a160b34200 mov eax,dword ptr [programname!$S1 (0042b360)]
15 00401058 83e001 and eax,1
15 0040105b 7526 jne funcstat!MyClass::getInstance+0x33 (00401083)
programname!MyClass::getInstance+0xd [programname.cpp @ 15]:
15 0040105d 8b0d60b34200 mov ecx,dword ptr [programname!$S1 (0042b360)]
15 00401063 83c901 or ecx,1
15 00401066 890d60b34200 mov dword ptr [programname!$S1 (0042b360)],ecx
15 0040106c b9b0be4200 mov ecx,offset programname!instance (0042beb0)
15 00401071 e88fffffff call programname!ILT+0(??0MyClassQAEXZ) (00401005)
15 00401076 68e03e4200 push offset programname!`MyClass::getInstance'::`2'::`dynamic atexit destructor for 'instance'' (00423ee0)
15 0040107b e8f3010000 call programname!atexit (00401273)
15 00401080 83c404 add esp,4
programname!MyClass::getInstance+0x33 [programname.cpp @ 16]:
16 00401083 b8b0be4200 mov eax,offset programname!instance (0042beb0)
17 00401088 5d pop ebp
17 00401089 c3 ret
```
From this we can tell that the compiler called the object `$S1`. Of course, this name will depend on how many function-scoped static variables your program has.
**Option 2: Search memory for the object**
To expand on @gbjbaanb's suggestion, if `MyClass` has virtual functions, you might be able to find its location the hard way:
* Make a full memory dump of the process.
* Load the full memory dump into WinDbg.
* Use the `x` command to find the address of MyClass's vtable:
```
0:000> x programname!MyClass::`vftable'
00425c64 programname!MyClass::`vftable' =
```
* Use the `s` command to search the process's virtual address space (in this example, 0-2GB) for pointers to MyClass's vtable:
```
0:000> s -d 0 L?7fffffff 00425c64
004010dc 00425c64 c35de58b cccccccc cccccccc d\B...].........
0040113c 00425c64 8bfc458b ccc35de5 cccccccc d\B..E...]......
0042b360 00425c64 00000000 00000000 00000000 d\B.............
```
* Use the `dt` command to find the class's vtable offset, and subtract that from the addresses returned from the search. These are possible addresses for the object.
```
0:000> dt programname!MyClass
+0x000 __VFN_table : Ptr32
+0x008 x : Int4B
+0x010 y : Float
```
* Use `dt programname!MyClass 0042b360` to examine the object's member variables, testing the hypothesis that the object is located at 0042b360 (or some other address). You will probably get some false positives, as I did above, but by inspecting the member variables you may be able to figure out which one is your singleton.
This is a general technique for finding C++ objects, and is kind of overkill when you could just disassemble `MyClass::getInstance`. | That code just looks dangerous... :-)
But anyway, your mangled name is going to depend on your [Calling Convention](http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx) So before you find your mangle name you need to know what your build environment is using as the calling convention. MSDN has a lot more information on calling convention.
Besides this, one way to find out all this information about your class is to inspect your VTable, which is found in the first 4 bytes of your object. A nifty trick that reversers use is a hidden VC++ Flag [reportSingleClassLayout](http://blogs.msdn.com/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx) that prints the class structure in an ASCII art manner. | How does VC++ mangle local static variable names? | [
"",
"c++",
"scope",
""
] |
For a poor man's implementation of *near*-collation-correct sorting on the client side I need a JavaScript function that does *efficient* single character replacement in a string.
Here is what I mean (note that this applies to German text, other languages sort differently):
```
native sorting gets it wrong: a b c o u z ä ö ü
collation-correct would be: a ä b c o ö u ü z
```
Basically, I need all occurrences of "ä" of a given string replaced with "a" (and so on). This way the result of native sorting would be very close to what a user would expect (or what a database would return).
Other languages have facilities to do just that: [Python supplies `str.translate()`](http://docs.python.org/3.1/library/stdtypes.html#str.translate), in [Perl there is `tr/…/…/`](http://perldoc.perl.org/functions/tr.html), [XPath has a function `translate()`](http://www.w3.org/TR/xpath/#function-translate), [ColdFusion has `ReplaceList()`](http://livedocs.adobe.com/coldfusion/8/functions_m-r_33.html). But what about JavaScript?
Here is what I have right now.
```
// s would be a rather short string (something like
// 200 characters at max, most of the time much less)
function makeSortString(s) {
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
var translate_re = /[öäüÖÄÜ]/g;
return ( s.replace(translate_re, function(match) {
return translate[match];
}) );
}
```
For starters, I don't like the fact that the regex is rebuilt every time I call the function. I guess a closure can help in this regard, but I don't seem to get the hang of it for some reason.
Can someone think of something more efficient?
---
## Answers below fall in two categories:
1. String replacement functions of varying degrees of completeness and efficiency (what I was originally asking about)
2. A [late mention](https://stackoverflow.com/a/42163018/18771) of [`String#localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare), which is now [widely supported](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#Browser_compatibility) among JS engines (not so much at the time of the question) and could solve this category of problem much more elegantly. | I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.
Here is one way to do this:
```
function makeSortString(s) {
if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return ( s.replace(makeSortString.translate_re, function(match) {
return translate[match];
}) );
}
```
This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:
```
makeSortString.translate_re = /[a-z]/g;
```
So, there is that option.
One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:
```
var makeSortString = (function() {
var translate_re = /[öäüÖÄÜ]/g;
return function(s) {
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return ( s.replace(translate_re, function(match) {
return translate[match];
}) );
}
})();
```
Hopefully this is useful to you.
---
UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you `translate` object in a closure as well:
```
var makeSortString = (function() {
var translate_re = /[öäüÖÄÜ]/g;
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return function(s) {
return ( s.replace(translate_re, function(match) {
return translate[match];
}) );
}
})();
``` | Here is a more complete version based on the Unicode standard.
```
var Latinise={};Latinise.latin_map={"Á":"A",
"Ă":"A",
"Ắ":"A",
"Ặ":"A",
"Ằ":"A",
"Ẳ":"A",
"Ẵ":"A",
"Ǎ":"A",
"Â":"A",
"Ấ":"A",
"Ậ":"A",
"Ầ":"A",
"Ẩ":"A",
"Ẫ":"A",
"Ä":"A",
"Ǟ":"A",
"Ȧ":"A",
"Ǡ":"A",
"Ạ":"A",
"Ȁ":"A",
"À":"A",
"Ả":"A",
"Ȃ":"A",
"Ā":"A",
"Ą":"A",
"Å":"A",
"Ǻ":"A",
"Ḁ":"A",
"Ⱥ":"A",
"Ã":"A",
"Ꜳ":"AA",
"Æ":"AE",
"Ǽ":"AE",
"Ǣ":"AE",
"Ꜵ":"AO",
"Ꜷ":"AU",
"Ꜹ":"AV",
"Ꜻ":"AV",
"Ꜽ":"AY",
"Ḃ":"B",
"Ḅ":"B",
"Ɓ":"B",
"Ḇ":"B",
"Ƀ":"B",
"Ƃ":"B",
"Ć":"C",
"Č":"C",
"Ç":"C",
"Ḉ":"C",
"Ĉ":"C",
"Ċ":"C",
"Ƈ":"C",
"Ȼ":"C",
"Ď":"D",
"Ḑ":"D",
"Ḓ":"D",
"Ḋ":"D",
"Ḍ":"D",
"Ɗ":"D",
"Ḏ":"D",
"Dz":"D",
"Dž":"D",
"Đ":"D",
"Ƌ":"D",
"DZ":"DZ",
"DŽ":"DZ",
"É":"E",
"Ĕ":"E",
"Ě":"E",
"Ȩ":"E",
"Ḝ":"E",
"Ê":"E",
"Ế":"E",
"Ệ":"E",
"Ề":"E",
"Ể":"E",
"Ễ":"E",
"Ḙ":"E",
"Ë":"E",
"Ė":"E",
"Ẹ":"E",
"Ȅ":"E",
"È":"E",
"Ẻ":"E",
"Ȇ":"E",
"Ē":"E",
"Ḗ":"E",
"Ḕ":"E",
"Ę":"E",
"Ɇ":"E",
"Ẽ":"E",
"Ḛ":"E",
"Ꝫ":"ET",
"Ḟ":"F",
"Ƒ":"F",
"Ǵ":"G",
"Ğ":"G",
"Ǧ":"G",
"Ģ":"G",
"Ĝ":"G",
"Ġ":"G",
"Ɠ":"G",
"Ḡ":"G",
"Ǥ":"G",
"Ḫ":"H",
"Ȟ":"H",
"Ḩ":"H",
"Ĥ":"H",
"Ⱨ":"H",
"Ḧ":"H",
"Ḣ":"H",
"Ḥ":"H",
"Ħ":"H",
"Í":"I",
"Ĭ":"I",
"Ǐ":"I",
"Î":"I",
"Ï":"I",
"Ḯ":"I",
"İ":"I",
"Ị":"I",
"Ȉ":"I",
"Ì":"I",
"Ỉ":"I",
"Ȋ":"I",
"Ī":"I",
"Į":"I",
"Ɨ":"I",
"Ĩ":"I",
"Ḭ":"I",
"Ꝺ":"D",
"Ꝼ":"F",
"Ᵹ":"G",
"Ꞃ":"R",
"Ꞅ":"S",
"Ꞇ":"T",
"Ꝭ":"IS",
"Ĵ":"J",
"Ɉ":"J",
"Ḱ":"K",
"Ǩ":"K",
"Ķ":"K",
"Ⱪ":"K",
"Ꝃ":"K",
"Ḳ":"K",
"Ƙ":"K",
"Ḵ":"K",
"Ꝁ":"K",
"Ꝅ":"K",
"Ĺ":"L",
"Ƚ":"L",
"Ľ":"L",
"Ļ":"L",
"Ḽ":"L",
"Ḷ":"L",
"Ḹ":"L",
"Ⱡ":"L",
"Ꝉ":"L",
"Ḻ":"L",
"Ŀ":"L",
"Ɫ":"L",
"Lj":"L",
"Ł":"L",
"LJ":"LJ",
"Ḿ":"M",
"Ṁ":"M",
"Ṃ":"M",
"Ɱ":"M",
"Ń":"N",
"Ň":"N",
"Ņ":"N",
"Ṋ":"N",
"Ṅ":"N",
"Ṇ":"N",
"Ǹ":"N",
"Ɲ":"N",
"Ṉ":"N",
"Ƞ":"N",
"Nj":"N",
"Ñ":"N",
"NJ":"NJ",
"Ó":"O",
"Ŏ":"O",
"Ǒ":"O",
"Ô":"O",
"Ố":"O",
"Ộ":"O",
"Ồ":"O",
"Ổ":"O",
"Ỗ":"O",
"Ö":"O",
"Ȫ":"O",
"Ȯ":"O",
"Ȱ":"O",
"Ọ":"O",
"Ő":"O",
"Ȍ":"O",
"Ò":"O",
"Ỏ":"O",
"Ơ":"O",
"Ớ":"O",
"Ợ":"O",
"Ờ":"O",
"Ở":"O",
"Ỡ":"O",
"Ȏ":"O",
"Ꝋ":"O",
"Ꝍ":"O",
"Ō":"O",
"Ṓ":"O",
"Ṑ":"O",
"Ɵ":"O",
"Ǫ":"O",
"Ǭ":"O",
"Ø":"O",
"Ǿ":"O",
"Õ":"O",
"Ṍ":"O",
"Ṏ":"O",
"Ȭ":"O",
"Ƣ":"OI",
"Ꝏ":"OO",
"Ɛ":"E",
"Ɔ":"O",
"Ȣ":"OU",
"Ṕ":"P",
"Ṗ":"P",
"Ꝓ":"P",
"Ƥ":"P",
"Ꝕ":"P",
"Ᵽ":"P",
"Ꝑ":"P",
"Ꝙ":"Q",
"Ꝗ":"Q",
"Ŕ":"R",
"Ř":"R",
"Ŗ":"R",
"Ṙ":"R",
"Ṛ":"R",
"Ṝ":"R",
"Ȑ":"R",
"Ȓ":"R",
"Ṟ":"R",
"Ɍ":"R",
"Ɽ":"R",
"Ꜿ":"C",
"Ǝ":"E",
"Ś":"S",
"Ṥ":"S",
"Š":"S",
"Ṧ":"S",
"Ş":"S",
"Ŝ":"S",
"Ș":"S",
"Ṡ":"S",
"Ṣ":"S",
"Ṩ":"S",
"Ť":"T",
"Ţ":"T",
"Ṱ":"T",
"Ț":"T",
"Ⱦ":"T",
"Ṫ":"T",
"Ṭ":"T",
"Ƭ":"T",
"Ṯ":"T",
"Ʈ":"T",
"Ŧ":"T",
"Ɐ":"A",
"Ꞁ":"L",
"Ɯ":"M",
"Ʌ":"V",
"Ꜩ":"TZ",
"Ú":"U",
"Ŭ":"U",
"Ǔ":"U",
"Û":"U",
"Ṷ":"U",
"Ü":"U",
"Ǘ":"U",
"Ǚ":"U",
"Ǜ":"U",
"Ǖ":"U",
"Ṳ":"U",
"Ụ":"U",
"Ű":"U",
"Ȕ":"U",
"Ù":"U",
"Ủ":"U",
"Ư":"U",
"Ứ":"U",
"Ự":"U",
"Ừ":"U",
"Ử":"U",
"Ữ":"U",
"Ȗ":"U",
"Ū":"U",
"Ṻ":"U",
"Ų":"U",
"Ů":"U",
"Ũ":"U",
"Ṹ":"U",
"Ṵ":"U",
"Ꝟ":"V",
"Ṿ":"V",
"Ʋ":"V",
"Ṽ":"V",
"Ꝡ":"VY",
"Ẃ":"W",
"Ŵ":"W",
"Ẅ":"W",
"Ẇ":"W",
"Ẉ":"W",
"Ẁ":"W",
"Ⱳ":"W",
"Ẍ":"X",
"Ẋ":"X",
"Ý":"Y",
"Ŷ":"Y",
"Ÿ":"Y",
"Ẏ":"Y",
"Ỵ":"Y",
"Ỳ":"Y",
"Ƴ":"Y",
"Ỷ":"Y",
"Ỿ":"Y",
"Ȳ":"Y",
"Ɏ":"Y",
"Ỹ":"Y",
"Ź":"Z",
"Ž":"Z",
"Ẑ":"Z",
"Ⱬ":"Z",
"Ż":"Z",
"Ẓ":"Z",
"Ȥ":"Z",
"Ẕ":"Z",
"Ƶ":"Z",
"IJ":"IJ",
"Œ":"OE",
"ᴀ":"A",
"ᴁ":"AE",
"ʙ":"B",
"ᴃ":"B",
"ᴄ":"C",
"ᴅ":"D",
"ᴇ":"E",
"ꜰ":"F",
"ɢ":"G",
"ʛ":"G",
"ʜ":"H",
"ɪ":"I",
"ʁ":"R",
"ᴊ":"J",
"ᴋ":"K",
"ʟ":"L",
"ᴌ":"L",
"ᴍ":"M",
"ɴ":"N",
"ᴏ":"O",
"ɶ":"OE",
"ᴐ":"O",
"ᴕ":"OU",
"ᴘ":"P",
"ʀ":"R",
"ᴎ":"N",
"ᴙ":"R",
"ꜱ":"S",
"ᴛ":"T",
"ⱻ":"E",
"ᴚ":"R",
"ᴜ":"U",
"ᴠ":"V",
"ᴡ":"W",
"ʏ":"Y",
"ᴢ":"Z",
"á":"a",
"ă":"a",
"ắ":"a",
"ặ":"a",
"ằ":"a",
"ẳ":"a",
"ẵ":"a",
"ǎ":"a",
"â":"a",
"ấ":"a",
"ậ":"a",
"ầ":"a",
"ẩ":"a",
"ẫ":"a",
"ä":"a",
"ǟ":"a",
"ȧ":"a",
"ǡ":"a",
"ạ":"a",
"ȁ":"a",
"à":"a",
"ả":"a",
"ȃ":"a",
"ā":"a",
"ą":"a",
"ᶏ":"a",
"ẚ":"a",
"å":"a",
"ǻ":"a",
"ḁ":"a",
"ⱥ":"a",
"ã":"a",
"ꜳ":"aa",
"æ":"ae",
"ǽ":"ae",
"ǣ":"ae",
"ꜵ":"ao",
"ꜷ":"au",
"ꜹ":"av",
"ꜻ":"av",
"ꜽ":"ay",
"ḃ":"b",
"ḅ":"b",
"ɓ":"b",
"ḇ":"b",
"ᵬ":"b",
"ᶀ":"b",
"ƀ":"b",
"ƃ":"b",
"ɵ":"o",
"ć":"c",
"č":"c",
"ç":"c",
"ḉ":"c",
"ĉ":"c",
"ɕ":"c",
"ċ":"c",
"ƈ":"c",
"ȼ":"c",
"ď":"d",
"ḑ":"d",
"ḓ":"d",
"ȡ":"d",
"ḋ":"d",
"ḍ":"d",
"ɗ":"d",
"ᶑ":"d",
"ḏ":"d",
"ᵭ":"d",
"ᶁ":"d",
"đ":"d",
"ɖ":"d",
"ƌ":"d",
"ı":"i",
"ȷ":"j",
"ɟ":"j",
"ʄ":"j",
"dz":"dz",
"dž":"dz",
"é":"e",
"ĕ":"e",
"ě":"e",
"ȩ":"e",
"ḝ":"e",
"ê":"e",
"ế":"e",
"ệ":"e",
"ề":"e",
"ể":"e",
"ễ":"e",
"ḙ":"e",
"ë":"e",
"ė":"e",
"ẹ":"e",
"ȅ":"e",
"è":"e",
"ẻ":"e",
"ȇ":"e",
"ē":"e",
"ḗ":"e",
"ḕ":"e",
"ⱸ":"e",
"ę":"e",
"ᶒ":"e",
"ɇ":"e",
"ẽ":"e",
"ḛ":"e",
"ꝫ":"et",
"ḟ":"f",
"ƒ":"f",
"ᵮ":"f",
"ᶂ":"f",
"ǵ":"g",
"ğ":"g",
"ǧ":"g",
"ģ":"g",
"ĝ":"g",
"ġ":"g",
"ɠ":"g",
"ḡ":"g",
"ᶃ":"g",
"ǥ":"g",
"ḫ":"h",
"ȟ":"h",
"ḩ":"h",
"ĥ":"h",
"ⱨ":"h",
"ḧ":"h",
"ḣ":"h",
"ḥ":"h",
"ɦ":"h",
"ẖ":"h",
"ħ":"h",
"ƕ":"hv",
"í":"i",
"ĭ":"i",
"ǐ":"i",
"î":"i",
"ï":"i",
"ḯ":"i",
"ị":"i",
"ȉ":"i",
"ì":"i",
"ỉ":"i",
"ȋ":"i",
"ī":"i",
"į":"i",
"ᶖ":"i",
"ɨ":"i",
"ĩ":"i",
"ḭ":"i",
"ꝺ":"d",
"ꝼ":"f",
"ᵹ":"g",
"ꞃ":"r",
"ꞅ":"s",
"ꞇ":"t",
"ꝭ":"is",
"ǰ":"j",
"ĵ":"j",
"ʝ":"j",
"ɉ":"j",
"ḱ":"k",
"ǩ":"k",
"ķ":"k",
"ⱪ":"k",
"ꝃ":"k",
"ḳ":"k",
"ƙ":"k",
"ḵ":"k",
"ᶄ":"k",
"ꝁ":"k",
"ꝅ":"k",
"ĺ":"l",
"ƚ":"l",
"ɬ":"l",
"ľ":"l",
"ļ":"l",
"ḽ":"l",
"ȴ":"l",
"ḷ":"l",
"ḹ":"l",
"ⱡ":"l",
"ꝉ":"l",
"ḻ":"l",
"ŀ":"l",
"ɫ":"l",
"ᶅ":"l",
"ɭ":"l",
"ł":"l",
"lj":"lj",
"ſ":"s",
"ẜ":"s",
"ẛ":"s",
"ẝ":"s",
"ḿ":"m",
"ṁ":"m",
"ṃ":"m",
"ɱ":"m",
"ᵯ":"m",
"ᶆ":"m",
"ń":"n",
"ň":"n",
"ņ":"n",
"ṋ":"n",
"ȵ":"n",
"ṅ":"n",
"ṇ":"n",
"ǹ":"n",
"ɲ":"n",
"ṉ":"n",
"ƞ":"n",
"ᵰ":"n",
"ᶇ":"n",
"ɳ":"n",
"ñ":"n",
"nj":"nj",
"ó":"o",
"ŏ":"o",
"ǒ":"o",
"ô":"o",
"ố":"o",
"ộ":"o",
"ồ":"o",
"ổ":"o",
"ỗ":"o",
"ö":"o",
"ȫ":"o",
"ȯ":"o",
"ȱ":"o",
"ọ":"o",
"ő":"o",
"ȍ":"o",
"ò":"o",
"ỏ":"o",
"ơ":"o",
"ớ":"o",
"ợ":"o",
"ờ":"o",
"ở":"o",
"ỡ":"o",
"ȏ":"o",
"ꝋ":"o",
"ꝍ":"o",
"ⱺ":"o",
"ō":"o",
"ṓ":"o",
"ṑ":"o",
"ǫ":"o",
"ǭ":"o",
"ø":"o",
"ǿ":"o",
"õ":"o",
"ṍ":"o",
"ṏ":"o",
"ȭ":"o",
"ƣ":"oi",
"ꝏ":"oo",
"ɛ":"e",
"ᶓ":"e",
"ɔ":"o",
"ᶗ":"o",
"ȣ":"ou",
"ṕ":"p",
"ṗ":"p",
"ꝓ":"p",
"ƥ":"p",
"ᵱ":"p",
"ᶈ":"p",
"ꝕ":"p",
"ᵽ":"p",
"ꝑ":"p",
"ꝙ":"q",
"ʠ":"q",
"ɋ":"q",
"ꝗ":"q",
"ŕ":"r",
"ř":"r",
"ŗ":"r",
"ṙ":"r",
"ṛ":"r",
"ṝ":"r",
"ȑ":"r",
"ɾ":"r",
"ᵳ":"r",
"ȓ":"r",
"ṟ":"r",
"ɼ":"r",
"ᵲ":"r",
"ᶉ":"r",
"ɍ":"r",
"ɽ":"r",
"ↄ":"c",
"ꜿ":"c",
"ɘ":"e",
"ɿ":"r",
"ś":"s",
"ṥ":"s",
"š":"s",
"ṧ":"s",
"ş":"s",
"ŝ":"s",
"ș":"s",
"ṡ":"s",
"ṣ":"s",
"ṩ":"s",
"ʂ":"s",
"ᵴ":"s",
"ᶊ":"s",
"ȿ":"s",
"ɡ":"g",
"ᴑ":"o",
"ᴓ":"o",
"ᴝ":"u",
"ť":"t",
"ţ":"t",
"ṱ":"t",
"ț":"t",
"ȶ":"t",
"ẗ":"t",
"ⱦ":"t",
"ṫ":"t",
"ṭ":"t",
"ƭ":"t",
"ṯ":"t",
"ᵵ":"t",
"ƫ":"t",
"ʈ":"t",
"ŧ":"t",
"ᵺ":"th",
"ɐ":"a",
"ᴂ":"ae",
"ǝ":"e",
"ᵷ":"g",
"ɥ":"h",
"ʮ":"h",
"ʯ":"h",
"ᴉ":"i",
"ʞ":"k",
"ꞁ":"l",
"ɯ":"m",
"ɰ":"m",
"ᴔ":"oe",
"ɹ":"r",
"ɻ":"r",
"ɺ":"r",
"ⱹ":"r",
"ʇ":"t",
"ʌ":"v",
"ʍ":"w",
"ʎ":"y",
"ꜩ":"tz",
"ú":"u",
"ŭ":"u",
"ǔ":"u",
"û":"u",
"ṷ":"u",
"ü":"u",
"ǘ":"u",
"ǚ":"u",
"ǜ":"u",
"ǖ":"u",
"ṳ":"u",
"ụ":"u",
"ű":"u",
"ȕ":"u",
"ù":"u",
"ủ":"u",
"ư":"u",
"ứ":"u",
"ự":"u",
"ừ":"u",
"ử":"u",
"ữ":"u",
"ȗ":"u",
"ū":"u",
"ṻ":"u",
"ų":"u",
"ᶙ":"u",
"ů":"u",
"ũ":"u",
"ṹ":"u",
"ṵ":"u",
"ᵫ":"ue",
"ꝸ":"um",
"ⱴ":"v",
"ꝟ":"v",
"ṿ":"v",
"ʋ":"v",
"ᶌ":"v",
"ⱱ":"v",
"ṽ":"v",
"ꝡ":"vy",
"ẃ":"w",
"ŵ":"w",
"ẅ":"w",
"ẇ":"w",
"ẉ":"w",
"ẁ":"w",
"ⱳ":"w",
"ẘ":"w",
"ẍ":"x",
"ẋ":"x",
"ᶍ":"x",
"ý":"y",
"ŷ":"y",
"ÿ":"y",
"ẏ":"y",
"ỵ":"y",
"ỳ":"y",
"ƴ":"y",
"ỷ":"y",
"ỿ":"y",
"ȳ":"y",
"ẙ":"y",
"ɏ":"y",
"ỹ":"y",
"ź":"z",
"ž":"z",
"ẑ":"z",
"ʑ":"z",
"ⱬ":"z",
"ż":"z",
"ẓ":"z",
"ȥ":"z",
"ẕ":"z",
"ᵶ":"z",
"ᶎ":"z",
"ʐ":"z",
"ƶ":"z",
"ɀ":"z",
"ff":"ff",
"ffi":"ffi",
"ffl":"ffl",
"fi":"fi",
"fl":"fl",
"ij":"ij",
"œ":"oe",
"st":"st",
"ₐ":"a",
"ₑ":"e",
"ᵢ":"i",
"ⱼ":"j",
"ₒ":"o",
"ᵣ":"r",
"ᵤ":"u",
"ᵥ":"v",
"ₓ":"x"};
String.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\[\] ]/g,function(a){return Latinise.latin_map[a]||a})};
String.prototype.latinize=String.prototype.latinise;
String.prototype.isLatin=function(){return this==this.latinise()}
```
Some examples:
```
> "Piqué".latinize();
"Pique"
> "Piqué".isLatin();
false
> "Pique".isLatin();
true
> "Piqué".latinise().isLatin();
true
``` | Efficiently replace all accented characters in a string? | [
"",
"javascript",
"sorting",
"string",
"collation",
""
] |
I have a class 'Database' that works as a wrapper for ADO.net. For instance, when I need to execute a procedure, I call Database.ExecuteProcedure(procedureName, parametersAndItsValues).
We are experiencing serious problems with Deadlock situations in SQL Server 2000. Part of our team is working on the sql code and transactions to minimize these events, but I'm thinking about making this Database class robust against deadlock situations.
We want the deadlock victim to retry perhaps after some time delay, but I don't know if it is possible. Here is the code for a method we use:
```
public int ExecuteQuery(string query)
{
int rows = 0;
try
{
Command.Connection = Connection;
Command.CommandType = CommandType.Text;
if(DatabaseType != enumDatabaseType.ORACLE)
Command.CommandText = query;
else
Command.CommandText ="BEGIN " + query + " END;";
if (DatabaseType != enumDatabaseType.SQLCOMPACT)
Command.CommandTimeout = Connection.ConnectionTimeout;
if (Connection.State == ConnectionState.Closed)
Connection.Open();
rows = Command.ExecuteNonQuery();
}
catch (Exception exp)
{
//Could I add here any code to handle it?
throw new Exception(exp.Message);
}
finally
{
if (Command.Transaction == null)
{
Connection.Close();
_connection.Dispose();
_connection = null;
Command.Dispose();
Command = null;
}
}
return rows;
}
```
Can I do this handling inside a catch block? | First, I would review my SQL 2000 code and get to the bottom of why this deadlock is happening. Fixing this may be hiding a bigger problem (Eg. missing index or bad query).
Second I would review my architecture to confirm the deadlocking statement really needs to be called that frequently (Does `select count(*) from bob` have to be called 100 times a second?).
However, if you really need some deadlock support and have no errors in your SQL or architecture try something along the following lines. (Note: I have had to use this technique for a system supporting thousands of queries per second and would hit deadlocks quite rarely)
```
int retryCount = 3;
bool success = false;
while (retryCount > 0 && !success)
{
try
{
// your sql here
success = true;
}
catch (SqlException exception)
{
if (exception.Number != 1205)
{
// a sql exception that is not a deadlock
throw;
}
// Add delay here if you wish.
retryCount--;
if (retryCount == 0) throw;
}
}
``` | Building on @Sam's response, I present a general purpose retry wrapper method:
```
private static T Retry<T>(Func<T> func)
{
int count = 3;
TimeSpan delay = TimeSpan.FromSeconds(5);
while (true)
{
try
{
return func();
}
catch(SqlException e)
{
--count;
if (count <= 0) throw;
if (e.Number == 1205)
_log.Debug("Deadlock, retrying", e);
else if (e.Number == -2)
_log.Debug("Timeout, retrying", e);
else
throw;
Thread.Sleep(delay);
}
}
}
private static void Retry(Action action)
{
Retry(() => { action(); return true; });
}
// Example usage
protected static void Execute(string connectionString, string commandString)
{
_log.DebugFormat("SQL Execute \"{0}\" on {1}", commandString, connectionString);
Retry(() => {
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandString, connection))
command.ExecuteNonQuery();
});
}
protected static T GetValue<T>(string connectionString, string commandString)
{
_log.DebugFormat("SQL Scalar Query \"{0}\" on {1}", commandString, connectionString);
return Retry(() => {
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandString, connection))
{
object value = command.ExecuteScalar();
if (value is DBNull) return default(T);
return (T) value;
}
});
}
``` | How to get efficient Sql Server deadlock handling in C# with ADO? | [
"",
"c#",
"sql-server",
"ado.net",
".net-2.0",
"deadlock",
""
] |
Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the display, instead of my carriage returns and tabs
So what I'd like to do is use string.replace to turn `\\` into `\` - this doesn't seem to work.
```
s.Replace("\\\\", "\\");
```
doesn't change the string at all because the string thinks there's only 1 backslash
```
s.Replace("\\", "");
```
replaces all the double quotes and leaves me with just n instead of \n
also, using `@` and half as many `\` chars or the `Regex.Replace` method give the same result
anyone know of a good way to do this without looping through character by character? | Since `\n` is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. You will need to replace each pair of `\` and the following character with the escaped character, like:
```
s.Replace("\\n", "\n");
s.Replace("\\t", "\t");
etc
``` | You'd be better served adjusting the resx files themselves. Line breaks can be entered via two mechanisms: You can edit the resx file as XML (right-click in Solution Explorer, choose "Open As," and choose XML), or you can do it in the designer.
If you do it in the XML, simply hit Enter, backspace to the beginning of the newline you've created, and you're done. You could do this with Search and Replace, as well, though it will be tricky.
If you use the GUI resx editor, holding down SHIFT while pressing ENTER will give you a line break.
You could do the run-time replacement thing, but as you are discovering, it's tricky to get going -- and in my mind constitutes a code smell. (You can also make a performance argument, but that would depend on how often string resources are called and the scale of your app in general.) | string replace on escape characters | [
"",
"c#",
"string",
"resx",
""
] |
How to calculate minute difference between two date-times in PHP? | Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from `January 1, 1970, 00:00:00 GMT` | The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm.
Eg.
```
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
```
$since\_start is a [DateInterval](http://www.php.net/manual/en/class.dateinterval.php) object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).
The above code will output:
1837 days total
5 years
0 months
10 days
6 hours
14 minutes
2 seconds
To get the total number of minutes:
```
$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';
```
This will output:
2645654 minutes
Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time <http://www.php.net/manual/en/book.datetime.php> | How to get time difference in minutes in PHP | [
"",
"php",
"date",
"time",
"minute",
""
] |
All the documentation I've found so far is to update keys that are already created:
```
arr['key'] = val;
```
I have a string like this: `" name = oscar "`
And I want to end up with something like this:
```
{ name: 'whatever' }
```
That is, split the string and get the first element, and then put that in a dictionary.
### Code
```
var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.
``` | Use the first example. If the key doesn't exist it will be added.
```
var a = new Array();
a['name'] = 'oscar';
alert(a['name']);
```
Will pop up a message box containing 'oscar'.
Try:
```
var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
``` | Somehow all examples, while work well, are overcomplicated:
* They use `new Array()`, which is an overkill (and an overhead) for a simple associative array (AKA dictionary).
* The better ones use `new Object()`. It works fine, but why all this extra typing?
This question is tagged "beginner", so let's make it simple.
The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":
```
// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {}; // Huh? {} is a shortcut for "new Object()"
// Add a key named fred with value 42
dict.fred = 42; // We can do that because "fred" is a constant
// and conforms to id rules
// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!"; // We use the subscript notation because
// the key is arbitrary (not id)
// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
val = ...; // Insanely complex calculations for the value
dict[key] = val;
// Read value of "fred"
val = dict.fred;
// Read value of 2bob2
val = dict["2bob2"];
// Read value of our cool secret key
val = dict[key];
```
Now let's change values:
```
// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs
// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3]; // Any legal value can be used
// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key
// Go over all keys and values in our dictionary
for (key in dict) {
// A for-in loop goes over all properties, including inherited properties
// Let's use only our own properties
if (dict.hasOwnProperty(key)) {
console.log("key = " + key + ", value = " + dict[key]);
}
}
```
Deleting values is easy too:
```
// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact
// Let's delete 2bob2
delete dict["2bob2"];
// Let's delete our secret key
delete dict[key];
// Now dict is empty
// Let's replace it, recreating all original data
dict = {
fred: 42,
"2bob2": "twins!"
// We can't add the original secret key because it was dynamic, but
// we can only add static keys
// ...
// oh well
temp1: val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
dict[key] = dict.temp1; // Copy the value
delete dict.temp1; // Kill the old key
} else {
// Do nothing; we are good ;-)
}
``` | Dynamically creating keys in a JavaScript associative array | [
"",
"javascript",
"associative-array",
""
] |
Does anyone know of a `SQL` library in `ASP.NET` that can be used to manage tables?
E.g.
```
SQLTable table = new SQLTable();
table.AddColumn(“First name”, varchar, 100);
table.AddColumn(“Last name”, varchar, 100);
if(table.ColumnExists(“Company”))
table.RemoveColumn(“Company”);
```
The operations I am looking for are adding, editing and deleting tables, fields, indexes and foreign keys.
This can be done using `SQL` but it is messy, I am looking for a clean API that is intuitive to use. | Use Microsoft.SqlServer.Management.Smo
Other option would be to install the Microsoft Sql Server Web Data Administrator
[Sql Server Web Data Administrator](http://www.microsoft.com/downloads/details.aspx?FamilyID=C039A798-C57A-419E-ACBC-2A332CB7F959&displaylang=en)
Some references for Smo:
[Create Table in SQL Server 2005 Using C# and SMO](http://davidhayden.com/blog/dave/archive/2006/01/27/2775.aspx)
[How to: Create, Alter, and Remove a Table in Visual Basic .NET (sorry for lang choice)](http://msdn2.microsoft.com/en-US/library/ms162203.aspx) | [Subsonic](http://subsonicproject.com/) has a [migrations](http://subsonicproject.com/2-1-pakala/subsonic-using-migrations/) feature. It's fairly new, but I think it meets your 'intuitive' requirement. | Does an ASP.NET SQL Library Exist for Managing Tables? | [
"",
"sql",
".net",
""
] |
So I have an application that is based heavily on the QT API which using the QPlugin system. It's fairly simple to use, you define a class which inherit from an Interface and when the plugin is loaded you get an instance of that class. In the end it'll boil down to a `dlopen`/`dlsym` or `LoadLibrary`/`GetProcAddress`, whatever is appropriate for the OS. I have no problems here everything works as expected.
So, onto the issue. There is a *lot* of functionality that involves a plugin needing to refer to data/functions provided by the main application. For example, my application has a GUI, so I have in my application a "`plugin::v1::gui`" function which returns a `QWidget *`. If I want a plugin to be able to add things to my UI, or even make it's dialog a child of my UI it'll need a pointer to it.
I started development on Linux and quickly encountered the fact that by default the loader doesn't fill in unresolved symbols in shared objects with the ones from the application loading it. No problem, easy fix. add "`-rdynamic`" to my flags and move on. Thing work well.
Now I've discovered that there doesn't appear to be an equivalent on Windows :(. So what is a good solution?
So far the best I've come up with is having a structure I fill up in my main application that has pointers to every object/function a plugin might care about. Then passing that to the plugin's "`init()`" function and now it has proper pointers to everything, but it's an annoying solution since now I have to make changes in multiple places whenever I add something.
Is there a better solution? How has the SO community dealt with this? | Create a set of interfaces for the main interaction objects that will be exposed by your application and build them in a lib/dll of their own and implement those interfaces on classes in your application as appropriate. The library should also include a plugin interface with perhaps just an "initialize" method that the plugin object will implement.
The application and plugin will obviously link against that DLL and once the plugin is loaded by the application the application should call the plugin's initialize method which will have parameters to accept any objects needed to control the application.
A popular way of making this simple is to implement a hierarchy similar to the DOM in your application so that the plugin can get to all the relevant objects in your application from one root object. | Create a registry object that is passed to the plugin in the initialization function that contains a dictionary of exposed components. Then allow the plugin to request a pointer to components by string name or other identifier from this registry. It sacrifices compile-time type safety for a stable interface.
There are also more heavy-weight solutions like [CORBA](http://en.wikipedia.org/wiki/CORBA)... | Plugin API design | [
"",
"c++",
"api",
"qt",
"plugins",
"dll",
""
] |
I need to make a pop-up window for users to log-in to my website from other websites.
I need to use a pop-up window to show the user the address bar so that they know it is a secure login, and not a spoof. For example, if I used a floating iframe, websites could spoof my login window and record the user's login information.
Thanks
Additional details: My pop-up will come from javascript code from within an iframe in any domain. I know this sounds like I'm creating adverts.. but really I'm not. If it makes any difference, the iframe domain and the pop-up domain are the same.
1 more detail, I'm looking to do the same thing "Facebook Connect" does... if you aren't logged into facebook, they allow you to login to facebook from any domain by showing a pop-up on that domain's site. For an example, go to any article at techcrunch.com and use Facebook Connect to comment. Make sure you're logged out of facebook and you'll see what I'm talking about. | Take a look at [this site.](http://www.quirksmode.org/js/popup.html)
Some code copied from it:
```
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if(!newindow){
alert('We have detected that you are using popup blocking software...');}
if (window.focus) {newwindow.focus()}
return false;
}
// -->
</script>
```
And you link to it with:
```
<a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>
``` | Sean example is good, but you can still detect if the pop up has been blocked in the following way:
```
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if(!newwindow){
alert('We have detected that you are using popup blocking software...');}
if (window.focus) {newwindow.focus()}
return false;
}
// -->
</script>
``` | How to create a pop-up window (the good kind) | [
"",
"javascript",
"popup",
"window",
""
] |
How do I setup a class that represents an interface? Is this just an abstract base class? | To expand on the answer by [bradtgmurray](https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c#318084), you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.
```
class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Parent
{
public:
virtual ~Parent();
};
class Child : public Parent, public IDemo
{
public:
virtual void OverrideMe()
{
//do stuff
}
};
```
You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default. | Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods.
A pure virtual method is a class method that is defined as virtual and assigned to 0.
```
class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Child : public IDemo
{
public:
virtual void OverrideMe()
{
// do stuff
}
};
``` | How do you declare an interface in C++? | [
"",
"c++",
"inheritance",
"interface",
"abstract-class",
"pure-virtual",
""
] |
When executing the following (complete) SQL query on Microsoft SQL Server 2000:
```
SELECT B.ARTIFACTTNS, B.ARTIFACTNAME, B.ARTIFACTTYPE, B.INITIALBYTES, B.TIMESTAMP1, B.FILENAME, B.BACKINGCLASS,
B.CHARENCODING, B.APPNAME, B.COMPONENTTNS, B.COMPONENTNAME, B.SCAMODULENAME, B.SCACOMPONENTNAME
FROM (SELECT DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
FROM (SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemName' AND PVALUE = 'MyRuleGroup'
UNION SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemDisplayName' AND PVALUE = 'MyRuleGroup') A,
(SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemTargetNameSpace' AND PVALUE = 'http://MyModule') B
WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME) A, BYTESTORE B
WHERE (A.ARTIFACTTYPE = 'BRG') AND A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME
ORDER BY ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
```
I get the following exception:
```
java.sql.SQLException: [Acme][SQLServer JDBC Driver][SQLServer]
Ambiguous column name 'ARTIFACTTYPE'.
```
What am I doing wrong here and how can I correct it? | Because `ARTIFACTTYPE` can refer to either `A.ARTIFACTTYPE` or `B.ARTIFACTTYPE` and the server needs to know which one you want, just change it to `A.ARTIFACTTYPE` and you should be okay in this case.
To clarify, you need to specify the alias prefix any time the column name is ambiguous. It isn't bad practice to always use alias prefixes as it makes it clear which columns are coming from which tables when you read the query, and eliminates issues like this one.
One might wonder why you need to distinguish between which of two columns you want when they both refer to the same column in the same table. The answer is that when you join a table to itself, the values from A.column and B.column may be different depending on the join criteria (such as may be the case with an outer join where values in one of the columns may be null). | If that's the exact query you're running, I have no idea why it would find anything ambiguous.
I wrote what I think is an equivalent query and ran it in my database (Oracle) with no problem.
**EDIT** Adding exact output of a new experiment in Oracle. The query executed in this experiment is the exact query given by the OP, with the table name filled in. **NO OTHER CHANGES**. There's nothing ambiguous in this query. So, either that is not the exact query that is being executed, or SQL Server has a parser bug.
```
SQL> create table props (pname varchar2(100),
2 pvalue varchar2(100),
3 artifacttype number,
4 artifacttns number,
5 artifactname number);
Table created.
SQL> SELECT
2 DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
3 FROM
4 (SELECT DISTINCT
5 ARTIFACTTYPE,
6 ARTIFACTTNS,
7 ARTIFACTNAME
8 FROM props
9 WHERE PNAME = 'AcmeSystemName'
10 AND PVALUE = 'MyRuleGroup'
11 UNION
12 SELECT DISTINCT
13 ARTIFACTTYPE,
14 ARTIFACTTNS,
15 ARTIFACTNAME
16 FROM props
17 WHERE PNAME = 'AcmeSystemDisplayName'
18 AND PVALUE = 'MyRuleGroup') A,
19 (SELECT DISTINCT
20 ARTIFACTTYPE,
21 ARTIFACTTNS,
22 ARTIFACTNAME
23 FROM props
24 WHERE PNAME = 'AcmeSystemTargetNameSpace'
25 AND PVALUE = 'http://mymodule') B
26 WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE
27 AND A.ARTIFACTTNS = B.ARTIFACTTNS
28 AND A.ARTIFACTNAME = B.ARTIFACTNAME
29 /
no rows selected
```
**End Edit**
My suggestion for getting around the error is to give the table in each select clause a unique alias and qualify all column references. Like this:
```
SELECT
DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
FROM
(SELECT DISTINCT
P1.ARTIFACTTYPE,
P1.ARTIFACTTNS,
P1.ARTIFACTNAME
FROM {PROPERTIES_TABLE_NAME} P1
WHERE PNAME = 'AcmeSystemName'
AND PVALUE = 'MyRuleGroup'
UNION
SELECT DISTINCT
P2.ARTIFACTTYPE,
P2.ARTIFACTTNS,
P2.ARTIFACTNAME
FROM {PROPERTIES_TABLE_NAME} P2
WHERE PNAME = 'AcmeSystemDisplayName'
AND PVALUE = 'MyRuleGroup') A,
(SELECT DISTINCT
P3.ARTIFACTTYPE,
P3.ARTIFACTTNS,
P3.ARTIFACTNAME
FROM {PROPERTIES_TABLE_NAME} P3
WHERE PNAME = 'AcmeSystemTargetNameSpace'
AND PVALUE = 'http://mymodule') B
WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE
AND A.ARTIFACTTNS = B.ARTIFACTTNS
AND A.ARTIFACTNAME = B.ARTIFACTNAME
``` | Ambiguous column name error | [
"",
"sql",
"sql-server",
"sqlexception",
""
] |
I have a table that looks a bit like this actors(forename, surname, stage\_name);
I want to update stage\_name to have a default value of
```
forename." ".surname
```
So that
```
insert into actors(forename, surname) values ('Stack', 'Overflow');
```
would produce the record
```
'Stack' 'Overflow' 'Stack Overflow'
```
Is this possible?
Thanks :) | MySQL does not support computed columns or expressions in the `DEFAULT` option of a column definition.
You can do this in a trigger (MySQL 5.0 or greater required):
```
CREATE TRIGGER format_stage_name
BEFORE INSERT ON actors
FOR EACH ROW
BEGIN
SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
END
```
You may also want to create a similar trigger `BEFORE UPDATE`.
Watch out for `NULL` in forename and surname, because concat of a `NULL` with any other string produces a `NULL`. Use `COALESCE()` on each column or on the concatenated string as appropriate.
**edit:** The following example sets `stage_name` only if it's `NULL`. Otherwise you can specify the `stage_name` in your `INSERT` statement, and it'll be preserved.
```
CREATE TRIGGER format_stage_name
BEFORE INSERT ON actors
FOR EACH ROW
BEGIN
IF (NEW.stage_name IS NULL) THEN
SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
END IF;
END
``` | According to [10.1.4. Data Type Default Values](http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html) no, you can't do that. You can only use a constant or `CURRENT_TIMESTAMP`.
OTOH if you're pretty up-to-date, you could probably use a [trigger](http://dev.mysql.com/doc/refman/5.0/en/triggers.html) to accomplish the same thing. | MySQL - Set default value for field as a string concatenation function | [
"",
"sql",
"mysql",
"function",
"default-value",
""
] |
I need to create a trigger in every database on my sql 2005 instance. I'm setting up some auditing ddl triggers.
I create a cursor with all database names and try to execute a USE statement. This doesn't seem to change the database - the CREATE TRIGGER statement just fires in adventureworks repeatedly. The other option would be to prefix the trigger object with databasename.dbo.triggername. This doesn't work either - some kind of limitation in creating triggers. Of course, I could do this manually, but I'd prefer to get it scripted for easy application and removal. I have other options if I can't do this in 1 sql script, but I'd like to keep it simple :)
Here is what I have so far - hopefully you can find a bonehead mistake!
```
--setup stuff...
CREATE DATABASE DBA_AUDIT
GO
USE DBA_AUDIT
GO
CREATE TABLE AuditLog
(ID INT PRIMARY KEY IDENTITY(1,1),
Command NVARCHAR(1000),
PostTime DATETIME,
HostName NVARCHAR(100),
LoginName NVARCHAR(100)
)
GO
CREATE ROLE AUDITROLE
GO
sp_adduser 'guest','guest','AUDITROLE'
GO
GRANT INSERT ON SCHEMA::[dbo]
TO AUDITROLE
--CREATE TRIGGER IN ALL NON SYSTEM DATABASES
DECLARE @dataname varchar(255),
@dataname_header varchar(255),
@command VARCHAR(MAX),
@usecommand VARCHAR(100)
SET @command = '';
--get the list of database names
DECLARE datanames_cursor CURSOR FOR SELECT name FROM sys.databases
WHERE name not in ('master', 'pubs', 'tempdb', 'model','msdb')
OPEN datanames_cursor
FETCH NEXT FROM datanames_cursor INTO @dataname
WHILE (@@fetch_status = 0)
BEGIN
PRINT '----------BEGIN---------'
PRINT 'DATANAME variable: ' + @dataname;
EXEC ('USE ' + @dataname);
PRINT 'CURRENT db: ' + db_name();
SELECT @command = 'CREATE TRIGGER DBA_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
DECLARE @cmd NVARCHAR(1000)
DECLARE @posttime NVARCHAR(24)
DECLARE @spid NVARCHAR(6)
DECLARE @loginname NVARCHAR(100)
DECLARE @hostname NVARCHAR(100)
SET @data = EVENTDATA()
SET @cmd = @data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''NVARCHAR(1000)'')
SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''','''')))
SET @posttime = @data.value(''(/EVENT_INSTANCE/PostTime)[1]'', ''DATETIME'')
SET @spid = @data.value(''(/EVENT_INSTANCE/SPID)[1]'', ''nvarchar(6)'')
SET @loginname = @data.value(''(/EVENT_INSTANCE/LoginName)[1]'',
''NVARCHAR(100)'')
SET @hostname = HOST_NAME()
INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName)
VALUES(@cmd, @posttime, @hostname, @loginname);'
EXEC (@command);
FETCH NEXT FROM datanames_cursor INTO @dataname;
PRINT '----------END---------'
END
CLOSE datanames_cursor
DEALLOCATE datanames_cursor
OUTPUT:
----------BEGIN---------
DATANAME variable: adventureworks
CURRENT db: master
Msg 2714, Level 16, State 2, Procedure DBA_Audit, Line 18
There is already an object named 'DBA_Audit' in the database.
----------END---------
----------BEGIN---------
DATANAME variable: SQL_DBA
CURRENT db: master
Msg 2714, Level 16, State 2, Procedure DBA_Audit, Line 18
There is already an object named 'DBA_Audit' in the database.
----------END---------
```
EDIT:
I've already tried the sp\_msforeachdb approach
```
Msg 111, Level 15, State 1, Line 1
'CREATE TRIGGER' must be the first statement in a query batch.
```
EDIT:
Here is my final code - this exact script has not been tested, but it IS in production on about 100 or so databases. Cheers!
**One caveat** - your databases need to be in compatibility mode of 90(in options for each db), otherwise you may start getting errors. The account in the EXECUTE AS part of the statement also needs access to insert into your admin table.
```
USE [SQL_DBA]
GO
/****** Object: Table [dbo].[DDL_Login_Log] Script Date: 03/03/2009 17:28:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DDL_Login_Log](
[DDL_Id] [int] IDENTITY(1,1) NOT NULL,
[PostTime] [datetime] NOT NULL,
[DB_User] [nvarchar](100) NULL,
[DBName] [nvarchar](100) NULL,
[Event] [nvarchar](100) NULL,
[TSQL] [nvarchar](2000) NULL,
[Object] [nvarchar](1000) NULL,
CONSTRAINT [PK_DDL_Login_Log] PRIMARY KEY CLUSTERED
(
[DDL_Id] ASC,
[PostTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--This creates the trigger on the model database so all new DBs get it
USE [model]
GO
/****** Object: DdlTrigger [ddl_DB_User] Script Date: 03/03/2009 17:26:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [ddl_DB_User]
ON DATABASE
FOR DDL_DATABASE_SECURITY_EVENTS
AS
DECLARE @data XML
declare @user nvarchar(100)
SET @data = EVENTDATA()
select @user = convert(nvarchar(100), SYSTEM_USER)
execute as login='domain\sqlagent'
INSERT sql_dba.dbo.DDL_Login_Log
(PostTime, DB_User, DBName, Event, TSQL,Object)
VALUES
(@data.value('(/EVENT_INSTANCE/PostTime)[1]', 'nvarchar(100)'),
@user,
db_name(),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
@data.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)'),
@data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(1000)')
)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--CREATE TRIGGER IN ALL NON SYSTEM DATABASES
DECLARE @dataname varchar(255),
@dataname_header varchar(255),
@command VARCHAR(MAX),
@usecommand VARCHAR(100)
SET @command = '';
DECLARE datanames_cursor CURSOR FOR SELECT name FROM sys.databases
WHERE name not in ('master', 'pubs', 'tempdb', 'model','msdb')
OPEN datanames_cursor
FETCH NEXT FROM datanames_cursor INTO @dataname
WHILE (@@fetch_status = 0)
BEGIN
PRINT '----------BEGIN---------'
PRINT 'DATANAME variable: ' + @dataname;
EXEC ('USE ' + @dataname);
PRINT 'CURRENT db: ' + db_name();
SELECT @command = 'CREATE TRIGGER DBA_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
DECLARE @cmd NVARCHAR(1000)
DECLARE @posttime NVARCHAR(24)
DECLARE @spid NVARCHAR(6)
DECLARE @loginname NVARCHAR(100)
DECLARE @hostname NVARCHAR(100)
SET @data = EVENTDATA()
SET @cmd = @data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''NVARCHAR(1000)'')
SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''','''')))
SET @posttime = @data.value(''(/EVENT_INSTANCE/PostTime)[1]'', ''DATETIME'')
SET @spid = @data.value(''(/EVENT_INSTANCE/SPID)[1]'', ''nvarchar(6)'')
SET @loginname = @data.value(''(/EVENT_INSTANCE/LoginName)[1]'',
''NVARCHAR(100)'')
SET @hostname = HOST_NAME()
INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName)
VALUES(@cmd, @posttime, @hostname, @loginname);'
EXEC (@command);
FETCH NEXT FROM datanames_cursor INTO @dataname;
PRINT '----------END---------'
END
CLOSE datanames_cursor
DEALLOCATE datanames_cursor
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----Disable all triggers when things go haywire
sp_msforeachdb @command1='use [?]; IF EXISTS (SELECT * FROM sys.triggers WHERE name = N''ddl_DB_User'' AND parent_class=0)disable TRIGGER [ddl_DB_User] ON DATABASE'
``` | When you use EXEC() each use is in its own context. So, when you do EXEC('USE MyDB') it switches to MyDB for that context then the command ends and you're back where you started. There are a couple of possible solutions...
You can call sp\_executesql with a database name (for example, MyDB..sp\_executesql) and it will run in that database. The trick is to let you do that dynamically, so you basically wrap it twice like so:
```
DECLARE @cmd NVARCHAR(2000), @my_db VARCHAR(255)
SET @my_db = 'MyDatabaseName'
SET @cmd = 'DECLARE @my_cmd NVARCHAR(2000); SET @my_cmd = ''CREATE TRIGGER DBA_Audit ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
DECLARE @cmd NVARCHAR(1000)
DECLARE @posttime NVARCHAR(24)
DECLARE @spid NVARCHAR(6)
DECLARE @loginname NVARCHAR(100)
DECLARE @hostname NVARCHAR(100)
SET @data = EVENTDATA()
SET @cmd = @data.value(''''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'''', ''''NVARCHAR(1000)'''')
SET @cmd = LTRIM(RTRIM(REPLACE(@cmd,'''''''','''''''')))
SET @posttime = @data.value(''''(/EVENT_INSTANCE/PostTime)[1]'''', ''''DATETIME'''')
SET @spid = @data.value(''''(/EVENT_INSTANCE/SPID)[1]'''', ''''nvarchar(6)'''')
SET @loginname = @data.value(''''(/EVENT_INSTANCE/LoginName)[1]'''',
''''NVARCHAR(100)'''')
SET @hostname = HOST_NAME()
INSERT INTO [DBA_AUDIT].dbo.AuditLog(Command, PostTime,HostName,LoginName)
VALUES(@cmd, @posttime, @hostname, @loginname);''; EXEC ' + @my_db + '..sp_executesql @my_cmd'
EXEC (@cmd)
```
The other option is to do this as a two-step process where the first step generates and prints out the actual code with USE statements and all, then you run that generated code. | You don't have to create a CURSOR...
```
sp_msforeachdb 'USE ?; PRINT ''Hello ?'''
```
EDIT: The "USE ?" part is to switch to the specified database... you may want to put an IF statement to make sure that the database name is what you'd like it to be. | Create a DDL trigger in every database on a 2005 instance | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
So I don't do a lot of Win32 calls, but recently I have had to use the [`GetFileTime()`](http://msdn.microsoft.com/en-us/library/ms724320(VS.85).aspx) and [`SetFileTime()`](http://msdn.microsoft.com/en-us/library/ms724933(VS.85).aspx) functions. Now although Win98 and below are not officially supported in my program people do use it there anyway, and I try to keep it as usable as possible. I was just wondering what will happen as those functions do not exist in pre-NT systems, will they receive an error message of some sort for example because in that case I will add in an OS check? Thanks | If you call the functions directly, then your program will not load on Win98.
What you can do is use `LoadLibrary()` / `GetProcAddress()` to get a pointer to `GetFileTime()` / `SetFileTime()`. On Win98 this will fail, giving you a null pointer which you can test for and ignore. On 2000 and later you will get a pointer which you can then use.
It's a pain, but it's the only solution I know of.
Here is an example of getting the UpdateLayeredWindow function if it exists:
```
typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
UpdateLayeredWinFunc updateLayeredWindow = 0;
HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
``` | You could call `FindFirstFile()` instead of `GetFileTime()`. I wouldn't know an alternative for `SetFileTime()`, though. | Calling NT function on pre-NT system | [
"",
"c++",
"windows",
"winapi",
"dll",
""
] |
I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:
```
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
``` | The scope of functions `hello` and `hi` are entirely different. They do not have any variables in common.
Note that the result of calling `hi(x,y)` is some object. You save that object with the name `good` in the function `hello`.
The variable named `good` in `hello` is a different variable, unrelated to the variable named `good` in the function `hi`.
They're spelled the same, but the exist in different namespaces. To prove this, change the spelling the `good` variable in one of the two functions, you'll see that things still work.
---
Edit. Follow-up: "so what should i do if i want use the result of `hi` function in `hello` function?"
Nothing unusual. Look at `hello` closely.
```
def hello(x,y):
fordf150 = hi(y,x)
"then do somethings,and use the variable 'fordf150'."
return something
def hi( ix, iy ):
"compute some value, good."
return good
```
Some script evaluates `hello( 2, 3)`.
1. Python creates a new namespace for the evaluation of `hello`.
2. In `hello`, `x` is bound to the object `2`. Binding is done position order.
3. In `hello`, `y` is bound to the object `3`.
4. In `hello`, Python evaluates the first statement, `fordf150 = hi( y, x )`, `y` is 3, `x` is 2.
a. Python creates a new namespace for the evaluation of `hi`.
b. In `hi`, `ix` is bound to the object `3`. Binding is done position order.
c. In `hi`, `iy` is bound to the object `2`.
d. In `hi`, something happens and `good` is bound to some object, say `3.1415926`.
e. In `hi`, a `return` is executed; identifying an object as the value for `hi`. In this case, the object is named by `good` and is the object `3.1415926`.
f. The `hi` namespace is discarded. `good`, `ix` and `iy` vanish. The object (`3.1415926`), however, remains as the value of evaluating `hi`.
5. In `hello`, Python finishes the first statement, `fordf150 = hi( y, x )`, `y` is 3, `x` is 2. The value of `hi` is `3.1415926`.
a. `fordf150` is bound to the object created by evaluating `hi`, `3.1415926`.
6. In `hello`, Python moves on to other statements.
7. At some point `something` is bound to an object, say, `2.718281828459045`.
8. In `hello`, a `return` is executed; identifying an object as the value for `hello`. In this case, the object is named by `something` and is the object `2.718281828459045`.
9. The namespace is discarded. `fordf150` and `something` vanish, as do `x` and `y`. The object (`2.718281828459045`), however, remains as the value of evaluating `hello`.
Whatever program or script called `hello` gets the answer. | If you want to define a variable to the global namespace from inside a function, and thereby make it accessible by other functions in this space, you can use the global keyword. Here's some examples
```
varA = 5 #A normal declaration of an integer in the main "global" namespace
def funcA():
print varA #This works, because the variable was defined in the global namespace
#and functions have read access to this.
def changeA():
varA = 2 #This however, defines a variable in the function's own namespace
#Because of this, it's not accessible by other functions.
#It has also replaced the global variable, though only inside this function
def newVar():
global varB #By using the global keyword, you assign this variable to the global namespace
varB = 5
def funcB():
print varB #Making it accessible to other functions
```
Conclusion: variables defined in a function stays in the function's namespace. It still has access to the global namespace for reading only, unless the variable has been called with the global keyword.
The term global isn't entirely global as it may seem at first. It's practically only a link to the lowest namespace in the file you're working in. Global keywords cannot be accessed in another module.
As a mild warning, this may be considered to be less "good practice" by some. | A small question about python's variable scope | [
"",
"python",
"variables",
"scope",
""
] |
Pour in your posts. I'll start with a couple, let us see how much we can collect.
To provide inline event handlers like
```
button.Click += (sender,args) =>
{
};
```
To find items in a collection
```
var dogs= animals.Where(animal => animal.Type == "dog");
```
For iterating a collection, like
```
animals.ForEach(animal=>Console.WriteLine(animal.Name));
```
Let them come!! | Returning an custom object:
```
var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname});
``` | Here's a slightly different one - you can use them [(like this)](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/f44dc57a9dc5168d/02c312dcf8a9a769#4805324df6b30218) to simulate the missing "infoof"/"nameof" operators in C# - i.e. so that instead of hard-coding to a property name as a string, you can use a lambda. This means that it is validated at compile time (which strings can't be).
There is obviously a performance cost to this, hence "just for fun", but interesting... | In what ways do you make use of C# Lambda Expressions? | [
"",
"c#",
".net",
"c#-3.0",
"lambda",
""
] |
i need a report and i should use pivot table for it.Report will be group by categories .It is not good to use case when statement because there are many categories.u can think Northwind Database as sample and All Categories will be shown as Columns and Report will show customers preference among Categories.I dont know another solution and saw examples as Stored Procedures in Internet for Sql Server.Do u know a Solution except for using case when?
Thanks | Once you get Oracle 11G there is a [built-in PIVOT feature](http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-pivot.html). Prior to that, you are restricted to using CASE (or DECODE) expressions. I have an article on how to automate doing that [on my blog.](http://tonyandrews.blogspot.com/2004/10/pivot-queries.html) | It is painful to do row/column swaps in SQL. Each row you want to turn into a column, you have to ask for explicitly. So if you have many categories, your query will be very long, and it'll change every time you add/remove/change a category (this is probably the CASE method you're mentioning). You can write a stored procedure to generate that will generate that query for you (or otherwise build the result set you want), but honestly, in that way lies madness (and probably abysmal performance).
Take the data as rows, like SQL surely wants to give it, and then have your app convert it to columns. That'll be much easier than forcing SQL to do things it doesn't want to do. | Advice Using Pivot Table in Oracle | [
"",
"sql",
"oracle",
"plsql",
"pivot",
""
] |
Namely, how does the following code:
```
var sup = new Array(5);
sup[0] = 'z3ero';
sup[1] = 'o3ne';
sup[4] = 'f3our';
document.write(sup.length + "<br />");
```
output '5' for the length, when all you've done is set various elements?
My 'problem' with this code is that I don't understand how `length` changes without calling a `getLength()` or a `setLength()` method. When I do any of the following:
```
a.length
a['length']
a.length = 4
a['length'] = 5
```
on a non-array object, it behaves like a dict / associative array. When I do this on the array object, it has special meaning. What mechanism in JavaScript allows this to happen? Does JavaScript have some type of property system which translates
```
a.length
a['length']
```
into "get" methods and
```
a.length = 4
a['length'] = 5
```
into "set" methods? | Everything in JavaScript is an object. In the case of an `Array`, the `length` property returns the size of the internal storage area for indexed items of the array. Some of the confusion may come into play in that the `[]` operator works for both numeric and string arguments. For an array, if you use it with a numeric index, it returns/sets the expected indexed item. If you use it with a string, it returns/sets the named property on the array object - unless the string corresponds to a numeric value, then it returns the indexed item. This is because in JavaScript array indexes are coerced to strings by an implicit `toString()` call. Frankly, this is just one more of those things that makes you scratch your head and say "JavaScript, this, this is why they laugh at you."
The actual underlying representation may differ between browsers (or it may not). I wouldn't rely on anything other than the interface that is supplied when working with it.
You can find out more about JavaScript arrays [at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). | Characteristics of a JavaScript array
1. Dynamic - Arrays in JavaScript can grow dynamically .push
2. Can be sparse - for example, array[50000] = 2;
3. Can be dense - for example, array = [1, 2, 3, 4, 5]
In JavaScript, it is hard for the runtime to know whether the array is going to be dense or sparse. So all it can do is take a guess. All implementations use a heuristic to determine if the array is dense or sparse.
For example, code in point 2 above, can indicate to the JavaScript runtime that this is likely a sparse array implementation. If the array is initialised with an initial count, this could indicate that this is likely a dense array.
When the runtime detects that the array is *sparse*, it is implemented in a similar way to an object. So instead of maintaining a contiguous array, a key/value map is built.
For more references, see *[How are JavaScript arrays implemented internally?](https://www.quora.com/How-are-javascript-arrays-implemented-internally)* | How are JavaScript arrays implemented? | [
"",
"javascript",
"arrays",
"associative-array",
""
] |
Suppose I have this interface
```
public interface IFoo
{
///<summary>
/// Foo method
///</summary>
void Foo();
///<summary>
/// Bar method
///</summary>
void Bar();
///<summary>
/// Situation normal
///</summary>
void Snafu();
}
```
And this class
```
public class Foo : IFoo
{
public void Foo() { ... }
public void Bar() { ... }
public void Snafu() { ... }
}
```
Is there a way, or is there a tool that can let me automatically put in the comments of each member in a base class or interface?
Because I hate re-writing the same comments for each derived sub-class! | [GhostDoc](http://www.roland-weigelt.de/ghostdoc/) does exactly that. For methods which aren't inherited, it tries to create a description out of the name.
`FlingThing()` becomes `"Flings the Thing"` | You can always use the `<inheritdoc />` tag:
```
public class Foo : IFoo
{
/// <inheritdoc />
public void Foo() { ... }
/// <inheritdoc />
public void Bar() { ... }
/// <inheritdoc />
public void Snafu() { ... }
}
```
Using the `cref` attribute, you can even refer to an entirely different member in an entirely different class or namespace!
```
public class Foo
{
/// <inheritdoc cref="System.String.IndexOf" />
public void Bar() { ... } // this method will now have the documentation of System.String.IndexOf
}
``` | Inheriting comments from an interface in an implementing class? | [
"",
"c#",
"inheritance",
"comments",
""
] |
I am currently investigating several free/open source OpenGL based 3D engines, and was wondering if you guys could provide some feedback on these engines and how they are to work with in a real world project.
The engines being compared are (in no particular order):
[Crystal Space](http://www.crystalspace3d.org/main/Main_Page)
[Panda3D](http://panda3d.org/)
[Irrlicht](http://irrlicht.sourceforge.net/)
These are the main ones i know that are cross-platform, any there any others that i should be looking at? | **You can find a lot of informations on lot of engines [on this database.](http://www.devmaster.net/engines/)**
CrystalSpace is a full engine so it's a monolithic bloc that you have to customize for your needs.
Irrlicht too but it's made do do things easy. The counter effect is that it's hard to do specific things.
Now, i think [Ogre](http://www.ogre3d.org) might be the most general purpose hardware accelerated 3D rendering engine around here. Maybe Horde3D is better suited for specific high quality rendering but nothing that cannot be done with Ogre too. | More focused on large terrains than games (think GIS or flight simulators) there is also [openscenegraph](http://www.openscenegraph.org/) | 3D Engine Comparison | [
"",
"c++",
"open-source",
"opengl",
"3d",
"cross-platform",
""
] |
Given the schema
```
PERSON { name, spouse }
```
where PERSON.spouse is a foreign key to PERSON.name, NULLs will be necessary when a person is unmarried or we don't have any info.
Going with the argument against nulls, how do you avoid them in this case?
I have an alternate schema
```
PERSON { name }
SPOUSE { name1, name2 }
```
where SPOUSE.name\* are FKs to PERSON. The problem I see here is that there is no way to ensure someone has only one spouse (even with all possible UNIQUE constraints, it would be possible to have two spouses).
What's the best way to factor out nulls in bill-of-materials style relations? | All right, use Auto-IDs and then use a Check Constraint. The "Name1" column (which would only be an int ID) will be force to only have ODD numbered IDs and Name2 will only have EVEN.
Then create a Unique Constraint for Column1 and Column2. | I think that enforcing no NULLs and no duplicates for this type of relationship makes the schema definition way more complicated than it really needs to be. Even if you allow nulls, it would still be possible for a person to have more than one spouse, or to have conflicting records e.g:
```
PERSON { A, B }
PERSON { B, C }
PERSON { C, NULL }
```
You'd need to introduce more data, like gender (or "spouse-numbers" for same-sex marriages?) to ensure that, for example, only Persons of one type are allowed to have a Spouse. The other Person's spouse would be determined by the first person's record. E.g.:
```
PERSON { A, FEMALE, B }
PERSON { B, MALE, NULL }
PERSON { C, FEMALE, NULL }
```
... So that only PERSONs who are FEMALE can have a non-null SPOUSE.
But IMHO, that's overcomplicated and non-intuitive even with NULLs. Without NULLs, it's even worse. I would avoid making schema restrictions like this unless you literally have no choice. | Factoring out nulls in bill-of-materials style relations | [
"",
"sql",
"database",
"referential-integrity",
""
] |
We currently send an email notification in plain text or html format. Our environment is C#/.NET/SQL Server.
I'd like to know if anyone recommends a particular solution. I see two ways of doing this:
* dynamically convert current email to pdf using a third party library and sending the pdf as an attachment
or
* use SSRS to allow users to export pdf report (could eventually have SSRS push reports)
I'm open to third party libraries (especially if they are open source and free). It seems that SSRS is the simplest and easiest way to go. Anyone have any tips? | You can use [iTextSharp](http://itextsharp.sourceforge.net/) to convert your html pages to pdf. Here's an example:
```
class Program
{
static void Main(string[] args)
{
string html =
@"<html>
<head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />
</head>
<body>
<p style=""color: red;"">Hello World</p>
</body>
</html>";
Document document = new Document(PageSize.A4);
using (Stream output = new FileStream("out.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
using (StringReader htmlReader = new StringReader(html))
using (XmlTextReader reader = new XmlTextReader(htmlReader))
{
PdfWriter.GetInstance(document, output);
HtmlParser.Parse(document, reader);
}
}
}
``` | [iText-Sharp](http://itextsharp.sourceforge.net/)
Works very much like the java version, and has both great documentation and multiple books available. | PDF generation in C# | [
"",
"c#",
".net",
"sql-server",
"pdf",
"reporting-services",
""
] |
It is not uncommon for me (or likely anyone else) to have a list of objects I need to iterate through and then interact with a list of properties. I use a nested loop, like this:
```
IList<T> listOfObjects;
IList<TProperty> listOfProperties;
foreach (T dataObject in listOfObjects)
{
foreach (TProperty property in listOfProperties)
{
//do something clever and extremely useful here
}
}
```
Is this the time and performance tested pattern for this problem? Or is there something more performant, more elegant, or just plain fun (while still being readable and maintainable of course)?
The code above doesn't make me smile. Can someone please help bring some joy to my loop?
Thank you!
Update: I use the term "nerd" in a most positive sense. As part of the wikipedia definition puts it "that refers to a person who passionately pursues intellectual activities". By "code nerd" I mean someone who is concerned about continually improving oneself as a programmer, finding new, novel, and elegant ways of coding that are fast, maintainable, and beautiful! They rejoice to move out of VB6 and want smart people to critique their code and help them smartify themselves. (Note: they also like to make new words that end in -ify).
Final note:
Thank you to Dave R, Earwicker, and TheSoftwareJedi for sending me down the Linq path. It is just the sort of happy code I was looking for! | Looks like you are trying to cartesian join two lists, and apply a where clause. Here's a simple example showing the Linq syntax for doing this, which I think is what you are looking for. list1 and list2 can be any IEnumerable, your where clause can contain more detailed logic, and in your select clause you can yank out what you need.
```
var list1 = Enumerable.Range(1, 100);
var list2 = Enumerable.Range(1, 100);
foreach (var item in from a in list1
from b in list2
where a % b == 0
select new { a, b })
{
Console.WriteLine(item);
};
```
Performance will be identical to what you posted though - no desire to mislead on that respect. I do prefer this Linq syntax. | There is certainly nothing wrong with nested loops. They are fast, readable and have been around since software development took its first baby steps.
As you want to perform actions as you iterate over a collection, you may find that LINQ would be an interesting avenue to explore:
<http://msdn.microsoft.com/en-us/vcsharp/aa904594.aspx>
You'll be limiting yourself to later versions of the Framework (3.5 onwards), but you may actually find the Functional Programming approach quite elegant. Other language features that come into play when you go down this road include lambdas and anonymous methods, which are fascinating in their own right.
Best of luck and I hope you have fun on the way - that's a great approach :) | Calling fellow code nerds - Alternatives to Nested Loops? | [
"",
"c#",
"linq",
"loops",
""
] |
I am working on an If statement and I want to satisfy two conditions to ignore the loop. This seemed easy at first, but now... I don't know. this is my dilemma...
```
if((radButton1.checked == false)&&(radButton2.checked == false))
{
txtTitle.Text = "go to work";
}
```
The dilemma is "go to work" is not executed if radButton1 is false and radButton2 is true. Shouldn't it require both conditions to be false in order to skip the statement? | No, it requires them to both be false to *execute* the statement. | Nope, it requires both conditions to be false to *execute* the statement. Read again:
```
if ((radButton1.checked == false) && (radButton2.checked == false)) {
txtTitle.Text = "Go to work";
}
```
In English: "If radButton1.checked is false AND radButton2.checked is false, then set
the txtTitle.Text to 'Go to work'".
If you want to skip the statement when both conditions are false then negate your logic, like this:
```
if ((radButton1.checked == true) || (radButton2.checked == true)) {
txtTitle.Text = "Go to work";
}
```
This, translated to English would read: "If radButton1.checked is true OR radButton2.checked is true, then set the text to 'Go to work'". This means that if any condition is true, it will execute the statement, or, if both are false, to skip it. | Why is this a "so close yet so far" if statement? | [
"",
"c#",
".net",
"logic",
""
] |
I am currently using TcpListener to address incoming connections, each of which are given a thread for handling the communication and then shutdown that single connection. Code looks as follows:
```
TcpListener listener = new TcpListener(IPAddress.Any, Port);
System.Console.WriteLine("Server Initialized, listening for incoming connections");
listener.Start();
while (listen)
{
// Step 0: Client connection
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));
clientThread.Start(client.GetStream());
client.Close();
}
```
The `listen` variable is a boolean that is a field on the class. Now, when the program shuts down I want it to stop listening for clients. Setting listen to `false` will prevent it from taking on more connections, but since `AcceptTcpClient` is a blocking call, it will at minimum take the next client and THEN exit. Is there any way to force it to simply break out and stop, right then and there? What effect does calling listener.Stop() have while the other blocking call is running? | These are two quick fixes you can use, given the code and what I presume is your design:
## 1. Thread.Abort()
If you have started this `TcpListener` thread from another, you can simply call `Abort()` on the thread, which will cause a `ThreadAbortException` within the blocking call and walk up the stack.
## 2. TcpListener.Pending()
The second low cost fix is to use the `listener.Pending()` method to implement a polling model. You then use a `Thread.Sleep()` to wait before seeing if a new connection is pending. Once you have a pending connection, you call `AcceptTcpClient()` and that releases the pending connection. The code would look something like this:
```
while (listen) {
// Step 0: Client connection
if (!listener.Pending()) {
Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
continue; // skip to next iteration of loop
}
TcpClient client = listener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));
clientThread.Start(client.GetStream());
client.Close();
}
```
## Asynchronous Rewrite
However, you should really move to a non-blocking methodology for your application. Under the covers the framework will use overlapped I/O and I/O completion ports to implement non-blocking I/O from your asynchronous calls. It's not terribly difficult either, it just requires thinking about your code a little differently.
Basically you would start your code with the `BeginAcceptTcpClient()` method and keep track of the `IAsyncResult` that you are returned. You point that at a method whose responsible for getting the `TcpClient` and passing it off *NOT* to a new thread but to a thread off of the `ThreadPool.QueueUserWorkerItem`, so you're not spinning up and closing a new thread for each client request (Note: you may need to use your own thread pool if you have particularly long lived requests, because the thread pool is shared and if you monopolize all the threads other parts of your application implemented by the system may be starved). Once the listener method has kicked off your new `TcpClient` to its own `ThreadPool` request, it calls `BeginAcceptTcpClient()` again and points the delegate back at itself.
Effectively you're just breaking up your current method into 3 different methods that will then get called by the various parts:
1. to bootstrap everything;
2. to be the target to call `EndAcceptTcpClient()`, kick off the `TcpClient` to it's own thread and then call itself again;
3. to process the client request and close it when finished.
(**Note**: you should enclose your `TcpClient` call in a `using(){}` block to ensure that `TcpClient.Dispose()` or `TcpClient.Close()` methods are called even in the event of an exception. Alternately you can put this in the `finally` block of a `try {} finally {}` block.) | `listener.Server.Close()` from another thread breaks the blocking call.
```
A blocking operation was interrupted by a call to WSACancelBlockingCall
``` | Proper way to stop TcpListener | [
"",
"c#",
"sockets",
"networking",
"tcplistener",
""
] |
How do you rotate an image with the canvas html5 element from the bottom center angle?
```
<html>
<head>
<title>test</title>
<script type="text/javascript">
function startup() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'player.gif';
img.onload = function() {
ctx.translate(185, 185);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(img, 0, 0, 64, 120);
}
}
</script>
</head>
<body onload='startup();'>
<canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"></canvas>
</body>
</html>
```
Unfortunately this seems to rotate it from the top left angle of the image. Any idea?
Edit: in the end the object (space ship) has to rotate like a clock pointer, as if it is turning right/left. | First you have to translate to the point around which you would like to rotate. In this case the image dimensions are 64 x 120. To rotate around the bottom center you want to translate to 32, 120.
```
ctx.translate(32, 120);
```
That brings you to the bottom center of the image. Then rotate the canvas:
```
ctx.rotate(90 * Math.PI/180);
```
Which rotate by 90 degrees.
Then when you draw the image try this:
```
ctx.drawImage(img, -32, -120, 64, 120);
```
? Does that work? | The correct answer is, of course, Vincent's one.
I fumbled a bit with this rotation/translation thing, and I think my little experiments could be interesting to show:
```
<html>
<head>
<title>test</title>
<script type="text/javascript">
canvasW = canvasH = 800;
imgW = imgH = 128;
function startup() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Just to see what I do...
ctx.strokeRect(0, 0, canvasW, canvasH);
var img = new Image();
img.src = 'player.png';
img.onload = function() {
// Just for reference
ctx.drawImage(img, 0, 0, 128, 128);
ctx.drawImage(img, canvasW/2 - imgW/2, canvasH/2 - imgH/2, 128, 128);
mark(ctx, "red");
// Keep current context (transformations)
ctx.save();
// Put bottom center at origin
ctx.translate(imgW/2, imgH);
// Rotate
// Beware the next translations/positions are done along the rotated axis
ctx.rotate(45 * Math.PI / 180);
// Mark new origin
mark(ctx, "red");
// Restore position
ctx.translate(-imgW/2, -imgH);
ctx.drawImage(img, 0, 0, imgW, imgH);
mark(ctx, "green");
// Draw it an wanted position
ctx.drawImage(img, canvasW/2, canvasH/3, imgW, imgH);
// Move elsewhere:
ctx.translate(canvasW/2, canvasH/2);
ctx.drawImage(img, 0, 0, imgW, imgH);
mark(ctx, "blue");
ctx.restore();
}
}
function mark(ctx, color) {
ctx.save();
//~ ctx.fillStyle = color;
//~ ctx.fillRect(-2, -2, 4, 4);
ctx.strokeStyle = color;
ctx.strokeRect(0, 0, imgW, imgH);
ctx.restore();
}
</script>
</head>
<body onload='startup();'>
<canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"></canvas>
</body>
</html>
```
My stumbling issue was that positioning the rotated figure is hard, because it is along the rotated axis: either we have to do some trigo math to paint at the primitive origin, or we have to draw on a secondary hidden canvas and then paint it on the target one.
Unless somebody else has a better idea? | Canvas rotate from bottom center image angle? | [
"",
"javascript",
"html",
"canvas",
"rotation",
""
] |
What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculations are done?
You could poll every X milliseconds for some public variable called "job finished" or something by the way, but then you'll receive the results later than when they would be available... the main code would be losing time waiting for them. On the other hand, if you use a lower X, the CPU would be wasted polling so many times.
So, what do you do to be aware that the Thread, or some Threads, have finished their work?
Sorry if it looks similar to this other [question](https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output), that's probably the reason for the *eben* answer, I suppose. What I meant was running lots of threads and know when all of them have finished, without polling them.
I was thinking more in the line of sharing the CPU load between multiple CPU's using batches of Threads, and know when a batch has finished. I suppose it can be done with **Future**s objects, but that blocking ***get*** method looks a lot like a hidden lock, not something I like.
Thanks everybody for your support. Although I also liked the answer by ***erickson***, I think ***saua***'s the most complete, and the one I'll use in my own code. | Don't use low-level constructs such as threads, unless you absolutely need the power and flexibility.
You can use a [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) such as the [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) to [submit()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)) [Callables](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html). This will return a [Future](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html) object.
Using that `Future` object you can easily check if it's done and get the result (including a blocking `get()` if it's not yet done).
Those constructs will greatly simplify the most common threaded operations.
I'd like to clarify about the blocking `get()`:
The idea is that you want to run some tasks (the `Callable`s) that do some work (calculation, resource access, ...) where you don't need the result *right now*. You can just depend on the `Executor` to run your code whenever it wants (if it's a `ThreadPoolExecutor` then it will run whenever a free Thread is available). Then at some point in time you probably *need* the result of the calculation to continue. At this point you're supposed to call `get()`. If the task already ran at that point, then `get()` will just return the value immediately. If the task didn't complete, then the `get()` call will wait until the task is completed. This is usually desired since you can't continue without the tasks result anyway.
When you don't need the value to continue, but would like to know about it if it's already available (possibly to show something in the UI), then you can easily call `isDone()` and only call `get()` if that returns `true`). | You could create a lister interface that the main program implements wich is called by the worker once it has finished executing it's work.
That way you do not need to poll at all.
Here is an example interface:
```
/**
* Listener interface to implement to be called when work has
* finished.
*/
public interface WorkerListener {
public void workDone(WorkerThread thread);
}
```
Here is an example of the actual thread which does some work and notifies it's listeners:
```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Thread to perform work
*/
public class WorkerThread implements Runnable {
private List listeners = new ArrayList();
private List results;
public void run() {
// Do some long running work here
try {
// Sleep to simulate long running task
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
results = new ArrayList();
results.add("Result 1");
// Work done, notify listeners
notifyListeners();
}
private void notifyListeners() {
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
WorkerListener listener = (WorkerListener) iter.next();
listener.workDone(this);
}
}
public void registerWorkerListener(WorkerListener listener) {
listeners.add(listener);
}
public List getResults() {
return results;
}
}
```
And finally, the main program which starts up a worker thread and registers a listener to be notified once the work is done:
```
import java.util.Iterator;
import java.util.List;
/**
* Class to simulate a main program
*/
public class MainProg {
public MainProg() {
WorkerThread worker = new WorkerThread();
// Register anonymous listener class
worker.registerWorkerListener(new WorkerListener() {
public void workDone(WorkerThread thread) {
System.out.println("Work done");
List results = thread.getResults();
for (Iterator iter = results.iterator(); iter.hasNext();) {
String result = (String) iter.next();
System.out.println(result);
}
}
});
// Start the worker thread
Thread thread = new Thread(worker);
thread.start();
System.out.println("Main program started");
}
public static void main(String[] args) {
MainProg prog = new MainProg();
}
}
``` | Getting the output of a Thread | [
"",
"java",
"multithreading",
""
] |
Since I've started using NetBeans, I've learned of some [powerful ways](http://www.netbeans.org/kb/60/java/gui-db.html) to abstract away the process of creating Java database applications with automatically generated UI, beans bindings, and a bunch of other stuff I only vaguely understand the workings of at the moment (I hate being a newb). Problem is, *how do I do the basic stuff I actually want to do*? The tutorials I've read make a big deal about being able to connect to and mess around with a database from within the IDE, or how to create and bind some UI sliders and checkboxes to table columns, etc. But where can I learn about how to make my own code do that stuff? Abstraction is nice and all, but it's quite useless to me at the moment for what I need done.
Can anyone refer me to some good resources or tutorials to learn this? The few I've found aren't proving as useful as I'd hoped to get my project underway... | The [JDBC Tutorial](http://java.sun.com/docs/books/tutorial/jdbc/index.html) is a good starting point
A snippet from the intro
```
The JDBC API is a Java API that can access any kind of tabular data,
especially data stored in a Relational Database.
JDBC helps you to write java applications that manage these three programming
activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to
your query
The following simple code fragment gives a simple example of
these three steps:
```
```
Connection con = DriverManager.getConnection
( "jdbc:myDriver:wombat", "myLogin","myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
```
```
This short code fragment instantiates a DriverManager object to
connect to a database driver and log into the database, instantiates a
Statement object that carries your SQL language query to the database;
instantiates a ResultSet object that retrieves the results of your query,
and executes a simple while loop, which retrieves and displays those
results. It's that simple.
```
There is also a book preview on Google Books [here](http://tinyurl.com/5sgag8). | One you get comfortable with JDBC, you might want to consider using [Spring`s support for JDBC](http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html). It provides a much nicer API (than the standard libraries) for accessing a database via JDBC | What do I need to know to make a Java application that uses a database? | [
"",
"java",
"database",
"netbeans",
""
] |
I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?
Thanks | You might do something like this:
```
def action1():
pass # put a function here
def action2():
pass # blah blah
def action3():
pass # and so on
def no_such_action():
pass # print a message indicating there's no such action
def main():
actions = {"foo": action1, "bar": action2, "baz": action3}
while True:
print_menu()
selection = raw_input("Your selection: ")
if "quit" == selection:
return
toDo = actions.get(selection, no_such_action)
toDo()
if __name__ == "__main__":
main()
```
This puts all your possible actions' functions into a dictionary, with the key being what you will input to run the function. It then retrieves the action input action from the list, unless the input action doesn't exist, in which case it retrieves no\_such\_action.
After you have a basic understanding of how this works, if you're considering doing a Serious Business command-line–type application, I would look at the [`cmd` framework](http://docs.python.org/library/cmd.html) for command-line applications. | Generally if elif will be fine, but if you have lots of cases, please consider using a dict.
```
actions = {1: doSomething, 2: doSomethingElse}
actions.get(n, doDefaultThing)()
``` | Suggestion to implement a text Menu without switch case | [
"",
"python",
""
] |
Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects `std::vector::reserve` to throw `std::bad_alloc`. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) and behavior (expecting the exception to be thrown).
Here's a minimal example that reproduces it:
```
#include <vector>
int main()
{
size_t uint_max = static_cast<size_t>(-1);
std::vector<char> v;
v.reserve(uint_max);
}
```
Running valgrind, I get this output:
```
Warning: silly arg (-1) to __builtin_new()
new/new[] failed and should throw an exception, but Valgrind
cannot throw exceptions and so is aborting instead. Sorry.
at 0x40192BC: VALGRIND_PRINTF_BACKTRACE (valgrind.h:319)
by 0x401C823: operator new(unsigned) (vg_replace_malloc.c:164)
by 0x80487BF: std::vector<char, std::allocator<char> >::reserve(unsigned) new_allocator.h:92)
by 0x804874D: main (vg.cxx:6)
```
I'd like to modify my unit test to simply skip the offending code when it's being run from within valgrind. Is this possible? | You should look at [this page](http://valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.clientreq) from the Valgrind manual, it contains a `RUNNING_ON_VALGRIND` macro (included from valgrind.h) which does what you want. | If one does not want to include `valgrind.h` (which requires an autoconf test or similar) or use a wrapper, here's a heuristic for Linux (and other systems using ELF?): test the value of the `LD_PRELOAD` environment variable since Valgrind works by preloading libraries. I use the following test in C to check whether `LD_PRELOAD` contains the string `"/valgrind/"` or `"/vgpreload"`:
```
int tests_run_within_valgrind (void)
{
char *p = getenv ("LD_PRELOAD");
if (p == NULL)
return 0;
return (strstr (p, "/valgrind/") != NULL ||
strstr (p, "/vgpreload") != NULL);
}
```
Other systems might have a similar solution. I suggest the following command to see whether the environment mentions Valgrind:
```
valgrind env | grep -i valgrind
```
Edit:
In the relatively unlikely event that you are trying to do this either on macOS or on FreeBSD i386 running on an amd64 kernel then the environment variables are different.
* macOS uses DYLD\_INSERT\_LIBRARIES
* FreeBSD uses LD\_32\_PRELOAD (ONLY for i386 on amd64, not amd64 on amd64 or i386 on i386).
Plain LD\_PRELOAD should work for all Linux and Solaris variants. | How can I detect if a program is running from within valgrind? | [
"",
"c++",
"unit-testing",
"valgrind",
""
] |
I get the above error whenever I try and use ActionLink ? I've only just started playing around with MVC and don't really understand what it's problem is with the code (below):
```
<%= Html.ActionLink("Lists", "Index", "Lists"); %>
```
This just seems to be a parsing issue but it only happens when I run the page. The application builds perfectly fine, so I really don't get it because the error is a compilation error? If I take line 25 out it will happen on the next line instead...
```
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1026: ) expected
Source Error:
Line 23: </div>
Line 24:
Line 25: <%= Html.ActionLink("Lists", "Index", "Lists"); %>
Line 26: <a href="<%= Url.Action("/", "Lists"); %>">Click here to view your lists</a>
Line 27:
Source File: d:\Coding\Playground\HowDidYouKnowMVCSoln\HowDidYouKnowMVC\Views\Home\Index.aspx Line: 25
``` | Remove the semi-colon from the ActionLink line.
Note: when using `<%= ... %>` there's no semi-colon and the code should return something, usually a string. When using `<% ...; %>`, i.e. no equals after the percent, the code should return void and you need a semi-colon before the closing percent.
When using Html methods, for example, VS intellisense will tell you whether it returns void. If so, don't use an equals and terminate with a semi-colon. | Use it without trailing semicolon:
```
<%= Html.ActionLink("Lists", "Index", "Lists") %>
``` | ActionLink CS1026: ) expected | [
"",
"c#",
"asp.net",
"asp.net-mvc",
""
] |
How do I set the executable icon for my C++ application in visual studio 2008? | First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.
Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.
Then compile your project and see the effect.
See: <http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0> | This is how you do it in Visual Studio 2010.
Because it is finicky, this can be quite painful, actually, because you are trying to do something *so incredibly simple*, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to sink your teeth into a 2 by 4 and scream, by all means, please do so.
Gotchas:
* You need to [use an .ico file](http://www.convertico.com/images/1329756536.52/Cursor%20drag%20move.ico). ***You cannot use a PNG image file for your executable's icon, it will not work. You must use .ico.*** [There are web utilities](http://www.convertico.com/) that convert images to .ico files.
* The ico used for your exe will be the ico with the LOWEST RESOURCE ID. In order to change the .ico
1) Open **VIEW** > **RESOURCE VIEW** (in the middle of the **VIEW** menu), or press `Ctrl`+`Shift`+`E` to get it to appear.
2) In Resource view, right click the project name and say **ADD** > **RESOURCE...**
3) Assuming you have already generated an .ico file yourself, choose **Icon** from the list of crap that appears, then click **IMPORT**.
4) At this dialog `*.ico` files aren't listed, and you **can't** use a regular PNG or JPG image as an icon, so change the file filter to **`*.ico`** using the dropdown. Misleading UI, I know, I know.
5) If you compile your project now, it will **automatically** stick the .ico **with the lowest ID** (as listed in `resource.h`) as the icon of your .exe file.
6) If you load a bunch of ICO files into the project for whatever reason, be sure the .ico you want Visual Studio to use has **the lowest** id in `resource.h`. You can edit this file manually with no problems
Eg.
```
//resource.h
#define IDI_ICON1 102
#define IDI_ICON2 103
```
IDI\_ICON1 is used
```
//resource.h
#define IDI_ICON1 106
#define IDI_ICON2 103
```
Now IDI\_ICON2 is used. | How do I set the icon for my application in visual studio 2008? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"icons",
""
] |
Wnen I use external resources such as files or DB connection I need to close them before I let them go.
Do I need to do the same thing with Swing components ? If yes then how ? | Normally, you don't need to dispose of objects when you are done with them (although setting the references to them to null may allow them to be GCed sooner). However, AWT and Swing objects allocate some amount of native resources that need to be freed. Furthermore, the AWT thread treats the windows as top-level objects, preventing them from being garbage collected and the JVM from terminating.
Thus, when you are done with your window, you need to dispose of it, which frees the native resources that it has allocated. One way to do this is to call [Window.dispose](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#dispose())() on it. However, a better option would be to call [JFrame.setDefaultCloseOperation](http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html)() when you initialize each of your root windows. If you pass it DISPOSE\_ON\_CLOSE it will take care of disposing itself when the user closes the window. When the last such window closes, the AWT thread will stop blocking and allow the JVM to close (assuming you don't have any other aberrant threads running). Alternatively, you can pass it EXIT\_ON\_CLOSE, which will cause your window to call System.exit(), which tells the JVM that your application is done and to gracefully terminate. | At one point it was taught that you had to disconnect all the listeners, because otherwise they'd act as references to the Swing component. But I'm told that this is no longer a problem. | Do I need to free Swing components before letting them get garbage collected? | [
"",
"java",
"swing",
""
] |
I'm having an error where I am not sure what caused it.
Here is the error:
```
Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'user_id' in 'field list'")
```
Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine.
My view code is below:
```
if "login" in request.session:
t = request.POST.get('title', '')
d = request.POST.get('description', '')
fid = request.session["login"]
fuser = User.objects.get(id=fid)
i = Idea(user=fuser, title=t, description=d, num_votes=1)
i.save()
return HttpResponse("true", mimetype="text/plain")
else:
return HttpResponse("false", mimetype="text/plain")
```
I appreciate any help! Thanks!
Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?
Edit: Here are the relevant models:
```
class User (models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
password = models.CharField(max_length=200)
class Idea (models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
description = models.CharField(max_length=255)
num_votes = models.IntegerField()
``` | You'll have to show your models to get real help, but it looks like your Idea table doesn't have a user\_id column? Did you modify the SQL table structure? | 1. The `user_id` field is the FK reference from `Idea` to `User`. It looks like you've changed your model, and not updated your database, then you'll have this kind of problem.
Drop the old table, rerun syncdb.
2. Your model tables get an `id` field by default. You can call it `id` in your queries. You can also use the synonym of `pk`.
If you define your own primary key field you, you don't get the automatic `id` field. But you can still use `pk` to refer to the Primary Key. | "Unknown column 'user_id' error in django view | [
"",
"python",
"django",
"django-models",
"model",
"view",
""
] |
I am writing a program that does a lot of writes to a Postgres database. In a typical scenario I would be writing say 100,000 rows to a table that's well normalized (three foreign integer keys, the combination of which is the primary key and the index of the table). I am using PreparedStatements and executeBatch(), yet I can only manage to push in say 100k rows in about 70 seconds on my laptop, when the embedded database we're replacing (which has the same foreign key constraints and indices) does it in 10.
I am new at JDBC and I don't expect it to beat a custom embedded DB, but I was hoping it to be only 2-3x slower, not 7x. Anything obvious that I maybe missing? does the order of the writes matter? (i.e. say if it's not the order of the index?). Things to look at to squeeze out a bit more speed? | This is an issue that I have had to deal with often on my current project. For our application, insert speed is a critical bottleneck. However, we have discovered for the vast majority of database users, the select speed as their chief bottleneck so you will find that there are more resources dealing with that issue.
So here are a few solutions that we have come up with:
First, all solutions involve using the postgres [COPY command](http://www.postgresql.org/docs/8.3/static/sql-copy.html). Using COPY to import data into postgres is by far the quickest method available. However, the JDBC driver by default does not currently support COPY accross the network socket. So, if you want to use it you will need to do one of two workarounds:
1. A JDBC driver patched to support COPY, such as this [one](http://kato.iki.fi/sw/db/postgresql/jdbc/copy/).
2. If the data you are inserting and the database are on the same physical machine, you can write the data out to a file on the filesystem and then use the COPY command to import the data in bulk.
Other options for increasing speed are using JNI to hit the postgres api so you can talk over the unix socket, removing indexes and the [pg\_bulkload project](http://pgfoundry.org/projects/pgbulkload/). However, in the end if you don't implement COPY you will always find performance disappointing. | Check if your connection is set to autoCommit. If autoCommit is true, then if you have 100 items in the batch when you call executeBatch, it will issue 100 individual commits. That can be a lot slower than calling executingBatch() followed by a single explicit commit().
I would avoid the temptation to drop indexes or foreign keys during the insert. It puts the table in an unusable state while your load is running, since nobody can query the table while the indexes are gone. Plus, it seems harmless enough, but what do you do when you try to re-enable the constraint and it fails because something you didn't expect to happen has happened? An RDBMS has integrity constraints for a reason, and disabling them even "for a little while" is dangerous. | Tips on Speeding up JDBC writes? | [
"",
"java",
"performance",
"postgresql",
"jdbc",
""
] |
I have an update query being run by a cron task that's timing out. The query takes, on average, five minutes to execute when executed in navicat.
The code looks roughly like this. It's quite simple:
```
// $db is a mysqli link
set_time_limit (0); // should keep the script from timing out
$query = "SLOW QUERY";
$result = $db->query($query);
if (!$result)
echo "error";
```
Even though the script shouldn't timeout, the time spent waiting on the sql call still seems to be subject to a timeout.
Is there an asynchronous call that can be used? Or adjust the timeout?
Is the timeout different because it's being called from the command line rather than through Apache?
Thanks | I had the same problem somwhere, and "solved" it with the following code (first two lines of my file):
```
set_time_limit(0);
ignore_user_abort(1);
``` | According to the [manual](https://www.php.net/set_time_limit):
> **Note**: The set\_time\_limit() function and the configuration directive max\_execution\_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running.
So it's unlikely to have anything to do with PHP's time limit. What message are you getting when it times out? Perhaps there's a MySQL setting involved. | How to keep a php script from timing out because of a long mysql query | [
"",
"php",
"mysql",
"timeout",
""
] |
What's the regex to match a square bracket? I'm using `\\]` in a pattern in `eregi_replace`, but it doesn't seem to be able to find a `]`... | `\]` is correct, but note that PHP itself ALSO has `\` as an escape character, so you might have to use `\\[` (or a different kind of string literal). | Works flawlessly:
```
<?php
$hay = "ab]cd";
echo eregi_replace("\]", "e", $hay);
?>
```
Output:
```
abecd
``` | How do I match a square bracket literal using RegEx? | [
"",
"php",
"regex",
"string",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.