Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting? ``` static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){ PyObject *o; //gen...
`PyDict_New()` returns a new reference, check the [docs](http://docs.python.org/c-api/dict.html) for `PyDict`. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways. You als...
OT: Using successive calls to `PyList_Append` is a performance issue. Since you know how many results you'll get in advance, you can use: ``` PyObject *pyTimeList = PyList_New(NUM_DRAWERS); int i; for (i=0; i<NUM_DRAWERS; i++){ o = PyInt_FromLong(pdbHeader->last_good_test[i]); PyList_SET_ITEM(pyTimeList, i, o)...
Why is my Python C Extension leaking memory?
[ "", "python", "c", "refcounting", "" ]
Take the following code for example; ``` if (Convert.ToString(frm.WindowState) == "Minimized") Layout.WindowState = "Maximized"; else Layout.WindowState = Convert.ToString(frm.WindowState); ``` We are analysing the string definition of the window state, i.e. "Minimized". Would this string des...
The [`WindowState`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.windowstate.aspx) value *is* an enumeration - [`System.Windows.Forms.FormWindowState`](http://msdn.microsoft.com/en-us/library/system.windows.forms.formwindowstate.aspx). Just compare to the enumeration constants, skip the `ToString()...
It shouldn't change across culture, since it's merely turning the Enum name into string. Enum name doesn't change when you use different culture of .Net/Windows/IDE, thus it will remain as what it was originally written.
C# Will "WindowState.ToString" change between cultures
[ "", "c#", "windowstate", "" ]
I have a Winform with a BackgroundWorker. The BackgroundWorker, among other things, has to make an HTTP call to a page, fill out some data, submit the form, and retrieve the HTML that comes back after "clicking" the submit button. I've run into a number of roadblocks while doing this: 1. Can't POST the data because th...
What web-server is it that doesn't support POST in this scenario? What does the comparable HTML form do? A POST or a GET? Just do the same.. I suspect that WebClient or HttpWebRequest will do the job fine.
Have you tried using [WebClient.UploadValues](http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvalues(VS.80).aspx) with the Method argument set to "GET" ?
C#/Winform: Enter data into HTML page, submit form
[ "", "c#", "multithreading", "http", "interop", "backgroundworker", "" ]
This is perhaps similar to previous posts, but I want to be specific about the use of locking on a network, rather than locally. I want to write a file to a shared location, so it may well go on a network (certainly a Windows network, maybe Mac). I want to prevent other people from reading any part of this file whilst ...
This can't be reliably done on a network file system. As long as your application is the only application that accesses the file, it's best to implement some kind of cooperative locking process (perhaps writing a lock file to the network filesystem when you open the file). The reason that is not recommended, however, i...
You can have a empty file which is lying on the server you want to write to. When you want to write to the server you can catch the token. Only when you have the token you should write to any file which is lying on the server. When you are ready with you file operations or an exception was thrown you have to release ...
Java file locking on a network
[ "", "java", "file", "networking", "" ]
What is the best way to generate a string of `\t`'s in C#? I am learning C# and experimenting with different ways of saying the same thing. `Tabs(uint t)` is a function that returns a `string` with `t` amount of `\t`'s For example, `Tabs(3)` returns `"\t\t\t"` Which of these three ways of implementing `Tabs(uint nu...
What about this: ``` string tabs = new string('\t', n); ``` Where `n` is the number of times you want to repeat the string. Or better: ``` static string Tabs(int n) { return new string('\t', n); } ```
``` string.Concat(Enumerable.Repeat("ab", 2)); ``` Returns > "abab" And ``` string.Concat(Enumerable.Repeat("a", 2)); ``` Returns > "aa" from... [Is there a built-in function to repeat string or char in .net?](https://stackoverflow.com/questions/4115064/is-there-a-built-in-function-to-repeat-string-or-char-in-n...
Best way to repeat a character in C#
[ "", "c#", ".net", "string", "" ]
I am using LINQ to EF and have the following LINQ query: ``` var results = (from x in ctx.Items group x by x.Year into decades orderby decades.Count() descending select new { Decade = decades.Key, DecadeCount = decades.Count() }); ``` So this kind of gets me to where I wan...
It looks like we cannot do a grouping or select or similar on calculated fields that are definied in the partial classes on the entity framework. The calculated fields can be used on LINQ to objects (so you could return all the data as objects and then do a grouping)
You can use the `let` clause to avoid counting the decades multiple times: ``` from x in ctx.Items group x by (x.Year / 10 * 10) into decades let decadeCount = decades.Count() orderby decadeCount descending select new { Decade = decades.Key, DecadeCount = decadeCount } ```
Using LINQ how do I have a grouping by a "calculated field"
[ "", "c#", ".net", "linq", ".net-3.5", "linq-to-entities", "" ]
Hey I am developing an desktop application using Spring and Hibernate, and I have a problem with lazy initiation. I looked in the web and every solution is related to the open session in view pattern, but I can't use this pattern. I've also tried to get the `sessionfactory` from the `HibernateTemplate`, but it returns ...
I would suggest that you basically have two solutions: 1. Make arrangements to keep a Hibernate session open when you access a lazy-initialized object or collection. That means you're going to have to carefully mark your transaction boundaries in your code, a la the "open session in view" pattern. Spring makes this po...
One option is to call Hibernate.initialize() on the entities or collections to force initialize them. You'd want to do this before you return the data back to your view. I would consider this carefully, since it's going to generate a lot of SQL statements back to the database. You may want to look into using "fetch" i...
Spring and Hibernate, Lazy initiation problem
[ "", "java", "hibernate", "spring", "lazy-loading", "" ]
I'm exploring the possibility of running a Java app on a machine with very large amounts of RAM (anywhere from 300GB to 15TB, probably on an SGI Altix 4700 machine), and I'm curious as to how Java's GC is likely to perform in this scenario. I've heard that IBM's or JRockit's JVMs may be better suited to this than Sun'...
On the Sun JVM, you can use the option -XX:UseConcMarkSweepGC to turn on the Concurrent mark and sweep Collector, which will avoid the "stop the world" phases of the default GC algorithm almost completely, at the cost of a little bit more overhead. The advise to use more than on VM on such a machine is IMHO outdated. ...
The question is: do you want to run within a single process (JVM) or not? If you do, then you're going to have a problem. Refer to [Tuning Java Virtual Machines](http://edocs.beasys.com/wls/docs81/perform/JVMTuning.html), [Oracle Coherence User Guide](http://coherence.oracle.com/display/COH34UG/Coherence+User+Guide+(Fu...
Java performance with very large amounts of RAM
[ "", "java", "garbage-collection", "" ]
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures wil...
Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields. ``` class EligibilityForm(forms.Form): def __init__(self, *args, **kwargs): super(EligibilityForm, self).__init__(*args, **kwargs) # dynamic fields here ... self.fields['p...
If you run ``` python manage.py shell ``` and type: ``` from app.forms import PictureForm p = PictureForm() p.fields type(p.fields) ``` you'll see that p.fields is a SortedDict. you just have to insert a new field. Something like ``` p.fields.insert(len(p.fields)-2, 'fieldname', Field()) ``` In this case it would...
Variable number of inputs with Django forms possible?
[ "", "python", "django", "django-forms", "" ]
I am trying to add a link into the pop-up text bubble of a marker in Google Maps through the API. I have successfully run the below code: ``` echo '<marker lat="43.91892" lng="-78.89231" html="Albertus Magnus College&lt;br&gt;Link to Admissions" label="Albertus Magnus College" />'; ``` But once I actually try to add ...
This is the answer: ``` $window2a_url = '&lt;a href=&apos;http://www.albertus.edu/admission/index.shtml&apos;&gt;Admissions'; echo '<marker lat="41.331304" lng="-72.921438" html=" Albertus Magnus College&lt;br&gt;'; echo $window2a_url; echo '" label="Albertus Magnus College" />'; ``` I had to escape the apostrophes.....
Seems you are putting an apostrophe (') inside the string. You should use an escape character (may be "\", I don't know PHP's syntax) near the apostrophe.
Google Map API and Links
[ "", "php", "api", "google-maps", "" ]
Let's say I have a table like this: ``` name | score_a | score_b -----+---------+-------- Joe | 100 | 24 Sam | 96 | 438 Bob | 76 | 101 ... | ... | ... ``` I'd like to select the minimum of score\_a and score\_b. In other words, something like: ``` SELECT name, MIN(score_a, score_b) FROM ta...
[LEAST](https://www.postgresql.org/docs/current/functions-conditional.html#FUNCTIONS-GREATEST-LEAST)(a, b): > The `GREATEST` and `LEAST` functions select the largest or smallest value from a list of any number of expressions. The expressions must all be convertible to a common data type, which will be the type of the ...
Here's the link to docs for the `LEAST()` function in PostgreSQL: <http://www.postgresql.org/docs/current/static/functions-conditional.html#AEN15582>
How do I get the MIN() of two fields in Postgres?
[ "", "sql", "postgresql", "min", "" ]
What communication is going on between Eclipse and my application server (JBoss) when I run the server from within Eclipse in debugging mode? How does this work?
When you start the server in debug mode, it listens on a specified TCP port. Eclipse connects to that port, and they talk using the Java Debug Wire Protocol (JDWP). Read the details here: <http://java.sun.com/j2se/1.5.0/docs/guide/jpda/>
I think it is called JDWP (Java Debugging Wire Protocol) - read more [here](http://java.sun.com/j2se/1.5.0/docs/guide/jpda/architecture.html)
How does Eclipse debug code in an application server?
[ "", "java", "eclipse", "jakarta-ee", "jdb", "" ]
I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question. In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to un...
The relevant answer is found in [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt), section 2.1 *URI and non-ASCII characters* --- The relationship between URI and characters has been a source of confusion for characters that are not part of US-ASCII. To describe the relationship, it is useful to distinguish between a "...
On the question: "But is a URL actually text?" It depends on the context, in some languages or libraries (for example java, I'm not sure about python), a URL may be represented internally as an object. However, a URL always has a well defined text representation. So storing the text-representation is much more portabl...
URLs: Binary Blob, Unicode or Encoded Unicode String?
[ "", "python", "mysql", "database", "url", "" ]
Something I do often if I'm storing a bunch of string values and I want to be able to find them in O(1) time later is: ``` foreach (String value in someStringCollection) { someDictionary.Add(value, String.Empty); } ``` This way, I can comfortably perform **constant-time** lookups on these string values later on, ...
If you're using .Net 3.5, try [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx). If you're not using .Net 3.5, try [C5](http://www.itu.dk/research/c5/). Otherwise your current method is ok (bool as @leppie suggests is better, or not as @JonSkeet suggests, dun dun dun!). ``` HashSet<string> stringSet = n...
You can use `HashSet<T>` in .NET 3.5, else I would just stick to you current method (actually I would prefer `Dictionary<string,bool>` but one does not always have that luxury).
'Proper' collection to use to obtain items in O(1) time in C# .NET?
[ "", "c#", ".net", "optimization", "collections", "string", "" ]
I don't think this can be done "cleanly", but I'll ask anyway. I have a system which needs to get a JSON resource via a REST GET call in order to initialize. At the moment the system waits until the onLoad event and fires an ajax request to retrieve the resource, which I don't think is the best way to do it, as the re...
I was thinking of putting it in an iframe but then I realized that you have a problem with that the content-type is application/json. When I tested FF, IE and Chrome was trying to download the file and asked the user where to store it (Opera displayed the file) Putting it in a LINK will not help you since the browser ...
Maybe I'm not understanding but couldn't you just: ``` <?php $json_data = json_encode($your_data); ?> <script> var data = <?= $json_data ?>; </script> ```
Load JSON at runtime rather than dynamically via AJAX
[ "", "javascript", "html", "dom", "" ]
I have a C# public API that is used by many third-party developers that have written custom applications on top of it. In addition, the API is used widely by internal developers. This API wasn't written with testability in mind: most class methods aren't virtual and things weren't factored out into interfaces. In addi...
What you're really asking is, "How do I design my API with SOLID and similar principles in mind so my API plays well with others?" It's not just about testability. If your customers are having problems testing their code with yours, then they're also having problems WRITING/USING their code with yours, so this is a big...
Another approach would be to create a seperate branch of the API and do option 3 there. Then you just maintain these two versions and deprecate the former. Merging changes from one branch into the other should work automatically most of the time.
How to make an existing public API testable for external programmers using it?
[ "", "c#", ".net", "unit-testing", "" ]
I have a Gridview in which i have two templatefields of dropdownlist. I bound them on runtime with same list item. ``` li = new listitem ("1","1"); dl1.items.add(li); dl2.items.add(li); li = new listitem ("2","2"); dl1.items.add(li); dl2.items.add(li); li = new listitem ("3","3"); dl1.items.add(li); dl2.items.add(li...
The ListItem class has a property "Selected" which marks if the item is selected. I haven't checked the DDL SelectedValue property to see what it does, but my guess is that the ListItem.Selected property is being set to true, and since you are using the same object in both drop-down lists, it is being marked as 'select...
Looking at just the last part of the code: you've got a single list item, and it's appearing in two different lists. But it's still one object. How would you expect one object to have two different values for a single property (SelectedValue)?
Dropdowns filled with same list item
[ "", "c#", "gridview", ".net-2.0", "" ]
I really need help with interfaces in general... Any resources that you guys would recommend me? ### Related: * [How are Java interfaces actually used?](https://stackoverflow.com/questions/504904/how-are-java-interfaces-actually-used) * [Java interface and inheritance](https://stackoverflow.com/questions/1215437/jav...
[What is an Interface?](http://java.sun.com/docs/books/tutorial/java/concepts/interface.html) from Java's official tutorial Edit: A second resource from the same tutorial, is the [Interfaces and Inheritence](http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html) section.
In general: You can see an interface as a contract or an agreement between two parties. So they can develop independently as long as the interface does not change. The calling party, knows which behaviour is available and the implementing party knows what to implement. There are a lot of advantages by using interfac...
Java Interfaces?
[ "", "java", "oop", "" ]
I want to set up a continuous integration and test framework for my open source C++ project. The desired features are: ``` 1. check out the source code 2. run all the unit and other tests 3. run performance tests (these measure the software quality - for example how long does it take the system to complete the test) 4...
I am using CruiseControl and UnitTest++ today for exactly this task. UnitTest++ is really nice although I feel sometimes limited by it around the corner. At least it is 10 times better than cppunit. Still haven't tried the google testing framework, it will be for my next project. I have been extremely disappointed by...
I have written an article that might help you. It describes continuous integration of C++ code using googletest and hudson, using gcov for code coverage metrics. <http://meekrosoft.wordpress.com/2010/06/02/continuous-code-coverage-with-gcc-googletest-and-hudson/>
c++ continuous integration with performance metrics
[ "", "c++", "unit-testing", "continuous-integration", "automated-tests", "cruisecontrol", "" ]
Are there any Java VMs which can save their state to a file and then reload that state? If so, which ones?
Another option, which may or may not be relevant in your case, is to run the JVM (any JVM) inside a virtual machine. Most virtual machines offer the option to store and resume state, so you *should* be able to restart your PC, fire up the VM when it comes back up and have the Java process pick up from where it was. I ...
[Continuations](http://en.wikipedia.org/wiki/Continuation) are probably be what you are looking for: > [...] first class continuations, which are constructs > that give a programming language the > ability to save the execution state at > any point and return to that point at > a later point in the program. There are...
Are there any Java VMs which can save their state to a file and then reload that state?
[ "", "java", "persistence", "virtual-machine", "" ]
I've got a bunch of strings like: ``` "Hello, here's a test colon&#58;. Here's a test semi-colon&#59;" ``` I would like to replace that with ``` "Hello, here's a test colon:. Here's a test semi-colon;" ``` And so on for all [printable ASCII values](http://www.w3schools.com/tags/ref_ascii.asp). At present I'm using...
The big advantage of using a regex is to deal with the tricky cases like `&#38;#38;` Entity replacement isn't iterative, it's a single step. The regex is also going to be fairly efficient: the two lead characters are fixed, so it will quickly skip anything not starting with `&#`. Finally, the regex solution is one with...
``` * Repaired SNOBOL4 Solution * &#38;#38; -> &#38; digit = '0123456789' main line = input :f(end) result = swap line arb . l + '&#' span(digit) . n ';' rem . line :f(out) result = result l char(n) :(swap) out output = result line :(main) end ```
Regex Replacing &#58; to ":" etc
[ "", "c++", "regex", "boost", "ascii", "ncr", "" ]
I'm currently refactoring/tidying up some old C code used in a C++ project, and regularly see functions such as: ``` int f(void) ``` which I would tend to write as: ``` int f() ``` Is there any reason not to replace (void) with () throughout the codebase in order to improve consistency, or is there a subtle differe...
In C, the declaration `int f(void)` means a function returning int that takes no parameters. The declaration `int f()` means a function returning int that takes any number of parameters. Thus, if you have a function that takes no parameters in C, the former is the correct prototype. In C++, I believe `int f(void)` is ...
To add to [Chris's answer](https://stackoverflow.com/questions/416345/is-fvoid-deprecated-in-modern-c-and-c/416354#416354), using `int f()` is bad practice in C, in my experience, since you lose the compiler's ability to compare the function's declaration to its definition, to ensure that it will be called correctly. ...
Is f(void) deprecated in modern C and C++?
[ "", "c++", "c", "refactoring", "void", "" ]
I need to minify some C# code in a handful of Silverlight .cs and .xmal files. What are your tips for maintaining one code base and running a "tool" to generate minified code for a project? Are there any tools (like Resharper) that will do this? If not fully, partially or assist in some way... EDIT: I realize that th...
How about a source-code obfuscator? They generally abbreviate names, etc - and certainly remove white space. For example, [here](http://www.semdesigns.com/Products/Obfuscators/CSharpObfuscator.html), with demo [here](http://www.semdesigns.com/Products/Obfuscators/CSharpObfuscationExample.html) (although you'd probably...
Is that necessary? It was my understanding that the compiled .Net assembly would be sent across the wire, not the C# (or whatever language) source code.
Do you have any tips for C# Minification?
[ "", "c#", "xaml", "minify", "" ]
I have a TextBox control on my Form. I use the Leave event on the control to process user input. It works fine if the user clicks on some other control on the form, but the even doesn't get fired when the user goes straight to the main menu. Any ideas which event should I use to get it fired everytime?
I found a reasonable workaround, I set the focus on the main menu manually: EDIT: As suggested by @TcKs, I changed the event from ItemClicked to MenuActivate. Thanks very much for help! ``` private void menuStrip1_MenuActivate( object sender, EventArgs e ) { menuStrip1.Focus(); } ```
You should use "Validating" and "Validated" events for checking user's input. Then if user go to another control "A", and the control "A" has property "CausesValidation" set to "true" ( its default value ) the "Validating" and "Validated" event will be fired. The menu has "CausesValidation" property too. **Edit:** So...
WinForms: Textbox Leave event doesn't get fired after going to main menu
[ "", "c#", ".net", "winforms", "" ]
Is there anyway I can make the process of adding references to C# projects less painful? Every time I create a new C# class library project. I have to use the Add Reference dialog for 5 times at least.
Install the [PowerCommands for Visual Studio](http://code.msdn.microsoft.com/PowerCommands). You can then simply copy and paste a bunch of references between projects (plus lots of other useful commands). Some of the other useful commands are: * Collapse Projects (my favourite) * Copy References and Paste References *...
You can select more than one reference at a time to add using CTRL-Click. You can also use the Recent tab to find references that you've added recently to other projects easily.
Add references manually
[ "", "c#", ".net", "visual-studio", "" ]
I cannot seem to access the context object using a loop context is set: `var context = [id1, id2, id3];` This callback function works: ``` function OnChangeSucceeded(result, context, methodName) { document.getElementById(context[0]).disabled = result; document.getElementById(context[1]).disabled = result; ...
Thats for the pointer to firebug tvanfosson. I have redone the function and it now works as: ``` function OnChangeSucceeded(result, context, methodName) { for (controlId in context) { document.getElementById(context[controlId]).disabled = result; } } ``` I am not sure if it was because the context wa...
It would be handy to see the calling code so that we could see how your context is established. I'm going to guess that you've set it up as an association and not an array so that when you go to use it in the callback, there is no length property (or it's 0). When you set it up it should look like: ``` var context = ...
How to access the context object as an array in PageMethods callback
[ "", "asp.net", "javascript", "callback", "" ]
I am looking at an asp.net 2 web application that I am maintaining (but did not write). Some things that should happen on the page loading do not, but only sometimes, and it seems to be if you are using Firefox 3 inside a VM. JQuery and asp.net Ajax are used. The important function that should run every time (but doe...
Try this: ``` <script type="text/javascript"> //<![CDATA[ $(document).ready(ImportantFunction); $(document).ready(Otherstuff); $(document).ready(MoreStuff); //]]> </script> ``` Put the call to `Sys.Application.add_load` in the body of `ImportantFunction`, i.e in your .js file: ``` function importantFunction() { ...
Is there any reason why you can't use the ASP.NET AJAX pageLoad function instead of $(document).ready()? ``` function pageLoad(sender, args) { ImportantFunction(); OtherStuff(); MoreStuff(); } ``` This is part of the ASP.NET AJAX client page lifecycle and all JavaScript code inside will be executed on ...
Javascript function should be running on every page load
[ "", "javascript", "jquery", "ajax", "asp.net-ajax", "" ]
Without having the full module path of a Django model, is it possible to do something like: ``` model = 'User' [in Django namespace] model.objects.all() ``` ...as opposed to: ``` User.objects.all(). ``` EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e....
I think you're looking for this: ``` from django.db.models.loading import get_model model = get_model('app_name', 'model_name') ``` There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get...
For Django 1.7+, there is an [applications registry](https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps). You can use the [`apps.get_model`](https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model) method to dynamically get a model. ``` from django.apps import apps My...
How do I retrieve a Django model class dynamically?
[ "", "python", "django", "django-models", "django-queryset", "" ]
On my blog, I want to display the all the posts from the last month. But if that is less than 10 posts, I want to show the ten most recent posts (in other words, there should never be less than 10 posts on the front page). I am wondering if there is a way to do this in a single query? Currently, I first run this query...
Just do this: ``` select * from posts order by timestamp desc limit 100 ``` And filter the results further in memory. (assumes 100 is a practical upper limit for "posts in a month" that people would want to see in a single page) This is a "more efficient single query".
``` (SELECT * FROM posts WHERE `timestamp` >= NOW() - INTERVAL 30 DAY) UNION (SELECT * FROM posts ORDER BY `timestamp` DESC LIMIT 10); ``` **edit:** Re @doofledorfer's comment: I ran this on my test database, and it worked fine. I tried comparing `timestamp` to a date literal as well as the constant expression as show...
How to query for 10 most recent items or items from last month, whichever is more?
[ "", "sql", "mysql", "" ]
I'm rewriting a PHP web site in ASP.NET MVC. I'd like to maintain the same user base but the passwords are hashed using the PHP crypt() function. I need the same function in .Net so that I can hash a password on login and check it against the hashed password in the user database. crypt in this case is using the CRYPT\...
The only solution I found was to call a trivial PHP script that simply performs a hash of the input string and returns it :-(
There are a few .NET methods for md5 hashing, `System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, format)` is the easiest to use, even though it's a mouthful. Just pass "md5" through as the format. Depending on how PHP is doing this, it may be as simple as chopping the `$1$` off the b...
PHP crypt() function in .Net?
[ "", "php", ".net", "asp.net", "security", "encryption", "" ]
i know that the JDK consists of all java packages .But what does the JRE consist of apart from java.exe ? I could understand the necessities of things in 'bin' folder in the JRE but what about the 'lib' folder ?
Have a look at this [JDK and JRE File Structure](http://java.sun.com/javase/6/docs/technotes/tools/windows/jdkfiles.html) document from Sun's JDK documentation. It specifically says the following about the `lib` directory: > Code libraries, property settings, and resource files used by the Java runtime environment. F...
JRE is composed of the JVM which is the runtime interpreter for the Java language, the Class Loader, Secure Execution Implementation classes, Java APIs(core classes, SE classes) and the Java Web (Deployment) foundation which includes Java Web Start. The lib part of JRE is Java's Library containing classes that lay the...
What does the JRE consist of?
[ "", "java", "" ]
Currently our Java application uses the values held within a tab delimited \*.cfg file. We need to change this application so that it now uses an XML file. What is the best/simplest library to use in order to read in values from this file?
There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta [commons-configuration](http://commons.apache.org/configuration/) and [commons-digester](http://commons.apache.org/digester/). You could always use the standard JDK method of getting a doc...
XML Code: ``` <?xml version="1.0"?> <company> <staff id="1001"> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff id="2001"> <firstname>low</firstname> <lastname>yin fong</lastname> ...
What is the best/simplest way to read in an XML file in Java application?
[ "", "java", "xml", "file", "" ]
This is probably a simple question, and I'm slightly embarrassed to ask it, but I've been working with this chunk of JavaScript ad code for a while and it's bothered me that it's never really made sense to me and is probably out dated now with modern browsers. My question is, do we need to check for browser types still...
On the second snippet of code: it's checking for two things: * That the browser opening the document supports the document.images portion of the DOM, that the document contains any images, and the browser's UserAgent string (an identifier) contains "Mozilla/2.", * OR that the UserAgent string contains "WebTV" in thos...
Mostly we use javascript libraries like [jQuery](http://jquery.com/) which handle this kind of thing for us. Strangely I find myself hacking per-browser CSS much more often these days.
Do we still need to check for different browser types in JavaScript?
[ "", "javascript", "jquery", "" ]
I'm just learning Qt with C++. I have successfully implemented signals and slots to trap standard events like `ButtonPushed()`, etc. However, I want to have a function called when I mouse over and mouse out of a `QLabel`. It looks like [QHoverEvent](http://doc.qt.io/qt-4.8/qhoverevent.html) will do what I need, but I c...
Using signals and slots for this purpose isn't going to work. `mouseMoveEvent()` is not a signal or meta-method and cannot be connected to a slot. Subclassing the widget class and overriding `mouseMoveEvent()` will allow you to get mouse-move-events, but that is a very heavyweight way to accomplish this (and adds one...
<https://doc.qt.io/qt-5/qwidget.html#enterEvent> <https://doc.qt.io/qt-5/qwidget.html#leaveEvent> <https://doc.qt.io/qt-5/qwidget.html#widget-attributes> ## `Qt::WA_Hover` > Forces Qt to generate paint events when the mouse enters or leaves the > widget. This feature is typically used when implementing custom > sty...
How do I implement QHoverEvent in Qt?
[ "", "c++", "qt", "events", "" ]
**UPDATE:** Obviously, you'd want to do this using templates or a base class rather than macros. Unfortunately for various reasons I can't use templates, or a base class. --- At the moment I am using a macro to define a bunch of fields and methods on various classes, like this: ``` class Example { // Use FIELDS_AN...
This cries out for a template. ``` class Example<class T> { ...class definition... }; ``` The direct answer to the last part of your question - "given that I'm not in a macro definition any more, how do I get pasting and stringizing operators to work" - is "You can't". Those operators only work in macros, so you'...
You have to add an extra layer of macros: ``` #define STRINGIZE(x) STRINGIZE2(x) #define STRINGIZE2(x) #x #define TOKENPASTE(x, y) TOKENPASTE2(x, y) #define TOKENPASTE2(x, y) x ## y ``` The reason is that when you have a macro, the preprocessor normally recursively expands the arguments before performing the macro s...
How do I replace this preprocessor macro with a #include?
[ "", "c++", "macros", "include", "c-preprocessor", "" ]
My application needs to execute a fairly complicated series of queries against a database. Normally I would just dump everything into a stored procedure and execute it that way. But I do not have access to the database I'm trying to access so I can't create a stored procedure. Is there a better way of doing this inste...
There's nothing wrong with joining 10 tables if that's ultimately what you need to do. Generally SQL is good at this kind of thing. However, if there isn't that tight of a coupling between your 5-6 queries, then run them separately. If you choose to break up the query, hitting the DB 5-6 times is fine--absolutely noth...
You can always execute the same series of queries in a single shot by separating them by ";" .
Application execute complex SQL query
[ "", "sql", "sql-server", "t-sql", "" ]
In the process of fixing a poorly imported database with issues caused by using the wrong database encoding, or something like that. Anyways, coming back to my question, in order to fix this issues I'm using a query of this form: > UPDATE `table_name` SET field\_name = > replace(field\_name,’search\_text’,'replace\_t...
Let's try and tackle each of these separately: If the set of replacements is the same for every column in every table that you need to do this on (or there are only a couple patterns), consider creating a user-defined function that takes a varchar and returns a varchar that just calls `replace(replace(@input,'search1'...
I don't know of a way to automatically run a search-and-replace on each column, however the problem of multiple pairs of search and replace terms in a single `UPDATE` query is easily solved by nesting calls to `replace()`: ``` UPDATE table_name SET field_name = replace( replace( replace( ...
SQL to search and replace in mySQL
[ "", "sql", "mysql", "" ]
I [half-answered a question about finding clusters of mass in a bitmap](https://stackoverflow.com/questions/411837/finding-clusters-of-mass-in-a-matrix-bitmap#411855). I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the lis...
Just so you know, you are asking for a solution to an [ill-posed](http://en.wikipedia.org/wiki/Ill-posed) problem: no definitive solution exists. That's fine...it just makes it more fun. Your problem is ill-posed mostly because you don't know how many clusters you want. Clustering is one of the key areas of machine lea...
It sounds to me like you're looking for the [K-means](http://en.wikipedia.org/wiki/K_means) algorithm.
Filtering away nearby points from a list
[ "", "python", "algorithm", "language-agnostic", "bitmap", "filtering", "" ]
I have the following enumeration: ``` public enum AuthenticationMethod { FORMS = 1, WINDOWSAUTHENTICATION = 2, SINGLESIGNON = 3 } ``` The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1. I have found the following solution for this problem ([link...
Try [type-safe-enum](http://www.javacamp.org/designPattern/enum.html) pattern. ``` public sealed class AuthenticationMethod { private readonly String name; private readonly int value; public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS"); public static readonly Aut...
Use method ``` Enum.GetName(Type MyEnumType, object enumvariable) ``` as in (Assume `Shipper` is a defined Enum) ``` Shipper x = Shipper.FederalExpress; string s = Enum.GetName(typeof(Shipper), x); ``` There are a bunch of other static methods on the Enum class worth investigating too...
String representation of an Enum
[ "", "c#", "enums", "" ]
How would you open a file (that has a known file/app association in the registry) into a "running instance" of the application it's supposed to open in? An example would be, I have Excel open and I click on an XLS file.....the file opens up in the current Excel instance. I want to do this for a custom application...how...
What you want to do is inherit a class from [WindowsFormsApplicationBase](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.applicationservices.windowsformsapplicationbase.aspx), setting the protected [IsSingleInstance](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.applicationservices.window...
Looks like what you are looking for is creating a single instance application. This can be done in C# by using WindowsFormsApplicationBase located in Microsoft.VisualBasic.dll For details, take a look at: <http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx> or sear...
Opening a "known file type" into running instance of custom app - .NET
[ "", "c#", ".net", "winforms", "" ]
I am using JavaScript and jQuery. My main file has `My.js` and Ajax. ### My.js ``` function build_one(){ alert("inside build_one"); } ``` ### My main file ``` <script type="text/javascript"> .. // Here I want to make call function defined in My.js build_one() .. // Here is the Ajax call ...
This should work: ``` <script type="text/javascript" src="My.js"></script> <script type="text/javascript"> build_one(); $.ajax({ type:'POST', url: 'ajax.php', data:'id='+id , success: function(data){ $("#response").html(data); } ...
First you have to import your file before calling the function using the following ``` <script type="text/javascript" src="My.js"></script> ``` Now you can call your function where ever you want.
Calling a JavaScript function inside jQuery
[ "", "javascript", "jquery", "" ]
I need to query a table for values given a string. The table is case sensitive but I want to do a ToLower() in the comparison. Suppose I have a classes table with the following data. ``` class teacher ----------------- Mat101 Smith MAT101 Jones mat101 Abram ENG102 Smith ``` My query should be something li...
No; it would be better to improve the data: create a numeric ID that represents these seemingly meaningless variations of class (and probably an associated lookup table to get the ID). Use the ID column in the where clause and you should be hitting an indexed numeric column. If that's no an option, consider a function...
Here is more information about Function-based Indexes (what Dave was referring to above): * [Using Function-based Indexes for Performance](http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/data_acc.htm#i9946) * [Function-Based Indexes](http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/schema....
Compare Strings in Oracle
[ "", "sql", "oracle", "comparison", "" ]
How can you prematurely exit from a function without returning a value if it is a void function? I have a void method that needs to not execute its code if a certain condition is true. I really don't want to have to change the method to actually return a value.
Use a return statement! ``` return; ``` or ``` if (condition) return; ``` You don't need to (and can't) specify any values, if your method returns `void`.
You mean like this? ``` void foo ( int i ) { if ( i < 0 ) return; // do nothing // do something } ```
How do you exit from a void function in C++?
[ "", "c++", "" ]
Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger? I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be passed debug options too.
A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev: ``` import inspect def isdebugging(): for frame in inspect.stack(): if frame[1].endswith("pydevd.py"): return True return False ``` The same should work with pdb by simply replacing `pydevd.py` with `pdb.py`...
Python debuggers (as well as profilers and coverage tools) use the `sys.settrace` function (in the `sys` module) to register a callback that gets called when interesting events happen. If you're using Python 2.6, you can call `sys.gettrace()` to get the current trace callback function. If it's not `None` then you can ...
How to detect that Python code is being executed through the debugger?
[ "", "python", "debugging", "" ]
Is there a way to use the formatter that comes with eclipse, outside of eclipse? I would like to format some java files using my formatter.xml file that I have configured using eclipse. Does anyone have any code examples that would allow me to do this? I would also like to use this standalone, so the specific jars that...
Apparently you can [directly invoke Eclipse's code formatter from the command line](https://peterfriese.wordpress.com/2007/05/28/formatting-your-code-using-the-eclipse-code-formatter/).
Here's the [offical eclipse docs](https://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-231.htm) on how to do this ### Dump of those docs: Running the formatter application is as simple as running the org.eclipse.jdt.core.JavaCodeFormatter application from the commandline: ``` ecl...
Can the Eclipse Java formatter be used stand-alone
[ "", "java", "eclipse", "formatter", "" ]
This is an example of RegisterClientScriptBlock ``` Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "key","scriptblock", True) ``` Why do the method needs the type as the first parameter ? Thanks.
From the MSDN docs: "A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates." Basically it gives you an additional way to uniquely identify your scripts. You could have the same key value across different types of controls.
I've wondered about this myself. As far as I can see in Reflector, it's not used by RegisterClientScriptBlock() directly, it is only passed through to be used by the GetHashCode() method of the ScriptKey class. There it probably serves to uniquely identify the script block further beyond just the user-supplied key, sin...
What is the significance of the Type parameter in the RegisterClientScriptBlock method call?
[ "", "asp.net", "javascript", "" ]
In a Java web application I have a recurring message load of type A (e.g., 20,000 every hour). Then I have a second type of messages (type B) that show up occasionally but have a higher priority than type A (say, 3,000). I want to be able to process these messages on one or more machines using open source software. It...
Set the message priority when you call "send(..)" on the MessageProducer (QueueSender, etc). Or, you can set the default priority on the MessageProducer from 0-9 (9 is highest). Setting the priority on the message itself won't work. It's overridden by the Producer. Uri is correct--whether or not the priority is respec...
The JMS standard supports message priorities default is 4, you can specify others). I think you need to set that in the message producer AND in the message itself (there are methods on both). I think that ActiveMQ does support it. However, many JMS broker have priority handling disabled by default. There is a flag th...
Message processing with priorities
[ "", "java", "message-queue", "" ]
I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment: > Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflo...
As far as the C++ standard is concerned, [litb](https://stackoverflow.com/questions/346622/opinions-on-type-punning-in-c#346675)'s answer is completely correct and the most portable. Casting `const char *data` to a `const uint3_t *`, whether it be via a C-style cast, `static_cast`, or `reinterpret_cast`, breaks the str...
Ignoring efficiency, for simplicity of code I'd do: ``` #include <numeric> #include <vector> #include <cstring> uint32_t compute_checksum(const char *data, size_t size) { std::vector<uint32_t> intdata(size/sizeof(uint32_t)); std::memcpy(&intdata[0], data, size); return std::accumulate(intdata.begin(), int...
Opinions on type-punning in C++?
[ "", "c++", "casting", "type-punning", "" ]
This question is related to ["How to make consistent dll binaries across VS versions ?"](https://stackoverflow.com/questions/232926/how-to-make-consistent-dll-binaries-across-vs-versions) * We have applications and DLLs built with VC6 and a new application built with VC9. The VC9-app has to use DLLs compiled wit...
Interface member names will *not* be decorated -- they're just offsets in a vtable. You can define an interface (using a C struct, rather than a COM "interface") in a header file, thusly: ``` struct IFoo { int Init() = 0; }; ``` Then, you can export a function from the DLL, with no mangling: ``` class CFoo : pub...
The biggest problem to consider when using a DLL compiled with a different C++ compiler than the calling EXE is memory allocation and object lifetime. I'm assuming that you can get past the name mangling (and calling convention), which isn't difficult if you use a compiler with compatible mangling (I think VC6 is broa...
Using C++ DLLs with different compiler versions
[ "", "c++", "windows", "visual-c++-6", "visual-c++-2008", "name-decoration", "" ]
I have a condition in which I need to close the application and so I call this.Dispose () when I set a certian flag. At first I thought it was a problem of calling functions after I call this.Dispose () and so I moved the code to be the last thing called, but I still get an "ArgumentException was unhandled" "Parameter...
Try using `Application.Exit()` to exit the application. When you use `Application.Run(new MyForm());`, a message loop is created on the thread using the form object as the main form. It tries to deliver Win32 messages that are coming to the application to their respective objects. However, when you call `Dispose()` on...
You should use this.Close() rather than this.Dispose() to close your main form.
Application.Run throws ArgumentException was unhandled
[ "", "c#", "winforms", "dispose", "argumentexception", "" ]
I am evaluating options for efficient data storage in Java. The data set is time stamped data values with a named primary key. e.g. ``` Name: A|B|C:D Value: 124 TimeStamp: 01/06/2009 08:24:39,223 ``` Could be a stock price at a given point in time, so it is, I suppose, a classic time series data pattern. However, I r...
I would look at a [column oriented database](http://en.wikipedia.org/wiki/Column-oriented_DBMS "Column Oriented Database"). It would be great for this sort of application
Hibernate (or any JPA solution) is the wrong tool for this job. JPA/Hibernate isn't a lightweight solution. In high-volume applications, the overhead is not only significant but prohibitive. You really need to look into [grid and cluster solutions](https://stackoverflow.com/questions/383920/what-is-the-best-library-fo...
What are my options to store and query huge amounts of data where a lot of it is repeating?
[ "", "java", "database", "hibernate", "jdbc", "compression", "" ]
I have a simulation that reads large binary data files that we create (10s to 100s of GB). We use binary for speed reasons. These files are system dependent, converted from text files on each system that we run, so I'm not concerned about portability. The files currently are many instances of a POD struct, written with...
In my experience, second-guessing the data you'll need is invariably wasted time. What's important is to structure your *metadata* in a way that is extensible. For XML files, that's straightforward, but binary files require a bit more thought. I tend to store metadata in a structure at the END of the file, not the beg...
For large binaries I'd look seriously at HDF5 (Google for it). Even if it's not something you want to adopt it might point you in some useful directions in designing your own formats.
What to put in a binary data file's header
[ "", "c++", "c", "binaryfiles", "" ]
The following code will generate a link to the page I want to get to. ``` <%= Html.ActionLink(image.Title, image.Id.ToString(), "Image") %> ``` The following code will cause the correct url to be rendered on the page. ``` <%= Url.Action("Index", "Image", new { id = image.Id })%> ``` But when I try to use it in java...
This should work actually. ASP.NET MVC will substitute all <%= ... %> or similar tags, it does not recognize whether it's a html definition or javascript. What is the output of your view? Is the "strange error" coming from Javascript or ASP.NET? **EDIT**: regarding your update: make sure your Index.aspx has the "Codeb...
Take a look at [this](http://codeguru302.blogspot.com/2008/11/aspnet-make-sure-that-class-defined-in.html) for a possible solution to your error message. Codebehind vs Codefile.
How do I do a JavaScript redirect in ASP.Net MVC?
[ "", "javascript", "asp.net-mvc", "" ]
I have a .mbm file that I copy to my device using this line in the .pkg file ``` "$(EPOCROOT)epoc32\data\z\resource\apps\MyApp.mbm" -"!:\resource\apps\MyApp.mbm" ``` Then in the draw function of my container I do this.. ``` _LIT(KMBMFile , "\\resource\\apps\\MyApp.mbm" ); CFbsBitmap* iBitmap; iBitmap->Load(KMBMFile...
You were dereferencing an uninitialized pointer, you could also use this: ``` // remember to include the EIK environemnt include file #include <eikenv.h> _LIT(KMBMFile , "\\resource\\apps\\MyApp.mbm" ); CFbsBitmap* iBitmap; iBitmap = iEikonEnv->CreateBitmapL( KMBMFile, 0 ); gc.BitBlt( Rect().iTl, iBitmap ); ```
I have solved this problem so will post answer here for future lookers.. Create an MBM file in your MMP file using a snippet like this ``` START BITMAP MyApp.mbm HEADER TARGETPATH \resource\apps SOURCEPATH ..\gfx SOURCE c24 background.bmp END ``` **ensure your .bmp images are saved in 32 bit fr...
Symbian C++ - Load and display image from .mbm file
[ "", "c++", "mobile", "symbian", "carbide", "" ]
I recently wrote a piece of code which did ``` SomeClass someObject; mysqlpp::StoreQueryResult result = someObject.getResult(); ``` where SomeClass::getResult() looks like: ``` mysqlpp::StoreQueryResult SomeClass::getResult() { mysqlpp::StoreQueryResult res = ...<something>...; return res; } ``` Now, using the exam...
I don't think there's any difference in the two cases. The same copy constructor is called both times. Are you sure this is *exactly* what you've written in your code?
Strictly speaking in the first case the default constructor is called followed by the assignment operator and in the second case it uses just the copy constructor. Okay, my initial assumption was wrong, and apparently in both cases just the copy constructor would get called (well in the assignment case an additional "...
C++ Copy Constructors
[ "", "c++", "constructor", "" ]
i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this: ``` class Item(models.Model): data = models.TextField() order = models.IntegerField() ``` or like this: ``` class Item(models.Model): data = models.TextField() next = m...
Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of `n` elements, you will need `n` database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient. In regular ...
That depends on what you want to do. The first one seems better to make a single query in the database and get all data in the correct order The second one seems better to insert an element between two existing elements (because in the first one you'd have to change a lot of items if the numbers are sequential) I'd ...
Ordered lists in django
[ "", "python", "django", "django-models", "" ]
I want to handle F1-F12 keys using JavaScript and jQuery. I am not sure what pitfalls there are to avoid, and I am not currently able to test implementations in any other browsers than Internet Explorer 8, Google Chrome and Mozilla FireFox 3. Any suggestions to a full cross-browser solution? Something like a well-tes...
The best source I have for this kind of question is this page: <http://www.quirksmode.org/js/keys.html> What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).
I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the [shortcut](http://www.openjs.com/scripts/events/keyboard_shortcuts/) library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way. Single keystroke: ``` shortcut....
Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser
[ "", "javascript", "jquery", "events", "keyboard", "keyboard-events", "" ]
I have two constructor : ``` function clsUsagerEmailUserName($nickName, $email) { $this->nickName = $nickName; $this->email = $email; } function clsUsagerEmailUserName($email) { $this->email = $email; } ``` But this is not working? What's wrong, isn't supposed to...
PHP5 doesn't allow overloaded constructor. Alternativly you can use function to set or you can use this trick (found at EE): ``` function __construct ($var1, $var2 = null) { if (isset($var2)) { //Do one thing } else { //Do another } } ```
If you have a good reason to want to keep the function arguments in that order, do something like this: ``` function __construct() { switch ( func_num_args() ) { case 1: $this->email = func_get_arg(0); break; case 2: $this->nickName = func_get_arg(0); $th...
How can I have over loaded constructor in Php5?
[ "", "php", "constructor", "" ]
I have to login into a https web page and download a file using Java. I know all the URLs beforehand: ``` baseURL = // a https URL; urlMap = new HashMap<String, URL>(); urlMap.put("login", new URL(baseURL, "exec.asp?login=username&pass=XPTO")); urlMap.put("logout", new URL(baseURL, "exec.asp?exec.asp?page=999")); urlM...
I agree with Alnitak that the problem is likely storing and returning cookies. Another good option I have used is [HttpClient](http://hc.apache.org/httpclient-3.x/) from Jakarta Commons. It's worth noting, as an aside, that if this is a server you control, you should be aware that sending the username and password as...
As has been noted, you must maintain the session cookie between requests (see [CookieHandler](http://java.sun.com/javase/6/docs/api/java/net/CookieHandler.html)). Here is a sample implementation: ``` class MyCookieHandler extends CookieHandler { private Map<String, List<String>> cookies = new HashMap<String, Lis...
How do I login and download a file from a https web page from Java?
[ "", "java", "https", "" ]
I'm trying to build the search for a Django site I am building, and in that search, I am searching across three different models. And to get pagination on the search result list, I would like to use a generic object\_list view to display the results. But to do that, I have to merge three QuerySets into one. How can I ...
Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost. ``` from itertools import chain result_list = list(chain(page_list, article_list, post_list)) ``` Using `itertools.chain` is...
Try this: ``` matches = pages | articles | posts ``` It retains all the functions of the querysets which is nice if you want to `order_by` or similar. **Please note:** this doesn't work on querysets from two different models.
How to combine multiple QuerySets in Django?
[ "", "python", "django", "search", "django-queryset", "django-q", "" ]
I'm writing a C++ static library that needs to be shared among several applications, one of them written in Perl. Unfortunately, I only barely know the core Perl language (I read the Llama book), and I'm not all that familiar with its libraries. How do you make calls to an external C++ binary from a Perl script? By Go...
You want to look at using XS, which is how Perl normally interfaces with C/C++ libraries. It's not quite trivial. A couple of relevant portions of the Perl documentation: * [perlxs](http://perldoc.perl.org/perlxs.html) * [perlxstut](http://perldoc.perl.org/perlxs.html)
You can call code from other libraries via Inline::C (and likely the same via Inline::CPP) - have a look at [Inline::C::Cookbook](http://search.cpan.org/~sisyphus/Inline-0.45/C/C-Cookbook.pod). Most likely you want to start out with Inline and after you're done experimenting use the resulting .XS file to work further.
How do I call a C++ static library from Perl?
[ "", "c++", "perl", "" ]
I cannot get std::tr1::shared\_ptr for my WinMobile project since the STL for WinCE is maintained by a different team at Microsoft :( aarrgh... Anyone worked with another thread-safe, reference counting smart pointers? I'm actually using yasper which seems to be good. Thank you very much.
I'd also recommend boost::shared\_ptr. You can do what I did for a library, and use a #define to switch between std::tr1::shared\_ptr and boost::shared\_ptr, depending on the capabilities of the compiler. That way your code doesn't need to be modified [much] if/when the CE team add tr1 support. Just my 2c.
[Boost Smart Pointers](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm). In particular [boost::shared\_ptr](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm). I am pretty sure they are supported for your platform. This is where tr1::shared\_ptr came from.
Smart pointers for Windows Mobile 6 SDK
[ "", "c++", "windows-mobile", "windows-ce", "smart-pointers", "" ]
All of us who work with relational databases have learned (or are learning) that SQL is different. Eliciting the desired results, and doing so efficiently, involves a tedious process partly characterized by learning unfamiliar paradigms, and finding out that some of our most familiar programming patterns don't work her...
I am consistently disappointed by most programmers' tendency to mix their UI-logic in the data access layer: ``` SELECT FirstName + ' ' + LastName as "Full Name", case UserRole when 2 then "Admin" when 1 then "Moderator" else "User" end as "User's Role", case SignedIn wh...
Here are my top 3. Number 1. Failure to specify a field list. (Edit: to prevent confusion: this is a production code rule. It doesn't apply to one-off analysis scripts - unless I'm the author.) ``` SELECT * Insert Into blah SELECT * ``` should be ``` SELECT fieldlist Insert Into blah (fieldlist) SELECT fieldlist ``...
What are the most common SQL anti-patterns?
[ "", "sql", "anti-patterns", "" ]
I want to know if it is possible to end a for loop in C++ when an ending condition (different from the reacheing right number of iterations) is verified. For instance: ``` for (int i = 0; i < maxi; ++i) for (int j = 0; j < maxj; ++j) // But if i == 4 < maxi AND j == 3 < maxj, // then jump out of t...
You can use the `return` keyword: move the nested loop into a subroutine, invoke the subroutine to run the nested loops, and 'return' from the subroutine to exit [all] the loops.
Despite the "`goto` considered harmful" arguments, this seems like the perfect place for `goto`. That's essentially what you are doing in Perl. Seriously... consider the alternatives: **Extra State Variables** --- ``` for (int i=0; i<maxi; ++i) { bool leaveLoop = false; for (int j=0; j<maxj; ++j) { i...
Is it possible to exit a for before time in C++, if an ending condition is reached?
[ "", "c++", "loops", "label", "nested-loops", "" ]
I am running into the same problem as in this question: [How do you prevent leading zeros from being stripped when importing an excel doc using c#](https://stackoverflow.com/questions/22879/how-do-you-prevent-leading-zeros-from-being-stripped-when-importing-an-excel-doc) But I am not sure if that is the best solution...
I don't know the output of your XSL transformation: I will assume it's the xml format for Excel. Trying to reverse the process I wrote three numbers (007) in an Excel sheet: once as number, once as text and once as number but formatted to show 3 digits padded with zeros. Then I saved it as xml and looked at it. Here is...
add a ' (single quote) to the front of the string.
How to stop the leading 0's from being stripped off when exporting to excel from a datatable?
[ "", "c#", "asp.net", "excel", "" ]
My coworker is new to C# and didn't know about the coalesce operator. So, I saw him write a line of code like this: ``` string foo = "" + str; ``` The idea being that if str is null, this expression would return an empty string. Of course, that could be rewritten as this: ``` string foo = str ?? ""; ``` And I feel ...
IMO, it is much better to clearly define such logic i.e. don't use string concatenation to avoid null string and use conditional statement or ?? operator. Regarding other comments: > there is also a performance benefit to > using the null-coalescing operator, > since no concatenation need take place > (and, therefore...
I don't think one is any more readable than the other personally. I prefer this: ``` string foo = str ?? ""; ``` simply because I really like the ?? operator. If you are a brand newbie, I think that this would be a little easier to understand: ``` string foo = str == null ? "" : str; ``` or ``` string foo = ""; i...
Coalesce vs empty string concatenation
[ "", "c#", "string", "concatenation", "coalesce", "" ]
I make a lot of use of boost::scoped\_ptr in my code and it is great but I'm currently working with software that uses shared\_ptr all over the place and I'm wondering if I'm missing something. AFAIK a shared\_ptr is only useful if different threads are going to be accessing the same data and you don't know what order...
Threads are irrelevant here. What's relevant is whether it's easy to specify a point at which the object is no longer of use. Suppose several different objects want to use the same object. It might be a pack of data, or for input/output, or some geometric object, or whatever. You want the shared object to be deleted a...
> AFAIK a shared\_ptr is only useful if > different threads are going to be > accessing the same data Well, it's for situations where multiple **owners** own the same object pointed to by the smart pointer. They may access the smart pointers from different threads, and **shared\_ptr** is usable in that area too, but t...
shared_ptr: what's it used for
[ "", "c++", "boost", "shared-ptr", "raii", "" ]
Say that I have two tables like those: ``` Employers (id, name, .... , deptId). Depts(id, deptName, ...). ``` But Those data is not going to be modified so often and I want that a query like this ``` SELECT name, deptName FROM Employers, Depts WHERE deptId = Depts.id AND Employers.id="ID" ``` be as faster as i...
Generally, unless you "materialize" a view, which is an option in some software like MS SQL Server, the view is just translated into queries against the base tables, and is therefore no faster or slower than the original (minus the minuscule amount of time it takes to translate the query, which is nothing compared to a...
If Depts.ID is the primary key of that table, and you index the Employers.DeptID field, then this query should remain very fast even over millions of records. Denormalizing doesn't make sense to me in that scenario. Generally speaking, performance of a view will be almost exactly the same as performance when running ...
How do Views work in a DBM?
[ "", "sql", "mysql", "performance", "view", "" ]
I have six string variables say str11, str12, str13, str21, str21 and str23. I need to compare combination of these variables. The combinations I have to check is str11 -- str12 -- str13 as one group and str21 -- str22 -- str23 as other group. I have to compare these two groups. Now I'm in confusion which method sho...
I’d test individually. Is “AB” “CD” “EF” equal to “ABC” “DE” “F”? Me thinks not. P.S. If it is, then it’s a VERY special case, and if you decide to code it that way (as a concatenated comparison) then comment the hell out of it.
Splitting the comparison into three if statements is definitely not necessary. You could also simply do an AND with your comparisons, eg ``` if ( str11 equals str21 && str12 equals str22 && str13 equals str23) ... ```
String Comparison : individual comparison Vs appended string comparison
[ "", "java", "string", "comparison", "" ]
This is just a question to satisfy my curiosity. But to me it is interesting. I wrote this little simple benchmark. It calls 3 variants of Regexp execution in a random order a few thousand times: Basically, I use the same pattern but in different ways. 1. Your ordinary way without any `RegexOptions`. Starting with ....
In the Regex.Match version you are looking for the input in the pattern. Try swapping the parameters around. ``` var m3 = Regex.Match(pattern, item); // Wrong var m3 = Regex.Match(item, pattern); // Correct ```
[I noticed](https://stackoverflow.com/questions/414328/using-static-regex-ismatch-vs-creating-an-instance-of-regex#414411) similar behavior. I also wondered why the compiled version would be slower, but noticed that above a certain number of calls, the compiled version is faster. So I dug into [Reflector](http://www.re...
Why is a cached Regexp outperforming a compiled one?
[ "", "c#", "regex", "performance", "benchmarking", "" ]
I have small problem with my .net 2.0 winforms application. I want to embed a few different icons to app. There are also other requirements: * must be automatic rebuildable by ms-build; using external gui apps for preparation isn't allowed * application must contain versioninfo. After embeding multiple icons, I ...
I decided to put all icons into separate old-school plain win32 c++ \*.dll. It's more convienient and I don't need to do any tricks with versioninfo/win32resources.
The solution is actually quite simple, although it required that I think back to my first encounter with RC files... In a plain text file, you can write the following ``` #include <windows.h> // The following is some Win32 candy for // -- the Windows styles in XP, Vista & 7 // does the UAC too. 1 RT_MANIFEST "App...
Multiple Icons into c# 2.0 WinApp
[ "", "c#", "winapi", "icons", "" ]
I am attempting to get the information from one table (games) and count the entries in another table (tickets) that correspond to each entry in the first. I want each entry in the first table to be returned even if there aren't any entries in the second. My query is as follows: ``` SELECT g.*, count(*) FROM games g, ...
You need to do a left-join: ``` SELECT g.Game_Number, g.PutColumnsHere, count(t.Game_Number) FROM games g LEFT JOIN tickets t ON g.Game_Number = t.Game_Number GROUP BY g.Game_Number, g.PutColumnsHere ``` Alternatively, I think this is a little clearer with a correlated subquery: ``` SELECT g.Game_Number, G.PutColum...
You need to learn more about how to use joins in SQL: ``` SELECT g.*, count(*) FROM games g LEFT OUTER JOIN tickets t USING (game_number) GROUP BY g.game_number; ``` Note that unlike some database brands, MySQL permits you to list many columns in the select-list even if you only GROUP BY their primary key. As lon...
SQL GROUP BY/COUNT even if no results
[ "", "sql", "mysql", "" ]
I need to check a string to see if any word in it has multiple occurences. So basically I will accept: "google makes love" but I don't accept: "google makes google love" or "google makes love love google" etc. Any ideas? Really don't know any way to approach this, any help would be greatly appreciated.
Based on Wicked Flea code: ``` function single_use_of_words($str) { $words = explode(' ', trim($str)); //Trim to prevent any extra blank if (count(array_unique($words)) == count($words)) { return true; //Same amount of words } return false; } ```
Try this: ``` function single_use_of_words($str) { $words = explode(' ', $str); $words = array_unique($words); return implode(' ', $words); } ```
PHP Multiple Occurences Of Words Within A String
[ "", "php", "algorithm", "string", "substring", "" ]
This is my first post and I'm quite a novice on C++ and compiling in general. I'm compiling a program which requires some graphs to be drawn. The program create a *.dat file and then i should open gnuplot and write plot '*.dat'. That's fine. Is there a way to make gnuplot automatically open and show me the plot I nee...
Depending on your OS, you might be able to use [popen().](http://www.opengroup.org/onlinepubs/007908799/xsh/popen.html) This would let you spawn a gnuplot process and just just write to it like any other FILE\*. If you have datapoints to plot, you can pass them inline with the *plot "-" ...* option. Similarly, you may...
I'm learning this today too. Here is a small example I cooked up. ``` #include <iostream> #include <fstream> using namespace std; int main(int argc, char **argv) { ofstream file("data.dat"); file << "#x y" << endl; for(int i=0; i<10; i++){ file << i << ' ' << i*i << endl; } file.close(); ...
C++ and gnuplot
[ "", "c++", "gnuplot", "" ]
I need to find the caller of a method. Is it possible using stacktrace or reflection?
``` StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace() ``` According to the Javadocs: > The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence. A `StackTraceElement` has `getClassName()`, `getFileName()`, `getLineNumb...
**Note**: if you are using Java 9 or later you should use `StackWalker.getCallerClass()` as described in [Ali Dehghani's answer](https://stackoverflow.com/a/45812871/350692). The comparison of different methods below is mostly interesting for historical reason. --- An alternative solution can be found in a comment t...
How do I find the caller of a method using stacktrace or reflection?
[ "", "java", "stack-trace", "" ]
I compiled 2 different binaries on the same GNU/Linux server using g++ version 4.2.3. The first one uses: ``` GLIBC_2.0 GLIBC_2.2 GLIBC_2.1 GLIBCXX_3.4 GLIBC_2.1.3 ``` The second one uses: ``` GLIBC_2.0 GLIBC_2.2 GLIBC_2.1 GLIBCXX_3.4.9 GLIBCXX_3.4 GLIBC_2.1.3 ``` Why the second binary uses GLIBCXX\_3.4.9 that is ...
To find out which of the listed GLIBCXX\_3.4.9 symbol(s) your binary actually depends on, do this: ``` readelf -s ./a.out | grep 'GLIBCXX_3\.4\.9' | c++filt ``` Once you know which symbols to look for, you can trace back to the object which needs them: ``` nm -A *.o | grep _ZN<whatever> ``` Finally, to tie this bac...
Since you asked for it, here are symbols having at least ABI version 3.4.9: ``` GLIBCXX_3.4.9 { _ZNSt6__norm15_List_node_base4hook*; _ZNSt6__norm15_List_node_base4swap*; _ZNSt6__norm15_List_node_base6unhookEv; _ZNSt6__norm15_List_node_base7reverseEv; _ZNSt6__norm15_List_node_base8transfer*; _...
What make g++ include GLIBCXX_3.4.9?
[ "", "c++", "linux", "compiler-construction", "g++", "gnu", "" ]
I just started Shader programming(GLSL) and created a few with RenderMonkey. Now I want to use this Shaders in my java code. Are there any simple examples of how I do that?
I have found a very simple example ``` int v = gl.glCreateShader(GL.GL_VERTEX_SHADER); int f = gl.glCreateShader(GL.GL_FRAGMENT_SHADER); BufferedReader brv = new BufferedReader(new FileReader("vertexshader.glsl")); String vsrc = ""; String line; while ((line=brv.readLine()) != null) { vsrc += line + "\n"; } gl.glSh...
I don't have any myself, but if I have a problem along these lines I have often found the best place for 3D programming and Java advice is over at [JavaGaming.org](http://www.javagaming.org/) - I've not been there for a while, but it was always a helpful and knowledgeable community.
Jogl Shader programming
[ "", "java", "opengl", "jogl", "shader", "" ]
I'm writing a C# program to convert a FoxPro database to XML, and everything works except the memo field is blank. Is there something I'm missing to convert that bit? I'm using C# .Net 3.5 SP1, Visual FoxPro 9 SP 1 OLE DB Driver. Connection string is okay, as all other data is being pulled properly. When I converted ...
Ended up having to do some work myself, but maybe it can help someone else out in the future: ``` public static object GetDbaseOrFoxproRawValue(string DBPath, string TableName, string ColumnName, string CompareColumnName, string CompareValue, bool CompareColumnIsAutoKey) { using (BinaryRea...
I am not terribly familiar with C# or FoxPro or SQL Server, so I cannot give you much advice in that regard. However, if you cannot find a suitable driver, you may consider parsing the raw data and memo files yourself. Another question has dealt with this: [What's the easiest way to read a FoxPro DBF file from Python...
How do I extract the data in a FoxPro memo field using .NET?
[ "", "c#", "oledb", "visual-foxpro", "foxpro", "" ]
I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format. ``` import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www...
Someone recently asked [the same question you're asking](https://stackoverflow.com/questions/301924/python-urlliburllib2httplib-confusion). If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standar...
You probably want to look into preserving cookies from the server. [Pycurl](http://pycurl.sourceforge.net/) or [Mechanize](http://wwwsearch.sourceforge.net/mechanize/) will make this much easier for you
urllib2 data sending
[ "", "python", "urllib2", "" ]
Is there a compelling reason to not use [`debug_backtrace`](https://www.php.net/debug_backtrace) for the sole purpose of determining the calling method's class, name, and parameter list? Not for debugging purposes. It has the word "debug" in the function name, which makes me feel a little dirty to be using it in this w...
It does feel a little dirty, but as has been well documented, opined, and beaten to death elsewhere, PHP isn't a system designed for elegance. One highly convoluted reason **not** to use debug\_backtrace for application logic is it's possible some future developer working on PHP could decide "it's just a debug functio...
> Is there a compelling reason to not use debug\_backtrace for the sole purpose of determining the calling method's class, name, and parameter list? Yes. The point is, it's generally a sign of bad design if your code requires such a tight coupling that the callee has to have these information about its caller because ...
PHP debug_backtrace in production code to get information about calling method?
[ "", "php", "" ]
I checked out a copy of a C++ application from SourceForge (HoboCopy, if you're curious) and tried to compile it. Visual Studio tells me that it can't find a particular header file. I found the file in the source tree, but where do I need to put it, so that it will be found when compiling? Are there special directori...
Visual Studio looks for headers in this order: * In the current source directory. * In the Additional Include Directories in the project properties (*Project* -> *[project name] Properties*, under C/C++ | General). * In the Visual Studio C++ *Include directories* under *Tools* → *Options* → *Projects and Solutions* → ...
Actually, on my windows 10 with visual studio 2017 community, the path of the C++ header are: 1. `C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include` 2. `C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt` The 1st contains standard C++ headers such as `<iostr...
Where does Visual Studio look for C++ header files?
[ "", "c++", "visual-studio", "header", "" ]
I'm getting a syntax error (undefined line 1 test.js) in Firefox 3 when I run this code. The alert works properly (it displays 'work') but I have no idea why I am receiving the syntax error. jQuery code: ``` $.getJSON("json/test.js", function(data) { alert(data[0].test); }); ``` test.js: ``` [{"test": "work"}] ...
I found a solution to kick that error ``` $.ajaxSetup({'beforeSend': function(xhr){ if (xhr.overrideMimeType) xhr.overrideMimeType("text/plain"); } }); ``` Now the explanation: In firefox 3 (and I asume only firefox THREE) every file that has the mime-type of "text/xml" is parsed and syntax-checked. I...
getJSON may be insisting on at least one name:value pair. A straight array `["item0","item1","Item2"]` is valid JSON, but there's nothing to reference it with in the callback function for getJSON. In this little array of Zip codes: ``` {"result":[["43001","ALEXANDRIA"],["43002","AMLIN"],["43003","ASHLEY"],["43004",...
jQuery .getJSON Firefox 3 Syntax Error Undefined
[ "", "javascript", "jquery", "html", "json", "firefox", "" ]
I'd like to swap out an sql:query for some Java code that builds a complex query with several parameters. The current sql is a simple select. ``` <sql:query var="result" dataSource="${dSource}" sql="select * from TABLE "> </sql:query> ``` How do I take my Java ResultSet (ie. rs = stmt.executeQuery(sql);) and...
Model (Row): ``` public class Row { private String name; // Add/generate constructor(s), getters and setters. } ``` DAO: ``` public List<Row> list() throws SQLException { Connection connection = null; Statement statement = null; ResultSet resultSet = null; List<Row> rows = new ArrayList<Row>...
You set up a session/request attribute from the Java code. However, I would suggest *not* using a ResultSet, as it has some lifecycle issues (i.e. needs to be closed). I would suggest fetching the ResultSet object in the Java code, iterating over it building, say a List, closing the ResultSet and pass the List to the ...
How do I make a Java ResultSet available in my jsp?
[ "", "java", "jsp", "jdbc", "jstl", "" ]
Forgive me, for I am fairly new to C++, but I am having some trouble regarding operator ambiguity. I think it is compiler-specific, for the code compiled on my desktop. However, it fails to compile on my laptop. I think I know what's going wrong, but I don't see an elegant way around it. Please let me know if I am maki...
This is explained in the book "C++ Templates - The Complete Guide". It's because your operator[] takes size\_t, but you pass a different type which first has to undergo an implicit conversion to size\_t. On the other side, the conversion operator can be chosen too, and then the returned pointer can be subscript. So the...
It's too hard to get rid of the ambiguity. It could easily interpret it as the direct [] access, or cast-to-float\* followed by array indexing. My advice is to drop the operator GLfloat\*. It's just asking for trouble to have implicit casts to float this way. If you must access the floats directly, make a get() (or so...
C++ Operator Ambiguity
[ "", "c++", "opengl", "operators", "ambiguity", "operator-keyword", "" ]
Both `System.Timers.Timer` and `System.Threading.Timer` fire at intervals that are considerable different from the requested ones. For example: ``` new System.Timers.Timer(1000d / 20); ``` yields a timer that fires 16 times per second, not 20. To be sure that there are no side-effects from too long event handlers, I...
Well, I'm getting different number up to 100 Hz actually, with some big deviations, but in most cases closer to the requested number (running XP SP3 with most recent .NET SPs). The System.Timer.Timer is implemented using System.Threading.Timer, so this explains why you see same results. I suppose that the timer is imp...
If you use winmm.dll you can use more CPU time, but have better control. Here is your example modified to use the winmm.dll timers ``` const String WINMM = "winmm.dll"; const String KERNEL32 = "kernel32.dll"; delegate void MMTimerProc (UInt32 timerid, UInt32 msg, IntPtr user, UInt32 dw1, UInt32 dw2); [DllImport(WIN...
C# Why are timer frequencies extremely off?
[ "", "c#", "timer", "frequency", "deviation", "" ]
I know that if an IP falls outside the Subnet Mask + Local IP rules, it will be only reachable through an Gateway. The problem is that I don't know how to obtain the local IP address, neither the local subnet mask, programatically using .NET. Any of you can help me? I will use this information to squeeze the maximum p...
You can use the classes inside the System.Net.NetworkInformation namespace (introduced in .NET 2.0): ``` NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface iface in interfaces) { IPInterfaceProperties properties = iface.GetIPProper...
There is an alternative way using the [NetworkInformation](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx) class: ``` public static void ShowNetworkInterfaces() { // IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface...
How to determine whether an IP is from the same LAN programatically in .NET C#
[ "", "c#", ".net", "ip", "" ]
Here's the problem: 1.) We have page here... www.blah.com/mypage.html 2.) That page requests a js file www.foo.com like this... ``` <script type="text/javascript" src="http://www.foo.com/jsfile.js" /> ``` 3.) "jsfile.js" uses Prototype to make an Ajax request back to www.foo.com. 4.) The ajax request calls www.foo...
It is XSS and it is forbidden. You should really not do things that way. If you really need to, make your AJAX code call the local code (PHP, ASP, whatever) on blah.com and make it behave like client and fetch whatever you need from foo.com and return that back to the client. If you use PHP, you can do this with fopen...
There is a [w3c proposal](http://www.w3.org/TR/access-control/) for allowing sites to specify other sites which are allowed to make cross site queries to them. (Wikipedia might want to allow all request for articles, say, but google mail wouldn't want to allow requests - since this might allow any website open when you...
Cross domain Ajax request from within js file
[ "", "javascript", "html", "ajax", "" ]
I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized? Is it when the application starts in the same way as static data or is it compiler dependent? For example: ``` // foo.cpp #include "foo.h" namespace { const int SOME_VALUE = 42; } void foo::Som...
C++ Standard, **3.6.2/1** : > Zero-initialization and > initialization with a constant > expression are collectively called > static initialization; all other > initialization is dynamic > initialization. Objects of POD types > (3.9) with static storage duration > initialized with constant expressions > (5.19) shall b...
In this particular case (a global variable that is const) the variable is "initialized" at compile time. SOME\_VALUE is always equal to 42. In fact, most (all?) compiler will actually compile this as if it was hardcoded : ``` void foo::SomeFunc(int n) { if (n == 42) { ... } } ```
When is anonymous namespace data initialized?
[ "", "c++", "namespaces", "" ]
hey guys, i'm getting an exception on the following inner exception: {"Value cannot be null.\r\nParameter name: String"} Which reads like a simple error message, but none of the values (image, fileName) are null. How can i find out where this null String is? ``` RipHelper.UploadImage(image, fileName); ``` which cal...
The exception is in the static constructor of the class Helpers.RipHelper, at line 23 of RipHelper.cs. This line is calling Int32.Parse, passing a null value. Perhaps the static constructor is referencing a static field that has not yet been initialized. If you are having trouble debugging this, post the code of the c...
The error is occuring in the static constructor of the RipHelper class.
Exception with System.Drawing.Image
[ "", "c#", "exception", "" ]
I would like to write a utility that will provide me with a relatively unique ID in Java. Something pretty simple, like x bits from timestamp + y bits from random number. So, how would I implement the following method: ``` long getUniqueID() { long timestamp = System.currentTimeMillis(); long random = some ra...
Just clip the bits you don't need: ``` return java.util.UUID.randomUUID().getLeastSignificantBits(); ```
What you are trying to do is create a [hash function](http://en.wikipedia.org/wiki/Hash_function) that combines two long values into a single long value. In this case, the [uniformity](http://en.wikipedia.org/wiki/Hash_function#Uniformity) of the hash function will be of utmost importance since collisions in created un...
How can I assemble bits into a long to create a unique ID?
[ "", "java", "guid", "uuid", "bit", "" ]
When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding because I feel the overhead of maintaining the state of the yeilding method doesn't buy me much. In almost all cases where I am returning a collection I...
I recently had to make a representation of mathematical expressions in the form of an Expression class. When evaluating the expression I have to traverse the tree structure with a post-order treewalk. To achieve this I implemented IEnumerable<T> like this: ``` public IEnumerator<Expression<T>> GetEnumerator() { if...
Note that with yield, you are iterating over the collection once, but when you build a list, you'll be iterating over it twice. Take, for example, a filter iterator: ``` IEnumerator<T> Filter(this IEnumerator<T> coll, Func<T, bool> func) { foreach(T t in coll) if (func(t)) yield return t; } ``` Now, y...
Is yield useful outside of LINQ?
[ "", "c#", ".net", "linq", "yield", "" ]
My table has data like so ``` products_parent_id | products_quantity 2 5 2 7 2 9 2 4 ``` My SQL statement looks like so (so far): ``` UPDATE ' . TABLE_PRODUCTS . ' SET products_quantity = products_quantity +' . $order['products...
Short Answer: No Long Answer: Sort Of. Because the order the rows are returned is not defined by SQL. Technically two different requests to the DB could return the rows in a different order. So even if you update the third row, which is the third will depend on the implementation. The only way to mitigate this is ...
Your question doesn't make your reasons for doing this update entirely clear, but it does remind me of when I've been generating sample entries in a DB table and wanted to move a handful of them into category A or category B. Your SQL query doesn't specify an ORDER BY, so Martin's answer is correct in saying that you ...
Is it possible in MySQL to update only the nth occurence?
[ "", "php", "mysql", "" ]
If I have a class as follows ``` class Example_Class { private: int x; int y; public: Example_Class() { x = 8; y = 9; } ~Example_Class() { } }; ``` And a struct as follows ``` struct { int x; int...
The C++ standard *guarantees* that memory layouts of a C `struct` and a C++ `class` (or `struct` -- same thing) will be identical, provided that the C++ `class`/`struct` fits the criteria of being **POD** ("Plain Old Data"). So what does POD mean? A class or struct is POD if: * All data members are public and themsel...
> Is the structure in memory of the example\_struct simmilar to that in Example\_Class The behaviour isn't guaranteed, and is compiler-dependent. Having said that, the answer is "yes, on my machine", provided that the Example\_Class contains no virtual method (and doesn't inherit from a base class).
Structure of a C++ Object in Memory Vs a Struct
[ "", "c++", "struct", "" ]
I need to set/get the cookies stored at `first.example` while browsing `second.example`, I have full access of `first.example` but I only have JavaScript access (can manipulate the DOM as I want) on `second.example`. My first approach was to create an iframe on `second.example` (with JS) that loaded a page like `first...
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it. Something like: ``` <script type="text/javascript"> var newfile=document.createElement('script'); newfile.setAttribute("type","text/javascript"); newfile.setAttribute("s...
Put this PHP-File to first.com: ``` //readcookie.php echo $_COOKIE['cookiename']; ``` On second.com you can use this javascript to get the value: ``` function readCookieCallback() { if ((this.readyState == 4) && (this.status == 200)) { alert("the value of the cookie is: "+this.responseText); } ...
Getting setting cookies on different domains, with JavaScript or other
[ "", "javascript", "dns", "cookies", "" ]
I am trying to connect to a remote MySQL database using Visual C# 2008 Express Edition. Is there a way to connect using the editor, or do I have to code the connection manually? The editor has a clear and easy-to-follow wizard for connecting to Microsoft SQL Server and Access databases, but I don't see an easy way to a...
You will have to code the connection manually to connect to a remote MySQL database using Visual C# 2008 Express Edition. VS 2008 Express (and VS 2005 Express too) doesn't allow you to use MySQL .Net Provider through the Data Source Dialog. The non-Express edition allow you to do the same. To use MySQL in VS Express,...
**EDIT:** I didn't check Rishi Agarwal's answer before posting. I think his answer has more insight on the express edition I am not sure about this and express edition, but you should try [MySQL Connector/Net](http://dev.mysql.com/downloads/connector/net/5.2.html). It works fine with my VS2008 Pro.
Connect to remote MySQL database with Visual C#
[ "", "c#", ".net", "mysql", "" ]
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
It varies based on the options that you pass to `install` and the contents of the [distutils configuration files](http://docs.python.org/install/index.html#inst-config-files) on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways. Notably, [distutils do...
The three things that get installed that you will need to delete are: 1. Packages/modules 2. Scripts 3. Data files Now on my linux system these live in: 1. /usr/lib/python2.5/site-packages 2. /usr/bin 3. /usr/share But on a windows system they are more likely to be entirely within the Python distribution directory....
How do you uninstall a python package that was installed using distutils?
[ "", "python", "" ]
I have some model objects I'm using in my Java client application. Later these model objects will be populated / retrieved from remote services (e.g. SOAP). Now I want to do manual / automatic testing of the frontend before implementing these services. The model objects are mostly POJO and I want to store some sample t...
You can also use Spring to mock your remote service(s) and their responses. In this case, all you have to do is loading an applicationContext that will simulate your backend system(s) by replying exactly what you want for your test purpose.
Sounds like a good use of XML serialization. You can use any XML serialization tool you like: XStream, etc. Another nice tool is SOAP UI. If you point it to the WSDL for your service it'll create the XML request for you. Fill in the values and off you go. These can be saved, so perhaps that's a good way to generate te...
How to prepopulate model objects with test data from file?
[ "", "java", "windows", "" ]
So I have this regex: ``` (^(\s+)?(?P<NAME>(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P<NAME2>R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$)) ``` Now if I try and do a match against this: ``` B048661501f.foo ``` I get this error: ``` File "C:\Python25\lib\re.py", line 188, in compile ...
No, you can't have two groups of the same name, this would somehow defy the purpose, wouldn't it? What you probably *really* want is this: ``` ^\s*(?P<NAME>\w\d{7}|R1_(?:\d{6}_){2})(01f\.foo|\.(?:bar|goo|moo|roo))$ ``` I refactored your regex as far as possible. I made the following assumptions: You want to (correc...
Reusing the same name makes sense in your case, contrary to Tamalak's reply. Your regex compiles with python2.7 and also re2. Maybe this problem has been resolved.
Regex Problem Group Name Redefinition?
[ "", "python", "regex", "" ]
Consider two web pages with the following in their body respectively: ``` <body> <script> document.writeln('<textarea></textarea>') </script> </body> ``` and ``` <body> <script> var t = document.createElement('textarea'); document.body.appendChild(t); </script> </body> ``` (think of them as part of something larger...
I believe the document.write version actually blows away an existing content on the page. Ie, the body and script tags will no longer be there. That is why people usually use appendChild. Keeping the text or not is very browser specific. I wouldn't bet that Firefox would not change it's behavior on that in a future ve...
document.write() won't blow away the page content as long as it is executed inline as the page is rendered. Online advertising makes extensive use of document.write() to dynamically write adverts into the page as it loads. If however, you executed the document.write() method at a later time in the page history (after ...
document.write() vs inserting DOM nodes: preserve form information?
[ "", "javascript", "firefox", "usability", "" ]
I've taken over a mixed PHP4/PHP5 project which has been handed down from developer to developer, with each one making things worse. Before I spend too much time on it I'd like to develop a base-standard, with consistent formatting at a minimum. Can anyone recommend a utility (Linux or Mac OS X preferably) that will r...
You can do that with [Netbeans](http://netbeans.org) or with [Eclipse PDT](http://www.eclipse.org/pdt/), both excellent PHP editors. There's a Format Code option in each, which will reformat a selected file according to your code style preferences. There may be an option to format code in bulk as well. I do recommend ...
I use phptidy: ~~<http://cmr.cx/phptidy/>~~ <https://github.com/cmrcx/phptidy> By design, it's not as aggressive as perltidy, but it's still very useful. It can be configured and will do all the php files in your project as a batch. Update: for a more aggressive, standards-based tool, consider PHP CS Fixer: <https://...
Automatically reformatting inherited PHP spaghetti code
[ "", "php", "code-formatting", "" ]