Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions. What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc. This is a winforms app and I have users around the world.
There are 2 big issues your design has to be sure to address 1. Privacy (what Don alluded to) - You must be crystal clear what information you are collecting and sending up to your central server, ideally the users should be able to inspect the exact data you are sending back to the central server (if they wish to) - ...
Try doing a google scholar search. There are some interesting ideas by Ben Liblit and co-authors, and another series of ideas by Alex Orso and co-authors (disclaimer - I'm one of Alex Orso's co-authors) based on taking a sample of runtime information from each user, and putting it together in an interesting way. <http...
lightweight instrumentation for winforms app
[ "", "c#", "winforms", "instrumentation", "" ]
In Python compiled regex patterns [have a `findall` method](http://docs.python.org/library/re.html#re.findall) that does the following: > Return all non-overlapping matches of > pattern in string, as a list of > strings. The string is scanned > left-to-right, and matches are > returned in the order found. If one or > ...
Use the `/g` modifier in your match. From the `perlop` manual: > The "`/g`" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the ...
To build on Chris' response, it's probably most relevant to encase the `//g` regex in a `while` loop, like: ``` my @matches; while ( 'foobarbaz' =~ m/([aeiou])/g ) { push @matches, $1; } ``` Pasting some quick Python I/O: ``` >>> import re >>> re.findall(r'([aeiou])([nrs])','I had a sandwich for lunch') [('a', '...
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?
[ "", "python", "regex", "perl", "iterator", "" ]
What's the easiest way to shuffle an array with python?
``` import random random.shuffle(array) ```
``` import random random.shuffle(array) ```
Shuffle an array with python, randomize array item order with python
[ "", "python", "arrays", "random", "shuffle", "" ]
Lately I've found myself constantly running ILDASM to study the MSIL output of my programs. Are there any utilities to streamline this? Ideally, it would be nice to select some source code and have it compile, disassemble and emit the selected C# code in MSIL. Anyone know of such a thing?
[.NET Reflector](http://www.red-gate.com/products/reflector/) I think that [RedGate](http://www.red-gate.com/) have bought the IP to this tool now. I'm fairly sure that there is a VS plugin which integrates to it to allow you to run this from vs. [.Net Reflector Plugin](http://www.testdriven.net/reflector/) [![alt te...
You could use [testdriven.net](http://www.testdriven.net/) an awesome unit testing plugin that gives you the ability to right click on any member and view it in reflector.
Is there a tool to select some code in Visual Studio and have it show the corresponding MSIL?
[ "", "c#", ".net", "visual-studio", "cil", "" ]
I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application. I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying "The file name, directory name, or volume label syntax is incorrect." As a point...
The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to ``` xr.parse( new InputSource( filename )); ``` works just fine.
Looks like you want to use `java.lang.Class.getResourceAsStream(String)`, see <https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String->
How do I read a resource file from a Java jar file?
[ "", "java", "jar", "resources", "" ]
I have a couple of tables in a SQL 2008 server that I need to generate unique ID's for. I have looked at the "identity" column but the ID's really need to be unique and shared between all the tables. So if I have say (5) five tables of the flavour "asset infrastructure" and I want to run with a unique ID between them ...
Why not use a GUID?
The simplest solution is to set your identity seeds and increment on each table so they never overlap. Table 1: Seed 1, Increment 5 Table 2: Seed 2, Increment 5 Table 3: Seed 3, Increment 5 Table 4: Seed 4, Increment 5 Table 5: Seed 5, Increment 5 The identity column mod 5 will tell you which table the record is in. Y...
Generate unique ID to share with multiple tables SQL 2008
[ "", "sql", "stored-procedures", "" ]
How can I access dynamically properties from a generated LINQ class ? Cause I would like to be able to customize the displayed table columns where Partner is the LINQ Class generated from a SQL Server Database Table. ``` <table class="grid"> <thead> <tr> <% foreach (Column c in (IEnumerable)ViewData["column...
Reflection is a pretty good fit here, but really - everything is known at compile time. So it's possible to specify everything at design time. ``` public class DataItem { string Title {get;set;} object Value {get;set;} } public interface IDataItems { IEnumerable<DataItem> Items() } //suppose LINQ gives you th...
Reflection should provide what you want - in particular, ``` typeof(Partner).GetProperty(c.Name).GetValue(p, null) ``` However, you might want to do this *before* the loop: ``` var columns = (IEnumerable<string>)ViewData["columns"]; var cols = columns.Select(colName => typeof(Partner).GetProperty(colName)).ToL...
dynamic property access for generated LINQ Classes
[ "", "c#", "asp.net-mvc", "linq", "" ]
Please consider the following scenario: ``` map(T,S*) & GetMap(); //Forward decleration map(T, S*) T2pS = GetMap(); for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it) { if(it->second != NULL) { delete it->second; it->second = NULL; } T2pS.erase(it); //In VS2005, a...
Yes, if you erase an iterator, that iterator gets a so-called *singular value*, which means it doesn't belong to any container anymore. You can't increment, decrement or read it out/write to it anymore. The correct way to do that loop is: ``` for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it+...
After you call `erase` on an iterator into a `std::map`, it is invalidated. This means that you cannot use it. Attempting to use it (e.g. by incrementing it) is invalid and can cause anything to happen (including a crash). For a `std::map`, calling `erase` on an iterator does not invalidate any other iterator so (for e...
What happens to an STL iterator after erasing it in VS, UNIX/Linux?
[ "", "c++", "linux", "visual-studio-2005", "stl", "dictionary", "" ]
I would like to embed a text file in an assembly so that I can load the text without having to read it from disk, and so that everything I need is contained within the exe. (So that it's more portable) Is there a way to do this? I assume something with the resource files? And if you can, how do you do it and how do y...
Right-click the project file, select Properties. In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource. ![enter image description here](https://i.stack.imgur.com/atzRt.png) Then from the toolbar above the tab-page, select t...
In Visual Studio 2003, Visual Studio 2005 and possibly earlier versions (this works in 2008 as well) you can include the text file in your project, then in the 'Properties' panel, set the action to 'Embedded Resource'. Then you can access the file as a stream using `Assembly.GetManifestResourceStream(string)`. Other a...
How to embed a text file in a .NET assembly?
[ "", "c#", ".net", "embedded-resource", "" ]
I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754). So I could take a number, and end up with a int num[16] array with the binary value of the float: num[0] would be 1 num[1] would be 1 num[2] would be 0 num[3] ...
Use union and bitset: ``` #include <iostream> #include <bitset> #include <climits> int main() { union { float input; // assumes sizeof(float) == sizeof(int) int output; } data; data.input = 2.25125; std::bitset<sizeof(float) * CHAR_BIT> bits(data.output); std::cout << bits ...
``` int fl = *(int*)&floatVar; //assuming sizeof(int) = sizeof(float) int binaryRepresentation[sizeof(float) * 8]; for (int i = 0; i < sizeof(float) * 8; ++i) binaryRepresentation[i] = ((1 << i) & fl) != 0 ? 1 : 0; ``` ## Explanation `(1 << i)` shifts the value `1`, `i` bits to the left. The `&` operator comput...
Floating Point to Binary Value(C++)
[ "", "c++", "binary", "floating-point", "ieee-754", "" ]
What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python — especially with respect to when I would want to use it, and when not?
> # In Python, what is the purpose of `__slots__` and what are the cases one should avoid this? ## TLDR: The special attribute [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) allows you to explicitly state which instance attributes you expect your object instances to have, with the expected re...
Quoting [Jacob Hallen](http://code.activestate.com/lists/python-list/531365/): > The proper use of `__slots__` is to save space in objects. Instead of having > a dynamic dict that allows adding attributes to objects at anytime, > there is a static structure which does not allow additions after creation. > [This use of...
Usage of __slots__?
[ "", "python", "oop", "python-internals", "slots", "" ]
I want to generate a dict with the letters of the alphabet as the keys, something like ``` letter_count = {'a': 0, 'b': 0, 'c': 0} ``` what would be a fast way of generating that dict, rather than me having to type it in?
I find this solution elegant: ``` import string d = dict.fromkeys(string.ascii_lowercase, 0) print(d) # {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0} ```
``` import string letter_count = dict(zip(string.ascii_lowercase, [0]*26)) print(letter_count) # {'a': 0, 'b': 0, 'c': 0, ... 'x': 0, 'y': 0, 'z': 0} ``` or maybe: ``` import string import itertools letter_count = dict(zip(string.ascii_lowercase, itertools.repeat(0))) print(letter_count) # {'a': 0, 'b': 0, 'c': 0, ...
Is there a fast way to generate a dict of the alphabet in Python?
[ "", "python", "dictionary", "alphabet", "" ]
How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#? I'm trying to generate a string of digits that can add together to be N.
I'm not sure what the statistics are on this but, the issue here is that you don't want to randomly select a number that makes it impossible to sum N with M number of entries either by overshooting or undershooting. Here's how I would do it: ``` static void Main() { int count = 30; int[] numbers = getNumbers(c...
The problem is we want all numbers to be bounded 1-9 **and** add up to N. So we have to generate each number one by one and determine the real bounds for the next number. This will of course generate statistical bias toward the end of the list, so I recommend shuffling the array once after generating. To determine th...
Generate a series of random numbers that add up to N in c#
[ "", "c#", ".net", "random", "" ]
Is there a way to use the `new` keyword to allocate on the stack (ala `alloca`) instead of heap (`malloc`) ? I know I could hack up my own but I'd rather not.
To allocate on the stack, either declare your object as a local variable *by value*, or you can actually use alloca to obtain a pointer and then use the in-place new operator: ``` void *p = alloca(sizeof(Whatever)); new (p) Whatever(constructorArguments); ``` However, while using alloca and in-place new ensures that ...
Jeffrey Hantin is quite correct that you can use placement new to create it on the stack with alloca. But, seriously, why?! Instead, just do: ``` class C { /* ... */ }; void func() { C var; C *ptr = &var; // do whatever with ptr } ``` You now have a pointer to an object allocated on the stack. And, it'l...
new on stack instead of heap (like alloca vs malloc)
[ "", "c++", "stack", "new-operator", "" ]
I'm currently writing a quick solution for Euler Problem #4 where one must find the largest palindromic number from the product of two 3-digit numbers. To identify if a number is palindromic, you would obviously compare a reverse of the number with the original. **Since C# doesn't have a built in String.Reverse() met...
I think it might be faster to do the comparison in-place. If you reverse the string, you've got to: 1. Instantiate a new string object (or StringBuffer object) 2. Copy the data (in reverse) from the first string to the new string 3. Do your comparison. If you perform the comparison in place, you do only the last step...
Wouldn't reversing the number be faster? ``` // unchecked code, don't kill me if it doesn't even compile. ulong Reverse(ulong number) { ulong result = 0; while (number > 0) { ulong digit = number % 10; result = result * 10 + digit; number /= 10; } return result; } ```
Quickest Method to Reverse in String in C#.net
[ "", "c#", "" ]
I have a question concerning this code which I want to run on QNX: ``` class ConcreteThread : public Thread { public: ConcreteThread(int test) { testNumber = test; } void *start_routine() { for(int i = 0; i < 10; i++) { sleep(1); cout << testNumber...
Note 1: If you only have 1 processor the code can only be done sequentially no matter how many threads you create. Each thread is given a slice of processor time before it is swapped out for the next threads. Note 2: If the main thread exits pthreads will kill all child threads before they have a chance to execute. N...
Try to make the pthread\_t id a class member instead of a function local variable. That way the caller can pthread\_join it. Not doing this is technically a resource leak (unless the thread is specifically not joinable). And joining will avoid the issue that [Martin York](https://stackoverflow.com/questions/433220/qnx...
QNX c++ thread question
[ "", "c++", "multithreading", "qnx", "" ]
We are getting this error on starting tomcat (both as a service and via command line): ``` This release of Apache Tomcat was packaged to run on J2SE 5.0 or later. It can be run on earlier JVMs by downloading and installing a compatibility package from the Apache Tomcat binary download page. ``` We have the version wi...
You only have the exe version and not the bat files, because you've downloaded the Windows Installer and not the zip file. The bat files are only included in the zip file. You can download the zip and copy the bat files to the bin directory. No need to uninstall. I bet that you have a PATH problem. Check if there is a...
You can configure a different version of Java in the start.bat file. The same goes for the service (but in a different place). I suggest to add an `echo %JAVA_HOME%` (if you use the start.bat) to see what is really happening. If you use the service, open the properties for the service (use the icon tomcat puts in the...
tomcat error - "This release of Apache Tomcat was packaged to run on J2SE 5.0"
[ "", "java", "tomcat", "" ]
I've been struggling with this for the past couple hours now and I really don't know what could be wrong. I'm simply trying to get Javascript to communicate text with Flash. I found this great example with this source <http://blog.circlecube.com/wp-content/uploads/2008/02/ActionscriptJavascriptCommunication.zip> I ra...
I do not see a call to the allowDomain function in your code. With out that the security sandbox will not allow your flash application to communicate with flash and vice versa on the server. Add a call to `System.security.allowDomain("mydomain.com", "mySecondDomain.com", "etc.com")` for every domain the flash app will ...
It probably doesn't have to do with Google app engine per se, since the whole thing's running in the browser -- unless there's some sort of server dependency somewhere you haven't mentioned. Assuming that's not the case... If you're able to get Flash to call into JavaScript with ExternalInterface.call(), but not JavaS...
Problem with Flash ExternalInterface on Google App Engine
[ "", "javascript", "flash", "google-app-engine", "" ]
In firefox, I have the following fragment in my .css file ``` tree (negative){ font-size: 120%; color: green;} ``` Using javascript, how do I change the **rule**, to set the color to red? **NOTE: I do not want to change the element. I want to change the rule. Please do not answer with something like** ... ele...
What you're looking for is the `document.styleSheets` property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE. For example, try pasting the following in FF for this page and pressing enter: ``` javascript:alert(doc...
``` function changeCSSRule (stylesheetID, selectorName, replacementRules) { var i, theStylesheet = document.getElementById(stylesheetID).sheet, thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules; for(i=0; i < thecss.length; i++){ if(thecss[i].selectorText == selectorNam...
In firefox, how can I change an existing CSS rule
[ "", "javascript", "css", "firefox", "" ]
This is easy for non-inlines. Just override the following in the your admin.py AdminOptions: ``` def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'photo': kwargs['widget'] = AdminImageWidget() return db_field.formfield(**kwargs) return super(NewsOptions,self).formfield_f...
It works exactly the same way. The TabularInline and StackedInline classes also have a formfield\_for\_dbfield method, and you override it the same way in your subclass.
Since Django 1.1, formfield\_overrides is also working ``` formfield_overrides = { models.ImageField: {'widget': AdminImageWidget}, } ```
How do I add a custom inline admin widget in Django?
[ "", "python", "django", "django-admin", "" ]
I am working on an application that will be used as an extensible framework for other applications. One of the fundamental classes is called Node, and Nodes have Content. The SQL tables look like this: TABLE Node ( NodeId int, .... etc ) TABLE NodeContentRelationship ( NodeId int, ContentType string, ContentId int) ...
Why is it impossible to set `NoteContentRelationship.ContentId` as a foreign key? You can easily use a relational inheritance model with a table `Content` representing an abstract base class, and various tables `AnimalContent`, `CarContent`, etc. representing derived classes.
Beware the [Inner Platform Effect](http://thedailywtf.com/Articles/The_Inner-Platform_Effect.aspx). If you're trying to build an 'extensible framework' which allows developers to store data of different 'content types' and relate them to each other in a generic fashion, you may find that others have already [solved](h...
SQL : one foreign key references primary key in one of several tables
[ "", "sql", "database", "foreign-keys", "relationship", "" ]
I have a very large Ruby on Rails application that I would like to port to PHP 5.2 or maybe PHP 5.3 (if 5.3 ever gets released). I've been looking for a some way of automatically converting the simple stuff like simple classes and the ERB templates. I would expect that I'd have to do the more complicated stuff myself ...
I completely agree with troelskn, this is a massive undertaking and I think that you'll have very little luck finding any form of automated process for porting the app. Your best bet is finding a framework that is very similar in design and porting all the classes one by one. The most tedious thing here will be where...
It's a non-trivial effort to port applications between any two languages. In this case, it's even worse, because of the dissimilarities between php and ruby. You can't hope to get any kind of automated process for this. If you need to do this (And the *why* is a different story on its own), you could try to use one of...
Port a Ruby/Rails application to PHP 5
[ "", "php", "ruby", "" ]
I want every cell in each row except the last in each row. I tried: ``` $("table tr td:not(:last)") ``` but that seems to have given me every cell except the very last in the table. Not quite what I want. I'm sure this is simple but I'm still wrapping my head around the selectors.
Try: ``` $('table tr td:not(:last-child)') ```
You could try ``` $("table td:not(:last-child)") ``` or ``` $("table td:not(:nth-child(n))") ``` where n is 1-based index of a child element or ``` $("table td").not(":last-child") ```
jQuery: how to select every cell in a table except the last in each row?
[ "", "javascript", "jquery", "" ]
As prescribed by Yahoo!, gzip'ng files would make your websites load faster. The problem? I don't know how :p
<http://www.webcodingtech.com/php/gzip-compression.php> Or if you have Apache, try <http://www.askapache.com/htaccess/apache-speed-compression.html> Some hosting services have an option in the control panel. It's not always possible, though, so if you're having difficulty, post back with more details about your platf...
If you are running Java Tomcat then you set a few properties on your Connector ( in conf/server.xml ). Specifically you set: 1. compressableMimeType ( what types to compress )- compression ( off | on | )- noCompressionUserAgents ( if you don't want certain agents to receive gzip, list them here ) Here's the tomcat d...
How do I gzip my web files
[ "", "php", ".htaccess", "" ]
I was debugging something and discovered some strangeness in JavaScript: ``` alert(1=='') ==> false alert(0=='') ==> true alert(-1=='') ==> false ``` It would make sense that an implied string comparison that 0 should = '0'. This is true for all non-zero values, but why not for zero?
According to the Mozilla documentation on [Javascript Comparison Operators](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators) > If the two operands are not of the same type, JavaScript converts the > operands then applies strict > comparison. If either operand is a > number...
When javascript does implicit type conversions, the empty string literal will match the 0 integer. Do your comparison like this and you'll get your expected result: ``` alert(1==='') ==> false alert(0==='') ==> false alert(-1==='') ==> false ```
Implied string comparison, 0=='', but 1=='1'
[ "", "javascript", "" ]
I'm working with PyGTK, trying to come up with a combination of widgets that will do the following: * Let me add an endless number of widgets in a column * Provide a vertical scrollbar to get to the ones that run off the bottom * Make the widgets' width adjust to fill available horizontal space when the window is resi...
* An endless number of widgets in a column: Sounds like a GtkVBox. * Vertical scrollbar: Put your VBox in a GtkScrolledWindow. * Horizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to mostly handle this (You wi...
What Steve said in code: ``` vbox = gtk.VBox() vbox.pack_start(widget1, 1, 1) ## fill and expand vbox.pack_start(widget2, 1, 1) ## fill and expand vbox.pack_start(widget3, 1, 1) ## fill and expand swin = gtk.ScrolledWindow() swin.add_with_viewport(vbox) ```
Which GTK widget combination to use for scrollable column of widgets?
[ "", "python", "gtk", "pygtk", "widget", "" ]
I have a windows service that has a custom configuration section. In the configSectionHandler class I am using attributes on the properties to validate the settings like this: ``` //ProcessingSleepTime Property [ConfigurationProperty("ProcessingSleepTime", DefaultValue = 1000, IsRequired = false)] [Integer...
Or better yet (as you might need multiple such a properties), using the code from @Ricardo Villiamil, create: ``` int GetIntFromConfigSetting(string settingName, int defaultValue) { int retValue = defaultValue; if(this.ContainsKey(settingName)) { int sleepInterval; if(Int32.TryParse(this[settingNa...
Ok I think I have it. In my service I have code that looks like this in the constructor: config = ConfigurationManager.GetSection("MyCustomConfigSection") as MyCustomConfigSectionHandler; This is where the error is thrown. I can catch the error and log it. The error must be rethrown in order to prevent the service fr...
How/Where to handle ConfigurationErrorsException in a windows service?
[ "", "c#", "windows-services", "configuration-files", "" ]
I'm dealing with an Oracle DBA at the moment, who has sent me some profiling he's done. One of the terms in his report is 'Buffer Gets', any idea what this actually means? My guess is bytes retrieved from a buffer, but I have no idea really. Here is some sample output: ``` Buffer Gets Executions Gets per Exec %...
Oracle storage is arranged into blocks of a given size (e.g. 8k). Tables and indexes are made up of a series of blocks on the disk. When these blocks are in memory they occupy a buffer. When Oracle requires a block it does a **buffer get**. First it checks to see if it already has the block it needs in memory. If so, ...
Just to answer one part of your question that WW didn't: "Gets per Exec" is simply the gets divided by the number of executions of the statement. You might have a statement that is very efficient but executed many times; this would have a high number of total buffer gets but a low gets per exec ratio.
In Oracle what does 'Buffer Gets' actually refer to?
[ "", "sql", "oracle", "" ]
In the application that I am working on, the logging facility makes use of `sprintf` to format the text that gets written to file. So, something like: ``` char buffer[512]; sprintf(buffer, ... ); ``` This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer. ...
No you can't use `sprintf()` to allocate enough memory. Alternatives include: * use `snprintf()` to truncate the message - does not fully resolve your problem, but prevent the buffer overflow issue * double (or triple or ...) the buffer - unless you're in a constrained environment * use C++ `std::string` and `ostrings...
You can use asprintf(3) (note: non-standard) which allocates the buffer for you so you don't need to pre-allocate it.
Using sprintf without a manually allocated buffer
[ "", "c++", "c", "string", "memory", "" ]
When using `call_user_func_array()` I want to pass a parameter by reference. How would I do this. For example ``` function toBeCalled( &$parameter ) { //...Do Something... } $changingVar = 'passThis'; $parameters = array( $changingVar ); call_user_func_array( 'toBeCalled', $parameters ); ```
To pass by reference using `call_user_func_array()`, the parameter in the array must be a reference - it does not depend on the function definition whether or not it is passed by reference. For example, this would work: ``` function toBeCalled( &$parameter ) { //...Do Something... } $changingVar = 'passThis'; $pa...
Directly, it may be impossible -- however, if you have control both over the function you are implementing *and* of the code that *calls* it - then there is one work-around that you *might* find suitable. Would you be okay with having to embed the variable in question into an object? The code would look (somewhat) lik...
Is it possible to pass parameters by reference using call_user_func_array()?
[ "", "php", "reference", "callback", "" ]
I am working on refactoring some old code and have found few structs containing zero length arrays (below). Warnings depressed by pragma, of course, but I've failed to create by "new" structures containing such structures (error 2233). Array 'byData' used as pointer, but why not to use pointer instead? or array of leng...
Yes this is a C-Hack. To create an array of any length: ``` struct someData* mallocSomeData(int size) { struct someData* result = (struct someData*)malloc(sizeof(struct someData) + size * sizeof(BYTE)); if (result) { result->nData = size; } return result; } ``` Now you have an object of some...
There are, unfortunately, several reasons why you would declare a zero length array at the end of a structure. It essentially gives you the ability to have a variable length structure returned from an API. Raymond Chen did an excellent blog post on the subject. I suggest you take a look at this post because it likely ...
Array of zero length
[ "", "c++", "arrays", "visual-c++", "flexible-array-member", "" ]
I've run into a really strange bug, that I'm hoping someone can explain. I have a simple `std::vector<V3x>`, where `V3x` is a 3d vector (the linear algebra kind.) The following code causes a `std::length_error` exception to be thrown: ``` std::vector<V3x> vertices; int vertexCount = computeVertexCount(); vertices.resi...
The value 3435973836 is significant. In hex, that's 0xcccccccc. That's the value assigned to local variables in Debug mode by the stack frame initialization code. When you see it back while debugging, you'd say "ah, variable not initialized". Maybe that gets you a bit closer to solving this. You mention DLL. That's re...
Whenever a parameter or local variable changes unexpectedly, there's a good chance it's due to stack corruption. This can occur whenever you use an uninitialized local variable or store data beyond the memory allocated to a local string or array. A simple way to debug this: 1. Load your program into a debugger. 2. In...
C++ Parameter's Value Changes Between Stack Frames in std::vector
[ "", "c++", "debugging", "memory", "parameters", "vector", "" ]
Is there a way to initialize all elements of an array to a constant value through generics?
I would use an extender (.net 3.5 feature) ``` public static class Extenders { public static T[] FillWith<T>( this T[] array, T value ) { for(int i = 0; i < array.Length; i++) { array[i] = value; } return array; } } // now you can do this... int[] array = new in...
Personally, I would use a good, old for loop, but if you want a one-liner, here it is: ``` T[] array = Enumerable.Repeat(yourConstValue, 100).ToArray(); ```
How to initialize an array through generics?
[ "", "c#", "generics", "" ]
*LIKE* operator in MySql is used to find rows that contain our query text, for example: ``` select name from user where name like "%john%" ``` which will return `John Smith`, `Peter Johnson` etc. What if I need the opposite - to find rows that are *CONTAINED* in our query text? For example I give it `John Smith and ...
Here's a way you can achieve what you describe: ``` SELECT name FROM user WHERE 'John Smith and Peter Johnson are best friends' LIKE CONCAT('%', name, '%') ```
``` select name from users where instr('John Smith and Peter Johnson', name) > 0 ``` I would rather use this method instead of: ``` select * from users WHERE 'John Smith and Peter Johnson' LIKE CONCAT('%', name ,'%') ``` because if there is any chance that the `name` could contain the `%` or `_` character (eg. name...
MySQL: What is a reverse version of LIKE?
[ "", "sql", "mysql", "" ]
There's no strongly typed View() method to return an ActionResult. So, suppose I have ``` class Edit : ViewPage<Frob> ``` In my FrobController, I will do something like "return View("Edit", someFrob);". There's no checking going on here, so I have to always manually synchronize the view and controller's use of it. Th...
The first problem I see is that you've now made your Controller aware of the View. That's a line you should never cross.
Take a look at this example: <http://oddiandeveloper.blogspot.com/2008/11/strongly-typed-view-names.html> You can call yout View like this: ``` return View(typeof(Views.en.Home.about), AboutModel); ```
Strongly typing ASP.NET Controller.View() method for model type
[ "", "c#", "asp.net-mvc", "" ]
I've been thinking about using extension methods as a replacement for an abstract base class. The extension methods can provide default functionality, and can be 'overridden' by putting a method of the same signature in a derived class. Any reason I shouldn't do this? Also, if I have two extension methods with the sa...
I agree with Michael. Base classes should contain all base functionality Extension methods should, obviously, extend the base functionality. In dynamic languages like Ruby it is often typical to use extension methods to provide addition functionality instead of using subclasses. Basically, extension methods are there t...
In general, you shouldn't provide "base" functionality through extension methods. They should only be used to "extend" class functionality. If you have access to the base class code, and the functionality you're trying to implement is logically part of the inheritance heirarchy, then you should put it in the abstract c...
Overriding Extension Methods
[ "", "c#", "" ]
So I was thinking one way that you can bring method chaining into PHP with the built-in global functions would be to "borrow" the |> (pipe) operator from F#. It would pipe the results on the left into the first parameter of the function on the right. Of course PHP would have to revisit the parameter order of some of th...
It looks like what he wants is a String class with methods that mirror the builtin functions. This is a guess, but maybe you could use the \_\_call magic method to do the work like this: **(untested)** ``` class String { private $_value = ''; public function __construct($value) { $_value = $value; } ...
Something much like that can be accomplished using fluent object methods. For example: ``` class Foo { public function bar() { echo 'Hello<br/>'; return $this; } public function bar2() { echo 'Goodbye<br/>'; return $this; } } $foo = new Foo(); $foo->bar()-...
Good or Bad? Bring "Function Chaining" Capabilities to PHP
[ "", "php", "language-features", "" ]
``` #include<iostream> class name { public: int a; name():a(0){}; }; void add(name * pname) { pname = NULL; } int main() { name varName(); name * pName = new name(); add(pName); add(&varName);//error C2664: 'add' : cannot convert parameter 1 from 'name __cdecl *)(void)' to 'name *' } ```
I think it's worth telling you about a similar problem, that also causes trouble: ``` struct foo { }; struct bar { bar(foo f); }; int main() { // does *not* create a bar object initialized by a default constructed // foo object. bar b(foo()); } ``` What b really is is a function that returns a `bar` and takes...
The error is on the first line of the main function: ``` name varName(); ``` You are **not** creating an instance of class *name* with the default constructor, you are actually declaring a new function called *varName*, with no parameters, which returns a *name* instance. You should instead write: ``` name varName;...
Is this' type variableofType()' function or object?
[ "", "c++", "function", "pointers", "" ]
I've got ~20 columns in a grid each of which can be shown or hidden via a checkbox in another dialog. The visibility state of any given column will be stored inside an XML file which is accessed via an Options class. I'm trying to decide how best to represent those Boolean visibility values inside the Options class. ...
The way I elected to do it was to create an Enum with an entry for each column combined with a Dictionary to hold the visibility state and a property exposing each column value. This makes it easy to store and retrieve the column values from my XML file (just enumerate through the Enum storing/retrieving the desired v...
If it's the only property you need to store for the columns, you could use a single string where 1 means the column is visible and 0 hidden. <Columns Visible="00001011110111010101" />
What is the best way to store configuration values for several dozen columns?
[ "", "c#", ".net", "" ]
What is the current status of TagLib# (TagLib sharp)? The official homepage www.taglib-sharp.com (link removed due to the NSFW nature of the new site that's parked at that address. -BtL) doesn't exist anymore! I've found the project on [ohloh](http://www.ohloh.net/p/5598) where the old homepage is still linked. Also ...
The page at Novell (<http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html>) is no longer updated. The source code is now hosted at <https://github.com/mono/taglib-sharp> and the best way to install and use the latest version is using NuGet. Open the Package Manager Console in Visual Studio and t...
Looks like it moved here: <http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html>
What happened to the "TagLib#" library?
[ "", "c#", "mp3", "id3", "taglib-sharp", "" ]
Is there a way in Python to override a class method at instance level? For example: ``` class Dog: def bark(self): print "WOOF" boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!! ```
Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class. You cannot debug monkeypatched code. When you find a bug in `boby` and `print type(boby)`, you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a n...
Yes, it's possible: ``` class Dog: def bark(self): print "Woof" def new_bark(self): print "Woof Woof" foo = Dog() funcType = type(Dog.bark) # "Woof" foo.bark() # replace bark with new_bark for this object only foo.bark = funcType(new_bark, foo, Dog) foo.bark() # "Woof Woof" ```
Override a method at instance level
[ "", "python", "" ]
I have a table where each row has a few fields that have ID's that relate to some other data from some other tables. Let's say it's called `people`, and each person has the ID of a `city`, `state` and `country`. So there will be three more tables, `cities`, `states` and `countries` where each has an ID and a name. W...
Assuming the following tables: ``` create table People ( ID int not null primary key auto_increment ,FullName varchar(255) not null ,StateID int ,CountryID int ,CityID int ) ; create table States ( ID int not null primary key auto_increment ,Name varcha...
JOINS are the only way to really do this. You might be able to change your schema, but the problem will be the same regardless. (A City is always in a State, which is always in a Country - so the Person could just have a reference to the city\_id rather than all three. You still need to join the 3 tables though).
What's the best way to get related data from their ID's in a single query?
[ "", "sql", "mysql", "join", "relational", "" ]
I'm looking for a portable and easy-to-use string library for C/C++, which helps me to work with Unicode input/output. In the best case, it will store its strings in memory in UTF-8, and allow me to convert strings from ASCII to UTF-8/UTF-16 and back. I don't need much more besides that (ok, a liberal license won't hur...
[UTF8-CPP](https://github.com/nemtrif/utfcpp) seems to be exactly what you want.
I'd recommend that you look at the [GNU iconv](http://www.gnu.org/software/libiconv/) library.
Portable and simple unicode string library for C/C++?
[ "", "c++", "c", "unicode", "" ]
I've got a multidimensional associative array which includes an elements like ``` $data["status"] $data["response"]["url"] $data["entry"]["0"]["text"] ``` I've got a strings like: ``` $string = 'data["status"]'; $string = 'data["response"]["url"]'; $string = 'data["entry"]["0"]["text"]'; ``` How can I convert the s...
Quick and dirty: ``` echo eval('return $'. $string . ';'); ``` Of course the input string would need to be be sanitized first. If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe. It does, however, make assumptions about the string format: ``` <?php $...
PHP's [variable variables](https://www.php.net/language.variables.variable) will help you out here. You can use them by prefixing the variable with another dollar sign: ``` $foo = "Hello, world!"; $bar = "foo"; echo $$bar; // outputs "Hello, world!" ```
Convert a String to Variable
[ "", "php", "arrays", "string", "variables", "" ]
This always forces us to return a single parameter in case I need to return multiple, say a List and a String. This restriction is not there in function arguments.
This problem is what functional languages such as F#, haskell etc. attempt to address. The problem is that in hardware, a function's return value was originally returned via a CPU register, so you could only return a single value. C syntax passed on this legacy and C++ (and C#, Java) also inherited this.
In fact, some languages do what you exactly want. For example Python, look at this code. It returns 2 values: 1 string and another int. ``` >>> def myFunc(): ... string_val = "techmaddy" ... int_val = 10 ... return string_val, int_val ... >>> >>> s, i = myFunc() >>> >>> print s techmaddy >>> >>> print i 10 ``` ...
why do functions dont have parameterized return types, as it has parameterized input?
[ "", "java", "function", "return-type", "" ]
How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)? For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like: ``` somefunction("self.post.id") = |Value of self.post.id| ```
As referenced in Stack Overflow question *[Inplace substitution from ConfigParser](https://stackoverflow.com/questions/295028/)*, you're looking for `eval()`: ``` print eval('self.post.id') # Prints the value of self.post.id ```
Note: do **not** use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering: ``` __import__("os").system("Some nasty command like rm -rf /*") ``` as the argument. Better is to limit to well-define...
Convert a string to preexisting variable names
[ "", "python", "" ]
Is it possible to get the value from the first page to the second page, BUT without `FORM`? Shall we use ``` window.parent.document.getElementById("").value.. ``` But this is working in `popup` window, but I need this for between two pages which redirecting from the first page to the second page.
If you are redirecting from one page to another, you MUST use form elements to pass from page to page or use a querystring value. That is it, Javascript does NOT have any knowledge of the structure of the previous page..
or you can use cookies...
Get the value from one window to another window - JavaScript
[ "", "javascript", "" ]
**My goal is to get Limewire(JAVA) and Songbird(XULRunner) to run together.** I was thinking the best way is to run the XUL application(songbird) inside a JAVA swing panel. Is there another way? Would it be better or possible to have the GUI entirely in XUL, and then access my JAVA objects somehow? How would I go ab...
Take a look at [JRex](http://jrex.mozdev.org/), as it might let you peek into a couple of ideas. Other than that, I'd also research about [Rhinohide](http://zelea.com/project/textbender/o/rhinohide/description.xht) as well.
Take a look at [DJ Native Swing](http://djproject.sourceforge.net/ns/ "DJ Native Swing"), a native Swing implementation using SWT and Xulrunner.
Embedding XULRunner application on Java
[ "", "java", "embed", "xul", "xulrunner", "" ]
What XML libraries are out there, which are minimal, easy to use, come with little dependencies (ideally none), can be linked statically and come with a liberal license? So far, I've been a pretty happy user of [TinyXML](http://www.grinninglizard.com/tinyxml/), but I'm curious what alternatives I have missed so far.
I recommend [rapidxml](http://rapidxml.sourceforge.net/). It's an order of magnitude smaller than tinyxml, and doesn't choke on doctypes like tinyxml does. If you need entity support or anything advanced, forget about static linking and use expat or libxml2.
[expat](http://expat.sourceforge.net/) is a very fast C XML parser (although a C++ wrapper exists) that's widely used in many open-source projects. If I remember correctly, it has very few dependencies, and it's licensed under the very liberal MIT License.
Minimal XML library for C++?
[ "", "c++", "c", "xml", "" ]
I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two. My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.). Is there a relatively easy way to have the COM object pass an array to the caller? For example, I want to ...
Try passing a safearray variant to the COM Object. Something like this to put a BYTE array inside a safearray variant.... ``` bool ArrayToVariant(CArray<BYTE, BYTE>& array, VARIANT& vtResult) { SAFEARRAY FAR* psarray; SAFEARRAYBOUND sabounds[1]; sabounds[0].lLbound=0; sabounds[0].cElements = (ULONG)array.GetSize();...
SAFEARRAYs are the way to go if you want OLE-Automation compliance, and maybe use the COM interface from other languages such as VB6. But there is an alternative in IDL, for example: - ``` void Fx([in] long cItems, [in, size_is(cItems)] BYTE aItems[]); ``` This describes a method where the marshalling code can infer ...
Passing an array using COM?
[ "", "c++", "com", "" ]
I want to develop ASP.NET C# based MMOG (Massively multiplayer online game). I would be using ASP.NET Ajax control kit, jquery and MS SQL server 2005. Q.1)How feasible .NET 3.5, ASP.NET with C# in handling thousands of users simultaneously. I would also incorporate ASP.NET ajax based chatting system with chat rooms a...
ASP.NET and MSSQL 2005 definitely have no "built in" scaling problems. You will have to take care to build you application right and be prepared to dish out some money for proper hardware. See for example the [hardware setup](https://blog.stackoverflow.com/2009/01/new-stack-overflow-server-glamour-shots/) that is sche...
1. ASP.NET can handle it with the proper server configuration, hardware, and performance considerations when creating the application. 2. I tried to do some googling and didn't find anything right away, but I'm sure that there are some out there. 3. For the chat piece you might look at a product such as CuteChat that a...
Feasibility of ASP.NET based MMOG
[ "", "c#", "asp.net", "asp.net-ajax", "chat", "" ]
I've got the following piece of code in an aspx webpage: ``` Response.Redirect("/Someurl/"); ``` I also want to send a different referrer with the redirect something like: ``` Response.Redirect("/Someurl/", "/previousurl/?message=hello"); ``` Is this possible in Asp.net or is the referrer handled solely by the brow...
Referrer is readonly and meant to be that way. I do not know why you need that but you can send query variables as instead of ``` Response.Redirect("/Someurl/"); ``` you can call ``` Response.Redirect("/Someurl/?message=hello"); ``` and get what you need there, if that helps.
`Response.Redirect` sends an answer code (HTTP 302) to the browser which in turn issues a new request (at least this is the expected behavior). Another possibility is to use `Server.Transfer` (see [here](http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx)) which doesn't go back to the br...
Response.Redirect with Different Referrer
[ "", "c#", "asp.net", "response.redirect", "referrer", "referer", "" ]
Sometimes the overhead of creating a new model type is annoying. In these cases, I want to set ViewData, and the options seem to be: 1. Simply set viewdata with a string key, and cast it out. This has obvious problems. 2. Store the identifier (string key) somewhere (where? on the controller?) and cast it out on the vi...
I think this is what the model does in the MVC pattern. Why you don't use a typed view instead? I believe you just make things more complicated by introducing yet another dependency between the controller and the view. I don't see any specific benefit in terms of line of code or something like that. You have to declar...
One idea would be to create tuples for a strongly typed view in cases where you don't want to create a specific view model class: ``` class SimpleModel<T> class SimpleModel<T, U> class SimpleModel<T, U, V> ``` Then make a strongly typed view, as usual. Now you have the advantages of strong typing without having to ...
Strongly typed ASP.NET MVC ViewData extensions - where to put identifiers?
[ "", "c#", "asp.net-mvc", "" ]
Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times? I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with `document.referrer` or `addEventListener`, but then I'm lost. I need something that will capture...
I tried this and it worked fine: ``` window.onload = function() { var clicked = readCookie('popunder'); if(clicked == null) { clicked = 0; } var allLinks = document.getElementsByTagName("a"); for(i=0;i<=allLinks.length;i++) { allLinks[i].addEventListener("click",countClicks,true); ...
Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3. Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out w...
How to find out user clicked 3 times through my website with Javascript
[ "", "javascript", "click", "dom-events", "" ]
I coded up 4 .java files. The thing is that I can only execute my .java files from my IDE, how do I execute the .class files like an application? I study at uni, and I was told that Java is platform independent. Any tutorial/book recommendations would be highly appreciated. Thanks
The basic idea (to give you some things to search for) is: * Bundle your compiled .class files into a 'jar'. * Add a manifest to your jar specifying a main class to run. You might find your IDE already creates this when you run a 'clean build'. Netbeans puts this into a 'dist' folder. Modern JREs will allow you to r...
Look at [executable jar](http://java.sun.com/docs/books/tutorial/deployment/jar/). Here is the precise one, without any details, [Creating executable jar files](http://csdl.ics.hawaii.edu/~johnson/613f99/modules/04/jar-files.html).
how do I convert my java files into an application?
[ "", "java", "executable", "executable-jar", "" ]
I have a SQL table like so: Update: I'm changing the example table as the existing hierarchical nature of the original data (State, Cities, Schools) is overshadowing the fact that a simple relationship is needed between the items. ``` entities id name 1 Apple 2 Orange ...
Define a constraint: `entity_id_a < entity_id_b`. Create indexes: ``` CREATE UNIQUE INDEX ix_a_b ON entity_entity(entity_id_a, entity_id_b); CREATE INDEX ix_b ON entity_entity(entity_id_b); ``` Second index doesn't need to include `entity_id_a` as you will use it only to select all `a`'s within one `b`. `RANGE SCAN`...
I think the structure you have suggested is fine. To get the related records do something like ``` SELECT related.* FROM entities AS search LEFT JOIN entity_entity map ON map.entity_id_a = search.id LEFT JOIN entities AS related ON map.entity_id_b = related.id WHERE search.name = 'Search term' ``` Hope that helps.
What is the best way to represent a many-to-many relationship between records in a single SQL table?
[ "", "sql", "database", "many-to-many", "entity-relationship", "relational", "" ]
Preface: I have jQuery and jQuery UI included on a page. I have this function defined: ``` function swap(sel) { if (1 == 1) { $(sel).hide('drop',{direction:'left'}); } } ``` How do I fix the (1 == 1) part to test to see if the element is already hidden and then bring it back if it ...
if you don't like `toggle`, then this may help you: ``` function swap(sel) { if($(sel).is(':visible')) { $(sel).hide('drop',{direction:'left'}); } else { $(sel).show('drop',{direction:'left'}); } } ```
As the other answerers have said, `toggle()` is the best solution. However if for some reason you can't/don't want to use toggle, and if your selector is for only one element: ``` function swap(sel) { if ($(sel).is(':visible')) { // Is this element visible? $(sel).hide('drop',{direction:'left'}); } } `...
jQuery UI - a swap function that hides and unhides elements by selector
[ "", "javascript", "jquery", "jquery-ui", "" ]
I want to auto-generate a HTML table from some custom data. One of the columns in my data is a number in the range 0-100, and I'd like to show it in a more graphical way, most desirably a colored horizontal bar. The length of the bar would represent the value, and the color would also change (i.e. below 20 it's red, et...
AListApart has a great article on how to generate charts using purely CSS. It's nice because it is accessible, meaning even without CSS it will provide meaningful data. <http://www.alistapart.com/articles/accessibledatavisualization> **Update:** According to one of the commenters on this answer, this solution will al...
This is doable. 2 options: 1) put an image in every cell using the img tag and resize the image using the width attribute 2) put a div with a pre-set height and change the width according to the value you want it to display. Use the background color of the div as your color - no images needed. example: ``` <table ...
Turning numbers into colored bars automatically in HTML/Javascript
[ "", "javascript", "html", "css", "" ]
Is it possible to pass a function as a parameter in C#? I can do it using the Func or Action classes, but this forces me to declare the entire function signature at once. When I try to use Delegate, I get a compile error saying it can't convert a method group to a Delegate. I'm working on [Axial](http://www.codeplex.c...
I think what you want is: ``` static object InvokeMethod(Delegate method, params object[] args){ return method.DynamicInvoke(args); } static int Add(int a, int b){ return a + b; } static void Test(){ Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4)); } ``` Prints "9".
Converting a method group, anonymous method or lambda expression to a delegate requires the compiler to know the exact delegate type. However, you could potentially use lambda expressions and captured variables to make this simpler: ``` public void InvokeMethod(Action action) { action(); } public int Add(int a, i...
How to pass a function as a parameter in C#?
[ "", "c#", "reflection", "" ]
I have the following snippet of code that's generating the "Use new keyword if hiding was intended" warning in VS2008: ``` public double Foo(double param) { return base.Foo(param); } ``` The `Foo()` function in the base class is protected and I want to expose it to a unit test by putting it in wrapper class solely...
The `new` just makes it absolutely clear that you know you are stomping over an existing method. Since the existing code was `protected`, it isn't as big a deal - you can safely add the `new` to stop it moaning. The difference comes when your method does something different; any variable that references the *derived* ...
The key is that you're *not* overriding the method. You're hiding it. If you were overriding it, you'd need the `override` keyword (at which point, unless it's virtual, the compiler would complain because you *can't* override a non-virtual method). You use the `new` keyword to tell both the compiler and anyone reading...
Use new keyword if hiding was intended
[ "", "c#", "inheritance", "warnings", "new-operator", "" ]
How do I force my application to run as 32-bit on a 64-bit machine? The code is written in C#.
Right click your project, and select properties. In properties, select the build tab. Under platform target, select x86. Hit `Ctrl`+`Shift`+`S` to save all files, right click the solution and select "Clean" to get rid of old binaries. Any builds after that should be 32 bit
Command-line form: ``` corflags application.exe /32BIT+ ``` (reference: <https://learn.microsoft.com/en-us/dotnet/framework/tools/corflags-exe-corflags-conversion-tool>)
Running a C# application as 32-bit on a 64-bit machine
[ "", "c#", ".net", "process", "x86", "32bit-64bit", "" ]
On my java project, I have a bunch of strings externalized on a `messages.properties` file. On its respective `Messages.java` file I had the same number of public static String-typed attributes, so I could access those externalized texts. Then, I implemented a method called `getString`, which receives the name of the ...
Messages sounds like a class you wrote, because I don't see it in my JDK 6 javadocs. It sounds like you've tried to reinvent java.util.ResourceBundle. I'd recommend using that instead and ditching your class. It'll have the added advantage of handling I18N properly. I don't see any value in hard-coding the public sta...
Your `Messages` class - it sounds like it extends `org.eclipse.osgi.util.NLS`. If this is the case, it is designed to fill the requirements: * to provide compile time checking that a message exists. * to avoid the memory usage of a map containing both keys and values (this would be the case in a resource bundle appro...
How do I avoid unwanted log messages on java project?
[ "", "java", "nls", "" ]
I would like to use `Dictionary` as `TKey` in another `Dictionary`. Something similar to python. I tried this but it gives me errors. ``` Dictionary<Dictionary<string, string>, int> dict = new Dictionary<Dictionary<string, string>, int>(); Dictionary<string, string> dict2 = new Dictionary<string, string>(); dict2["...
What error is it giving you? Is it complaining about your missing bracket on line 4? Line 4 looks like it should be: ``` dict[dict["abc"]] = 20; ``` However, you probably mean this, since "abc" is not a key of dict: ``` dict[dict2["abc"]] = 20; ``` But `dict2["abc"]` is a `string`, when the key of dict is supposed...
Just to throw this in there, I often find that dealing with complicated dictionaries like you describe it's far better to use real names with them rather than trying to let the reader of the code sort it out. You can do this one of two ways depending on personal preference. Either with a using statement to create a co...
using dictionary as a key in other dictionary
[ "", "c#", "dictionary", "" ]
How do I get an old VC++ 6.0 MFC program to read and display UTF8 in a TextBox or MessageBox? Preferably without breaking any of the file reading and displaying that is currently written in there (fairly substantial). I read a line into CString strStr, then used this code: ``` int nLengthNeeded = MultiByteToWideChar(...
I feel like this won't be helpful, but it's a starting point... I'm assuming it doesn't 'just work', and I don't think you want to try to screw around with wacky code pages that may or may not get you what you want. How about just using MultiByteToWideChar(CP\_UTF8, ...) to convert it to utf16 and then calling the W v...
take a look at: [widechartomultibyte](http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx) and [for more general info](http://msdn.microsoft.com/en-us/library/ey142t48.aspx) when/if you run into trouble, make sure you post your code. It's been a while since I did that and I remember it being a bit tricky.
UTF-8 From File to TextBox VC++ 6.0
[ "", "c++", "mfc", "utf-8", "visual-c++-6", "" ]
I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)? ``` >>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' >>> addrs = "Zip: 10010 State: NY" >>> y ...
regex definition: ``` (?P<zip>...) ``` Creates a named group "zip" ``` Zip:\s* ``` Match "Zip:" and zero or more whitespace characters ``` \d ``` Match a digit ``` \w ``` Match a word character [A-Za-z0-9\_] ``` y.groupdict('zip') ``` The groupdict method returns a dictionary with named groups as keys and the...
The **search** method will return an object containing the results of your regex pattern. **groupdict** returns a dictionnary of groups where the keys are the name of the groups defined by (?P...). Here *name* is a name for the group. **group** returns a list of groups that are matched. "State: NY" is your third grou...
Python-Regex, what's going on here?
[ "", "python", "regex", "" ]
I'm using Spring + JPA + Hibernate. I'm trying to enable Hibernate's second level cache. In my Spring's `applicationContext.xml` I have: ``` <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache...
I didn't answer this, but it's not obvious that the poster found the answer himself. I'm reposting his answer: ### Resolved Since I'm using `LocalEntityManagerFactoryBean` it gets its settings from `META-INF/persistence.xml`. My settings in `applicationContext.xml` weren't even being read.
Try this: ``` <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.max_fetch_depth">4</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRe...
Hibernate second level cache with Spring
[ "", "java", "hibernate", "spring", "jpa", "jakarta-ee", "" ]
I need a basic example of how to use the `IComparable` interface so that I can sort in ascending or descending order and by different fields of the object type I'm sorting.
Well, since you are using `List<T>` it would be a lot simpler to just use a `Comparison<T>`, for example: ``` List<Foo> data = ... // sort by name descending data.Sort((x,y) => -x.Name.CompareTo(y.Name)); ``` Of course, with LINQ you could just use: ``` var ordered = data.OrderByDescending(x=>x.Name); ``` But you c...
Here's a simple example: ``` public class SortableItem : IComparable<SortableItem> { public int someNumber; #region IComparable<SortableItem> Members public int CompareTo(SortableItem other) { int ret = -1; if (someNumber < other.someNumber) ret = -1; else if (some...
How do I use the IComparable interface?
[ "", "c#", ".net", "icomparable", "" ]
I am trying to find out programatically the max permgen and max heap size with which a the JVM for my program has been invoked, not what is currently available to them. Is there a way to do that? I am familiar with the methods in Java Runtime object, but its not clear what they really deliver. Alternatively, is ther...
Try this ones: ``` MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); mem.getHeapMemoryUsage().getUsed(); mem.getNonHeapMemoryUsage().getUsed(); ``` But they only offer snapshot data, not a cummulated value.
Try something like this for max perm gen: ``` public static long getPermGenMax() { for (MemoryPoolMXBean mx : ManagementFactory.getMemoryPoolMXBeans()) { if ("Perm Gen".equals(mx.getName())) { return mx.getUsage().getMax(); } } throw new RuntimeException("Perm gen not found"); }...
How to get the max sizes of the heap and permgen from the JVM?
[ "", "java", "memory-management", "jvm", "" ]
I want to get hold of the mouse position in a timeout callback. As far as I can tell, this can't be done directly. One work around might be to set an onmousemove event on document.body and to save this position, fetching later. This would be rather expensive however, and isn't the cleanest of approaches.
I think you'll have to do the same thing as @Oli, but then if you're using jQuery, it would be much more easier. <http://docs.jquery.com/Tutorials:Mouse_Position> ``` <script type="text/javascript"> jQuery(document).ready(function(){ $().mousemove(function(e){ $('#status').html(e.pageX +', '+ e.pageY); }); }...
The direct answer is **no** but as you correctly say, you can attach events to everything and poll accordingly. It *would* be expensive to do serious programming on every onmousemove instance so you might find it better to create several zones around the page and poll for a onmouseover event. Another alternative would...
Javascript: Is it possible to get hold of the mouse position outside of an event handler?
[ "", "javascript", "events", "mouse", "" ]
**Follow up to**: [How to safely update a file that has many readers and one writer?](https://stackoverflow.com/questions/421357/how-to-safely-update-a-file-that-has-many-readers-and-one-writer) In my previous questions, I figured out that you can use FileChannel's lock to ensure an ordering on reads and writes. But ...
despite the fact that there is no bullet-proof, cross-OS, cross-FS solution, the "write to unique temp file and rename" strategy is still your best option. most platforms/filesystems attempt to make file renaming (effectively) atomic. note, you want to use a +separate+ lock file for locking. so, assuming you want to u...
I don't think there is a perfect answer. I don't exactly know what you need to do, but can you do the writing to a new file, and then on success, rename files, rather than copying. Renaming is quick, and hence should be less prone a crash. This still won't help if it fails at the rename stage, but you've minimized the ...
How to ensure file integrity on file write failures?
[ "", "java", "file", "locking", "integrity", "" ]
Let's say I have some Java code: ``` public class SomeClass { static { private final double PI = 3.14; private final double SOME_CONSTANT = 5.76; private final double SOME_OTHER_CONSTANT = 756.33; } //rest of class } ``` If a thread is initializing SomeClass's `Class` object and is ...
If the first thread hasn't finished initializing SomeClass, the second thread will block. This is detailed in the Java Language Specification in [section 12.4.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2).
Static class initialization is guaranteed to be thread-safe by Java.
Thread safety of static blocks in Java
[ "", "java", "multithreading", "static", "" ]
I have an array of doubles and I want the index of the highest value. These are the solutions that I've come up with so far but I think that there must be a more elegant solution. Ideas? ``` double[] score = new double[] { 12.2, 13.3, 5, 17.2, 2.2, 4.5 }; int topScoreIndex = score.Select((item, indx) => new {Item = it...
I suggest writing your own extension method (edited to be generic with an `IComparable<T>` constraint.) ``` public static int MaxIndex<T>(this IEnumerable<T> sequence) where T : IComparable<T> { int maxIndex = -1; T maxValue = default(T); // Immediately overwritten anyway int index = 0; foreach (T...
Meh, why make it overcomplicated? This is the simplest way. ``` var indexAtMax = scores.ToList().IndexOf(scores.Max()); ``` Yeah, you could make an extension method to use less memory, but unless you're dealing with huge arrays, you will *never* notice the difference.
How do I get the index of the highest value in an array using LINQ?
[ "", "c#", "linq", "" ]
I have several objects in the database. Url to edit an object using the generic view looks like `site.com/cases/edit/123/` where `123` is an id of the particular object. Consider the `cases/url.py` contents: ``` url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit')...
In short what you need to do is wrap the update\_object function. ``` def update_object_wrapper(request, object_id, *args, **kwargs): redirect_to = reverse('your object edit url name', object_id) return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs) ```
First, read up on the [reverse](http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse) function. Second, read up on the `{%` [url](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url) `%}` tag. You use the `reverse` function in a view to generate the expected redirect location. Als...
how to pass id from url to post_save_redirect in urls.py
[ "", "python", "django", "django-urls", "" ]
We have a webapp where people can upload various image file types and on the backend we convert them to a standard type (typically png or jpeg). Right now we are using ImageIO to do this. However the new requirement is to be able to support eps files. I haven't found any libraries that support EPS in ImageIO, or much i...
I'm pretty sure ImageMagick (a C library) can do that (though I believe it requires GhostScript), and there's a JNI wrapper for ImageMagick called [JMagick](http://www.jmagick.org/index.html) that allows access to ImageMagick from Java. If you can deal with JNI, JMagick might do the trick.
[Freehep](http://java.freehep.org/freehep1.x/) has a [Java PostScript Viewer](http://java.freehep.org/freehep1.x/psviewer/) that you might be able to rework into a PS converter.
Need to convert EPS files to jpg/png in Java
[ "", "java", "eps", "" ]
SO has plenty of Q&As about how to accomplish various tasks using dynamic SQL, frequently the responses are accompanied with warnings and disclaimers about the advisability of actually using the approach provided. I've worked in environments ranging from "knowing how to use a cursor is a bad sign" to "isn't sp\_execute...
Answers to some of your questions can be found here [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html) Sometimes you have to use dynamic SQL because it will perform better
It depends on what you mean by dynamic sql. Queries built where parameter values substituted directly into the sql string are dangerous and should be avoided except for the very rare case where there is no other option. Dynamic SQL using the appropriate parameterized query mechanism supported by your platform can be v...
Dynamic SQL in production systems
[ "", "sql", "" ]
I need ideas to implement a (really) high performance in-memory Database/Storage Mechanism in Java. In the range of storing 20,000+ java objects, updated every 5 or so seconds. Some options I am open to: Pure JDBC/database combination JDO JPA/ORM/database combination An Object Database Other Storage Mechanisms ...
You could try something like [Prevayler](http://prevayler.org/old_wiki/Welcome.html) (basically an in-memory cache that handles serialization and backup for you so data persists and is transactionally safe). There are other similar projects. I've used it for a large project, it's safe and extremely fast. If it's the s...
I highly recommend **[H2](http://www.h2database.com/html/main.html)**. This is a kind of "second generation" version of HSQLDB done by one of the original authors. **H2** allows us to unit-test our DAO layer without requiring an actual PostgreSQL database, which is **awesome**. There is an active net group and mailing...
Highest Performance Database in Java
[ "", "java", "database", "performance", "embedded-database", "" ]
I'm used to using Telerik Grids and I'm able to display them in an outlook style, i.e. a picture on the far left, a bold title and a few other lines of text under the main title. Is there a way do this using a standard .Net2.0 Windows control? Either with a cheap control, or the existing datagridview or listview? Bas...
Here is help with using a listview for the list. I would go with the list because you will only have one column, so no need for the grid. You want to use : ``` private void lstItems_DrawItem(object sender, DrawItemEventArgs e) ``` Then use the e.Graphics to get an object you can draw directly to. I used this [tutor...
I can't give you an example as I don't have time to write it at this time, but you could create a UserControl which lays out the row as you would like to see it. Then you would have to create your own DataGridViewCell which can handle a UserControl rather than the standard cell types which MS provides. For each of your...
DataGridView/ListView - Display in an Outlook style?
[ "", "c#", "visual-studio", "datagridview", "datagridviewcolumn", "" ]
What is a reasonable amount of time to wait for a web request to return? I know this is maybe a little loaded as a question, but all I am trying to do is verify if a web page is available. Maybe there is a better way? ``` try { // Create the web request HttpWebRequest request = WebRequest.Create(this.getUr...
You need to consider how long the consumer of the web service is going to take e.g. if you are connecting to a DB web server and you run a lengthy query, you need to make the web service timeout longer then the time the query will take. Otherwise, the web service will (erroneously) time out. I also use something like ...
Offhand I'd allow 10 seconds, but it really depends on what kind of network connection the code will be running with. Try running some test pings over a period of a few days/weeks to see what the typical response time is.
Timeout for Web Request
[ "", "c#", "" ]
I am using the (.NET 3.5 SP1) System.Xml.Linq namespace to populate an html template document with div tags of data (and then save it to disk). Sometimes the div tags are empty and this seems to be a problem when it comes to HTML. According to my research, the DIV tag is not self-closing. Therefore, under Firefox at le...
I'm not sure why you'd end up with an empty DIV (seems a bit pointless!) But: ``` divTag.SetValue(string.Empty); ``` Should do it.
With XElement divTag = new XElement("div", String.Empty); you get the explicit closing tag
Explicit Element Closing Tags with System.Xml.Linq Namespace
[ "", "c#", "xml", "linq-to-xml", "" ]
How do I read the response headers returned from a PyCurl request?
There are several solutions (by default, they are dropped). Here is an example using the option HEADERFUNCTION which lets you indicate a function to handle them. Other solutions are options WRITEHEADER (not compatible with WRITEFUNCTION) or setting HEADER to True so that they are transmitted with the body. ``` #!/usr...
``` import pycurl from StringIO import StringIO headers = StringIO() c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.HEADER, 1) c.setopt(c.NOBODY, 1) # header only, no body c.setopt(c.HEADERFUNCTION, headers.write) c.perform() print headers.getvalue() ``` Add any other curl setopts as necessary/desired, such as ...
How to read the header with pycurl
[ "", "python", "curl", "pycurl", "" ]
I would like to print my Swing JComponent via iText to pdf. ``` JComponent com = new JPanel(); com.add( new JLabel("hello") ); PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream( dFile ) ); document.open( ); PdfContentByte cb = writer.getDirectContent( ); PdfTemplate tp = cb.createTemplate( pag...
I have figured it out adding addNotify and validate helps. ``` com.addNotify( ); com.validate( ); ```
I needed to call ``` com.addNotify() com.setSize() com.validate() ```
How do I paint Swing Components to a PDF file with iText?
[ "", "java", "swing", "pdf", "pdf-generation", "itext", "" ]
I'm working on an application that loads untrusted assemblies via an interface. Each of those assemblies should be able to add one or more GameAction objects to a thread-safe queue used by the server. The first iteration of design was to just pass the queue--something like this: ``` public interface IGameClient { v...
Thoughts in no particular order: 1) Events *do* guarantee ordering (or at least, your implementation could guarantee whatever ordering you want, and the simplest implementations will preserve ordering). 2) I don't see why you'd want to pass the queue by reference in the first example of the interface. It may be worth...
Don't expose the queue at all--simply expose a method on a facade that allows the GameClient to submit an entry that the GameServer will place on the internal queue.
Write-only queue?
[ "", "c#", ".net", "security", "" ]
I think I am being a bonehead, maybe not importing the right package, but when I do... ``` from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "insert into as...
That's because parameters can only be passed to VALUES. The table name can't be parametrized. Also you have quotes around a parametrized argument on the second query. Remove the quotes, escaping is handled by the underlining library automatically for you.
Try removing the quotes in the line that assigns to `stmt2`: ``` stmt2 = "insert into asgn values (?, ?)" ``` Also, as nosklo says, you can't use question-mark parameterisation with CREATE TABLE statements. Stick the table name into the SQL directly.
Python pysqlite not accepting my qmark parameterization
[ "", "python", "sqlite", "pysqlite", "python-db-api", "" ]
Is there a [ternary conditional operator](https://en.wikipedia.org/wiki/%3F:#Python) in Python?
Yes, it was [added](https://mail.python.org/pipermail/python-dev/2005-September/056846.html "[Python-Dev] Conditional Expression Resolution") in version 2.5. The expression syntax is: ``` a if condition else b ``` First `condition` is evaluated, then exactly one of either `a` or `b` is evaluated and returned based on...
You can index into a tuple: ``` (falseValue, trueValue)[test] ``` `test` needs to return *True* or *False*. It might be safer to always implement it as: ``` (falseValue, trueValue)[test == True] ``` or you can use the built-in [`bool()`](https://docs.python.org/3.3/library/functions.html#bool "bool") to assure a ...
Does Python have a ternary conditional operator?
[ "", "python", "operators", "conditional-operator", "" ]
I was looking a lot for method to get parent process in .NET, but found only P/Invoke way.
This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name: Usage: ``` Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id); ``` Code: ``` public static class ProcessExtensions { private static ...
Here is a solution. It uses p/invoke, but seems to work well, 32 or 64 cpu: ``` /// <summary> /// A utility class to determine a process parent. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ParentProcessUtilities { // These members must match PROCESS_BASIC_INFORMATION internal IntPtr Rese...
How to get parent process in .NET in managed way
[ "", "c#", "process", "pinvoke", "parent", "managed", "" ]
I'm trying to new up a LocalCommand instance which is a private class of System.Data.SqlClient.SqlCommandSet. I seem to be able to grab the type information just fine: ``` Assembly sysData = Assembly.Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); localCmdType = sysData.GetType(...
My first thought would be to get the `ConstructorInfo` using `ConstructorInfo constructorInfo = Type.GetConstructor()`, and then `constructorInfo.Invoke()` that. I suspect that `Activator.CreateInstance` makes it hard to call constructors you wouldn't normally have access to, although I don't remember trying it myself.
I got it to work this way: ``` using System; using System.Reflection; class Test { public String X { get; set; } Test(String x) { this.X = x; } } class Program { static void Main() { Type type = typeof(Test); ConstructorInfo c = type.GetConstructor(BindingFlags.NonPu...
Activator.CreateInstance with private sealed class
[ "", "c#", "reflection", "ado.net", "" ]
What does it mean by POD type?cv-qualified?
Very Nice article on [POD](http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html)
POD, Plain Old Data, is any C++ type that has an equivalent in C. cv-qualified type is a type that have been qualified either as a const or volatile. ``` // non cv_qualified int one; char *two; // cv-qualified const int three; volatile char * four; ``` POD type's data members must be public and can be of any th...
Terms new to beginners in c++?
[ "", "c++", "" ]
If you are doing something like the following: ``` var i = $('input[@name=some_field]'); if (i.val() != '' && !(i.val() >=1 && i.val() <= 36) || i.val() == 'OT')) { i.focus(); } ``` is `i.val()` fast enough to use it multiple times or should you do: ``` var value = i.val(); ``` first and then use value in the ...
This isn't necessarily a jQuery question but it applies pretty well to most programming languages. And in fact, there's a lot more to this question than just performance issues. One thing to keep in mind is that if you store the value, then there is no possibility that it will change during the execution of your subse...
When called without any parameters, I don't believe val() would be significantly slower then just accessing the value property directly. Based on my reading of the jQuery source code, essentially all the val() method does is check whether the element is a select, and if not, simply returns the content of the value prop...
jQuery: is val() fast enough to use repeatedly or is it better to put the value in a variable
[ "", "javascript", "jquery", "" ]
I looked in [Stevens](http://www.google.com/search?q=advanced+programming+in+the+unix+environment&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a), and in the [Posix Programmer's Guide](https://rads.stackoverflow.com/amzn/click/com/0937175730), and the best I can find is > An array of strings ca...
I think you can run your program with LD\_DEBUG set to see the exact order: ``` LD_DEBUG=all <myprogram> ``` **EDIT:** If you look at the source code of the runtime linker (glibc 2.7), specifically in files: * sysdeps/unix/sysv/linux/init-first.c * sysdeps/i386/init-first.c * csu/libc-start.c * sysdeps/i386/elf/star...
Given that both the environment setup and the invoking of the static initializers are functions that the language run-time has to perform *before* main() is invoked, I am not sure you will find a guarantee here. That is, I am not aware of a specific requirement here that this *has* to work and that the order is guarant...
Is it safe to use getenv() in static initializers, that is, before main()?
[ "", "c++", "c", "unix", "posix", "environment", "" ]
I would like to write an simple application able to retrieve some certain data from another process(application)'s allocated memory. Say I already know a process' id and I would like to obtain a value in this process' memory always from a fixed offset (like 0x523F1C), is this doable in the user-mode, or it has to be i...
Use ReadProcessMemory - you'll need a handle with PROCESS\_VM\_READ access to the other process[1], but if you're an administrator (or possibly, if you have SE\_DEBUG privs) it should be straightforward. ``` BOOL WINAPI ReadProcessMemory( __in HANDLE hProcess, __in LPCVOID lpBaseAddress, __out LPVOID lpBuff...
If you're doing interprocess communications / shared memory, I would suggest using [Boost::Interprocess](http://www.boost.org/doc/libs/1_35_0/doc/html/interprocess.html) instead as it will make life much easier.
Get the value from a fixed memory offset : Visual C++ Programming
[ "", "c++", "visual-c++", "" ]
One thing that's always confused me is input escaping and whether or not you're protected from attacks like SQL injection. Say I have a form which sends data using HTTP POST to a PHP file. I type the following in an input field and submit the form: ``` "Hello", said Jimmy O'Toole. ``` If you print/echo the input on ...
Ah, the wonders of [magic quotes](http://php.net/magic_quotes). It is making those unnecessary escapes from your POST forms. You should disable (or neutralize) them, and many of your headaches go away. Here's an exemplary article of the subject: <http://www.sitepoint.com/blogs/2005/03/02/magic-quotes-headaches/> Reca...
Instead of relying on escaping I would use parametrized SQL queries and let the mysql driver do whatever escaping it needs.
Understanding input escaping in PHP
[ "", "php", "mysql", "escaping", "sql-injection", "magic-quotes", "" ]
I have a small AJAX application, written in PHP that I did not secure from the start. I would like some recommendations on how to now secure the app, things to implement and check for. I have not found any exhaustive guides on google, and hope that some can be recommended. It is a small application that connects to an...
If you are talking about securing the app (as opposed to the server/ environment it is on - which I am not really qualified to address) then I would consider the following: 1. Ensure any user inputs are parsed/cleaned to ensure they can't do things such as [SQL injection attacks](http://www.unixwiz.net/techtips/sql-in...
The most important rule when handling user input is: *Validate input, escape output*.
Guide for securing an ajax php webapp
[ "", "php", "ajax", "security", "" ]
In C#, is there an inline shortcut to instantiate a List<T> with only one item? I'm currently doing: ``` new List<string>( new string[] { "title" } )) ``` Having this code everywhere reduces readability. I've thought of using a utility method like this: ``` public static List<T> SingleItemList<T>( T value ) { r...
Simply use this: ``` List<string> list = new List<string>() { "single value" }; ``` You can even omit the () braces: ``` List<string> list = new List<string> { "single value" }; ``` Update: of course this also works for more than one entry: ``` List<string> list = new List<string> { "value1", "value2", ... }; ```
``` var list = new List<string>(1) { "hello" }; ``` Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially. Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.
Shortcut for creating single item list in C#
[ "", "c#", "" ]
I'm working on a macro system for Python ([as discussed here](https://stackoverflow.com/questions/454648/pythonic-macro-syntax)) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of tim...
Here are a few possible problems: * You may find it difficult to provide the user with helpful error messages in case of a problem. This seems likely, as any compilation-time syntax error could be just a syntax extension. * Performance hit. I was trying to find some discussion of the pluses, minuses, and/or implement...
Here are some ideas from my master's thesis, which may or may not be helpful. The thesis was about robust parsing of natural language. The main idea: given a context-free grammar for a language, try to parse a given text (or, in your case, a python program). If parsing failed, you will have a partially generated parse ...
Partial evaluation for parsing
[ "", "python", "parsing", "macros", "language-design", "" ]
When referencing class variables, why do people prepend it with `this`? I'm not talking about the case when `this` is used to disambiguate from method parameters, but rather when it seems unnecessary. Example: ``` public class Person { private String name; public String toString() { return th...
Same reason why some people like to prepend private data members with "m\_" or name interfaces "IFoo". They believe it increases readability and clarity. Whether or not you agree with conventions like these is a matter of taste.
1. Defensive programming (in case someone editing the code later adds a parameter or local with a conflicting name 2. Make the code "self documenting," more obvious
In Java, why do people prepend fields with `this`?
[ "", "java", "coding-style", "" ]
I'm working on a resource management class and want to have the user provide a functor to a "ReleaseResource" method as part of the resource manager's constructor. From there when a resource is requested that functor will be provided as the deleter for the shared\_ptr that I will be returning so that the appropriate me...
``` template<class MyFunctor> MyMethod(MyFunctor f) { boost::function<void()> g = f; g(); } ``` The type you pass to [`boost::function`](http://www.boost.org/doc/libs/1_37_0/doc/html/function.html) is the function type. For example, `int(bool, char)` is the type of a function returning int and taking a bool an...
There are two ways, both of which biol down to templating the class. ``` template <MyFunctor> class MyClass { MyFunctor func; public: MyClass(MyFunctor f) :func(f) { } MyMethod() { func(); } } ``` This would require you to know the type of the functor. To avoid that, we can use a fa...
Retaining functors as variables
[ "", "c++", "functor", "" ]
there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function. ``` >>> def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... >>> gs(1,2) # should return 2 ...
This should allow you to keep checking the state and return from the outer function if a and b ever end up the same: ``` def gs(a,b): class SameEvent(Exception): pass def ry(): if a==b: raise SameEvent(a) try: # Do stuff here, and call ry whenever you want to return if t...
Do you mean? ``` def gs(a,b): def ry(): if a==b: return a return ry() ```
make a parent function return - super return?
[ "", "python", "class", "function", "return", "parent", "" ]
## Background: I have an application written in native C++ which uses the wxWidgets toolkit's wxODBC database access library which is being [removed](http://wiki.wxwidgets.org/ODBC) from all future versions of wxWidgets . I need to replace this with another database access method that supports the assumptions and cont...
I use SQLAPI++. Well worth a look. <http://www.sqlapi.com/>
A library is <http://otl.sourceforge.net/> An employer of mine used it. I can't tell you how its performance compares with wxODBC, but it might fit your requirements.
Database Access Libraries for C++
[ "", "c++", "windows", "database", "linux", "unmanaged", "" ]
I know: * Firebird: `FIRST` and `SKIP`; * MySQL: `LIMIT`; * SQL Server: `ROW_NUMBER()`; Does someone knows a SQL ANSI way to perform result paging?
See **Limit—with offset** section on this page: [<http://troels.arvin.dk/db/rdbms/>](http://troels.arvin.dk/db/rdbms/) BTW, Firebird also supports ROWS clause since version 2.0
No official way, no.\* Generally you'll want to have an abstracted-out function in your database access layer that will cope with it for you; give it a hint that you're on MySQL or PostgreSQL and it can add a 'LIMIT' clause to your query, or rownum over a subquery for Oracle and so on. If it doesn't know it can do any...
There are a method to paging using ANSI SQL only?
[ "", "sql", "ansi-sql", "" ]
This is a generalization of the "string contains substring" problem to (more) arbitrary types. Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts: Example usage (Seque...
I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in [Python Cookbook](https://rads.stackoverflow.com/amzn/click/com/0596007973) 2nd edition. You can find the related code at <http://code.activestate.com/recipes/117214/> It finds *all* the correct subsequ...
Here's a brute-force approach `O(n*m)` (similar to [@mcella's answer](https://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python#425764)). It might be faster than the Knuth-Morris-Pratt algorithm implementation in pure Python `O(n+m)` (see [@Gregg Lind answer](https:...
Best way to determine if a sequence is in another sequence?
[ "", "python", "algorithm", "sequence", "" ]