Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
The following code says that passing the map as `const` into the `operator[]` method discards qualifiers: ``` #include <iostream> #include <map> #include <string> using namespace std; class MapWrapper { public: const int &get_value(const int &key) const { return _map[key]; } private: map<int, in...
[`std::map`'s `operator []` is not declared as `const`, and cannot be due to its behavior:](http://en.cppreference.com/w/cpp/container/map/operator_at) > T& operator[] (const Key& key) > > Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exis...
Since [`operator[]`](http://www.cplusplus.com/reference/map/map/operator%5b%5d/) does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values. Instead, you can use: ``` V...
C++ map access discards qualifiers (const)
[ "", "c++", "constants", "" ]
Ok so I have an abstract base class called Product, a KitItem class that inherits Product and a PackageKitItem class that inherits KitItem. ie. ``` Product KitItem : Product PackageKitItem : KitItem ``` I have my KitItems loaded and I need to load up a collection of PackageKitItems which are, effectively, shallow cop...
The problem you have is that since ShallowCopy() is a member of KitItem, MemberwiseClone() is just copying the KitItem fields and returning a KitItem even if the original object is a PackageKitItem. I think what you have to do in this circumstance add to KitItem: ``` public virtual KitItem ShallowCopy() { ...
Strangely I didn't get an error doing this on Visual Studio 2008. I am posting the code so you can see what I am missing or what I am assuming wrong. My guess is that the problem is in one of the class members that you didn't post. ``` using System; using System.Collections.Generic; using System.ComponentModel; using ...
Shallow Copy From Inherited Classes
[ "", "c#", "inheritance", "shallow-copy", "" ]
I've a form and I'm doing databinding of my datagridview in the event "form load", the problem is, that the form takes a little (or a lot depends on the size of information) to load, because my data has a lot of binary information (photos) to binding there. In some sites, we can see a picture saying "loading", which i...
You can't do much about the actual binding itself, since forms have thread affinity. However, you can load the data (from the database or where-ever) on a separate thread - look at [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx), for example. If the db-load is fa...
You could show the 'loading' form in a different thread. Also consider hard whether you need *all* of the data loaded with the form - could any of this data be loaded after the form load? Try and give your application a feeling of *perceived* speed.
How can I play with databinding to a desktop application like in web-based application
[ "", "c#", ".net", "" ]
The problem is simple: Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following ``` export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/ export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite...
The problem is not with bash. It should be setting your environment variable correctly, complete with the `:` character. The problem, instead, is with Python's parsing of the `PYTHONPATH` variable. Following the example set by the [`PATH` variable](http://sourceware.org/cgi-bin/cvsweb.cgi/libc/posix/execvp.c?rev=1.27&...
The OP was trying to add a URL with a port number to a list of file paths. This type of URL is not a file path so python would never find a python file at that location. It doesn't make sense to put a URL with a port number into PYTHONPATH. Regardless, some people may end up at this question because of the following: ...
How do I add a directory with a colon to PYTHONPATH?
[ "", "python", "bash", "shell", "" ]
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86\_64 as well, but I immediately hit a problem. I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86\_64 code is correct: ``` fro...
As [vincent](https://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333) mentioned, this is due to the allocated page being marked as non executable. Newer processors support this [functionality](http://en.wikipedia.org/wiki/NX_bit), and its used as an added layer of security by OS's which suppo...
Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT\_EXEC and on others it does. Therefore it is necessary to change the protection level with mprotect afterwards. Lame thing, took a while to find out what to do. ``` fr...
Python ctypes and function calls
[ "", "python", "c", "assembly", "ctypes", "x86-64", "" ]
Previously, I had a class that wrapped an internal `System.Collections.Generic.List<Item>` (where Item is a class I created). The wrapper class provided several collection-level properties that provided totals, averages, and other computations on items in the list. I was creating a `BindingSource` around this wrapped `...
The system treats anything that implements `IList` (or `IListSource`) as a container, rather than an item. As such, you cannot bind to properties of anything that implements `IList`. As such, *encapsulation* (i.e. what you already have) is the best approach if you want to be able to bind to properties of the container....
The problem here is that you want to use your one class for two completely different purposes (in terms of bindings). Example: The "AverageValue" property doesn't make sense to be on each item, because it's a global property that spans all items. Either way, I'm guessing that your \_itemsBindingSource is for a ComboB...
How can I databind to properties not associated with a list item in classes deriving List<T>
[ "", "c#", "generics", "data-binding", "" ]
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
With: ``` decorator(original_function)() ``` Without: ``` original_function() ``` A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some [documentation](https://wiki.python.org/moin/PythonDecorators) might help clar...
``` def original_function(): pass decorated_function= decorator(original_function) if use_decorated: decorated_function() else: original_function() ``` Decorate only once, and afterwards choose which version to call.
Python decorating functions before call
[ "", "python", "decorator", "" ]
We are using jQuery [thickbox](http://jquery.com/demo/thickbox/) to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using [galleria](http://devkick.com/lab/galleria/demo_01.htm) a javascript library to display multiple pictures. The problem seems to be that `$(document).ready` in...
I answered a similar question (see [Javascript callback when IFRAME is finished loading?](https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading)). You can obtain control over the iframe load event with the following code: ``` function callIframe(url, callback) { $(document....
Using jQuery 1.3.2 the following worked for me: ``` $('iframe').ready(function() { $('body', $('iframe').contents()).html('Hello World!'); }); ``` REVISION:! Actually the above code sometimes looks like it works in Firefox, never looks like it works in Opera. Instead I implemented a polling solution for my purpose...
jQuery .ready in a dynamically inserted iframe
[ "", "javascript", "jquery", "iframe", "thickbox", "galleria", "" ]
[Spring Workflow](http://www.springsource.org/extensions/se-workflow) has now been published. * Have you tried it yet? For what kind of scenario? * What is your impression? How do you find it stacks up against other workflow libs? * Found any good docs or tutorials?
OK, ignoring my beliefs shown in my previous post I did try spring workflow, only to find out that I was right. Getting the sources and building is not that hard, they use svn, ant and ivy as repository manager. Making it work is another story. I took the sample sources, an placed them in a new project. At this poit I...
I don't think it's a good idea to try it yet, it's just a release to proove the concept. First of all you have to manually build your library, after that, leran how to use it with no example or documentation, just using the scarcely documented code and test code. And when you have an idea about it you realise it can't ...
Have you tried Spring Workflow already?
[ "", "java", "spring", "workflow", "" ]
I'm attempting to get my first ASP.NET web page working on windows using [Mono](http://www.mono-project.com/Main_Page) and the XSP web server. I'm following this chaps [example](http://www.codeproject.com/KB/cross-platform/introtomono2.aspx). The [first part](http://www.codeproject.com/KB/cross-platform/introtomono1.a...
Hey i don't know how to get the "code behind" stuff working but i've found a workaround that i'm happy with. I thought i'd post it up here for the benefit of others. Basically you move the code behind into the main page and it works great just by using the XSD command and no parameters. ``` <%@ Page Language="C#" %> ...
Can you paste the command line you are using to start xsp? If you are just running a single webapp something like this isn't really needed, and could be the source of the problem: xsp --applications /SimpleWebApp:C:\Projects\Mono\ASPExample\ just cd to the ASPExample directory and run xsp with no parameters.
Sample web Page using Mono and XSP on windows box
[ "", "c#", "asp.net", "windows", "mono", "xsp", "" ]
How do I serialize a 'Type'? I want to serialize to XML an object that has a property that is a type of an object. The idea is that when it is deserialized I can create an object of that type. ``` public class NewObject { } [XmlRoot] public class XmlData { private Type t; public Type T { get { r...
XML serialization serializes only the public fields and property values of an object into an XML stream. **XML serialization does not include type information.** For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same typ...
`Type` class cannot be serialized because `System.RuntimeType` is not accessible to our code, it is an internal CLR type. You may work around this by using the type's name instead, like this: ``` public class c { [XmlIgnore] private Type t; [XmlIgnore] public Type T { get { return t; } ...
How to XML Serialize a 'Type'
[ "", "c#", "xml", "serialization", "" ]
There is div named "dvUsers". there is an anchor tag "lnkUsers". When one clicks on anchortag, the div must open like a popup div just below it. Also the divs relative position should be maintained at window resize and all. How to do that using javascript/jquery?
Perhaps you should look for a premade script like **overLIB**: <http://www.bosrup.com/web/overlib/> !-)
My preference is to place both of these inside of a parent div as follows: ``` <div id="container"> <a id="lnkUsers" href="#">Users</a> <div id="dvUsers" style="display: none;"> <!-- user content... --> </div> </div> ``` The CSS for these elements would be: ``` #container{ /* ensure that #dvU...
Relative Positioning of DIV
[ "", "javascript", "jquery", "" ]
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message: > You can either make the non static method static or make an instance of that class to use its properties. **What the reason behind this? Am ...
You can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
The method you are trying to call is an instance-level method; you do not have an instance. `static` methods belong to the class, non-`static` methods belong to instances of the class.
What is the reason behind "non-static method cannot be referenced from a static context"?
[ "", "java", "static", "" ]
I'm currently refactoring code to replace Convert.To's to TryParse. I've come across the following bit of code which is creating and assigning a property to an object. ``` List<Person> list = new List<Person>(); foreach (DataRow row in dt.Rows) { var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) ...
Write an extension method. ``` public static Int32? ParseInt32(this string str) { Int32 k; if(Int32.TryParse(str, out k)) return k; return null; } ```
I'd use an alternative implementation `TryParse` which returns an `int?`: ``` public static int? TryParseInt32(string x) { int value; return int.TryParse(x, out value) ? value : (int?) null; } ``` Then you can write: ``` var p = new Person { RecordID = Helpers.TryParseInt32(row["ContactID"].ToString()) ?? 0 ...
Using TryParse for Setting Object Property Values
[ "", "c#", "exception", "refactoring", "tryparse", "" ]
Say I have this simple form: ``` class ContactForm(forms.Form): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) ``` And I have a default value for one field but not the other. So I set it up like this: ``` default_data = {'first_name','greg'} form1=ContactForm(default_d...
Form constructor has `initial` param that allows to provide default values for fields.
From the django docs is this: ``` from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) ``` The "required=False" should produce the effect you're after.
Django Forms - How to Not Validate?
[ "", "python", "django", "forms", "" ]
In C++, is it possible to have a base plus derived class implement a single interface? For example: ``` class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base { public: virtual void BaseFunction(){} }; class Derived : public Base,...
C++ doesn't notice the function inherited from Base already implements `BaseFunction`: The function has to be implemented explicitly in a class derived from `Interface`. Change it this way: ``` class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class ...
It looks like it's not quite the case that Derived "is-a" Base, which suggests that containment may be a better implementation than inheritance. Also, your Derived member functions should be decalred as virtual as well. ``` class Contained { public: void containedFunction() {} }; class Derived { publ...
C++: Derived + Base class implement a single interface?
[ "", "c++", "class", "inheritance", "interface", "" ]
It doesn't look like basic javascript but nor can I use JQuery commands like `$('myId')`. Is this or similar functions documented anywhere? For reason I don't want to go into, I am not able to use 3rd party libraries like JQuery but if some powerful javascript extensions come with asp then I would like to know about t...
$get is a function from the (now depreciated) ms ajax core javascript library. In the future they will be using jquery therefore $get will just be $('#myid') so I dont understand your feelings about not using jQuery, MS have decided to embrace OpenSource and bundle it with visual studio, check out Scott Gu and Hanslema...
Something to keep in mind is that MS AJAX's $get() function returns the same things as document.getElementById() where as JQuery's $() function returns a special object with different properties and methods. While they are used to select elements in the DOM, the $() is a lot more powerful thanks to jQuery's framework a...
ASP.Net AJAX uses syntax like $get('myId'), is this standard Javascript or JQuery?
[ "", "asp.net", "javascript", "jquery", "asp.net-ajax", "" ]
I have a `JPanel` extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. I have properties to expose in addition to the standard `JPanel` ones and have a custom `p...
I made JPanel component in NetBeans with overridden paint method: ``` @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; ... //draw elements ... } ``` It has some custom properties accessible through NetBeans properties window. ``` public int getResolu...
<http://www.netbeans.org> search for Matisse.
How do I create a custom JPanel extension and use it from the NetBeans palette?
[ "", "java", "swing", "netbeans", "" ]
My class contains a `Dictionary<T, S> dict`, and I want to expose a `ReadOnlyCollection<T>` of the keys. How can I do this without copying the `Dictionary<T, S>.KeyCollection dict.Keys` to an array and then exposing the array as a `ReadOnlyCollection`? I want the `ReadOnlyCollection` to be a proper wrapper, ie. to ref...
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>. So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implem...
DrJokepu said that it might be difficult to implement a wrapper for Keys Collection. But, in this particular case, I think the implementation is not so difficult because, as we know, this is a read-only wrapper. This allows us to ignore some methods that, in other case, would be hard to implement. Here's a quick impl...
How to get a ReadOnlyCollection<T> of the Keys in a Dictionary<T, S>
[ "", "c#", "generics", "dictionary", "collections", "c#-2.0", "" ]
How do I build an escape sequence string in hexadecimal notation. Example: ``` string s = "\x1A"; // this will create the hex-value 1A or dec-value 26 ``` I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B) ``` string s = "\x" + "1B"; // Unrecognized escape sequence ``...
You don't store hexadecimal values in strings. You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value. You can assign a hexadecimal value as a literal to an int or a byte though: ``` Byte value = 0x0FF; int value = 0x1B; ``` So, its easily possible...
Please try to avoid the `\x` escape sequence. It's difficult to read because where it stops depends on the data. For instance, how much difference is there at a glance between these two strings? ``` "\x9Good compiler" "\x9Bad compiler" ``` In the former, the "\x9" is tab - the escape sequence stops there because 'G' ...
C# Build hexadecimal notation string
[ "", "c#", "string", "hex", "" ]
Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from. Is it possible? If not, are there any partial solutions that may help? ...
Use -E : ``` # shows preprocessed source with cpp internals removed g++ -E -P file.cc # shows preprocessed source kept with macros and include directives g++ -E -dD -dI -P file.cc ``` The internals above are line-markers for gcc which are kinda confusing when you read the output. `-P` strips them ``` -E Stop afte...
> I would like to know (when compiling a .cc file) when a #define is encountered, [I know a solution to that](http://blogs.msdn.com/oldnewthing/archive/2008/04/10/8373617.aspx). Compile the file with the symbol already defined as illegal C++ code (the article linked to uses '@'). So, for GCC you would write ``` gcc m...
How to know (in GCC) when given macro/preprocessor symbol gets declared?
[ "", "c++", "gcc", "c-preprocessor", "" ]
What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated) Simply checking for a leading '.' works for \*nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hidi...
We actually address this in a project we write. What we do is have a number of different "hidden file checkers" that are registered with a main checker. We pass each file through these to see if it should be hidden or not. These checkers are not only for different OS's etc, but we plug into version control "ignored" f...
Here's a script that runs on Python 2.5+ and should do what you're looking for: ``` import ctypes import os def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith('.') or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: attrs = ct...
Cross platform hidden file detection
[ "", "python", "cross-platform", "filesystems", "" ]
Is something like the following possible in PHP? ``` $blah = 'foo1'; class foo2 extends $blah { //... } class foo1 { //... } ``` This gives an error. I want to dynamically set $blah so I can extend whatever class I want. **Edit:** The reason for wanting to do this because I wanted to use a function out of...
You're assuming here php executes top to bottom, but it doesn't quite work like that: ``` <?php foo(); # works function foo(){ print "bar"; } ``` --- ``` <?php foo(); #dies if( $i == 1 ) { function foo(){ print "bar"; } } ``` --- ``` <?php $i = 1; if( $i == 1 ) { function foo(){ print "bar"; ...
I know this question was asked a long time ago, but the answer is relatively simple. Assuming you want to extend class foo if class foo exists, or class bar if it doesn't, you'd use: ``` if(!class_exists('foo')) { class foo extends bar { function __construct() { parent::__construct(); ...
Variable variable class extensions in PHP--is it possible?
[ "", "php", "class", "object", "variable-variables", "" ]
I need to read an Excel 2007 XLSX file in a Java application. Does anyone know of a good API to accomplish this task?
AFAIK there are no xlsx-libraries available yet. But there are some for old xls: One library is [jxls](http://jxls.sourceforge.net/) which internally uses the already mentioned [POI](http://poi.apache.org/). 2 other links: [Handle Excel files](http://www.rgagnon.com/javadetails/java-0516.html), [Java libraries to rea...
[Apache POI](http://poi.apache.org/) 3.5 have added support to all the OOXML (docx, xlsx, etc.) See the [XSSF sub project](http://poi.apache.org/spreadsheet/index.html)
Read XLSX file in Java
[ "", "java", "excel", "parsing", "" ]
This very simple code gives me tons of errors: ``` #include <iostream> #include <string> int main() { std::string test = " "; std::cout << test; } ``` I tried to compile it on linux by typing **gcc -o simpletest simpletest.cpp** on the console. I can't see why it isn't working. What is happening?
Try using 'g++' instead of 'gcc'.
To add to what others have said: `g++` is the GNU C++ compiler. `gcc` is the GNU compiler collection (**not** the GNU C compiler, as many people assume). `gcc` serves as a frontend for `g++` when compiling C++ sources. `gcc` can compile C, C++, Objective-C, Fortran, Ada, assembly, and others. The reason why it fails t...
Simple C++ code not working
[ "", "c++", "gcc", "g++", "" ]
Say I have a list of all `Projects`, and that I group them by `Category` like this: ``` var projectsByCat = from p in Projects group p by p.Category into g orderby g.Count() descending select new { Category = g.Key, Projects = g }; ``` Now I want to display ...
If you're using LINQ to SQL or LINQ to Entities you should first fully materialize the results into memory: ``` var oddCategories = projectsByCat.ToList().Where((c,i) => i % 2 != 0); var evenCategories = projectsByCat.ToList().Where((c,i) => i % 2 == 0); ``` It isn't possible to iterate through results on the databa...
Note that calling `.ToList()` twice for the same query is going query the database twice. It would be much better to cache the result in an intermediate list, *then* apply your predicate filtering: ``` var projectsByCat = (from p in Projects group p by p.Category into g orderby g.Count() descending se...
Getting odd/even part of a sequence with LINQ
[ "", "c#", "linq", "" ]
I have a Windows forms project (VS 2005, .net 2.0). The solution has references to 9 projects. Everything works and compiles fine on one of my computers. When I move it to a second computer, 8 out of the 9 project compile with no problem. When I try to compile the 9th project (the main project for the application - pro...
I just got it to build by doing the following: There had been a licenses file in the Properties of the project in question. After deleting the file (it was no longer needed) the project was able to build successfully. So it looks like that was the culprit.
## What the error means *"Strong Name : Indicates that the reference has been signed with a key pair."* If your current project's assembly is signed, then all your reference assemblies **must** also be signed. **Failure to do so will result in this error.** --- ## How to check Solution Explorer > References > [Cli...
Error: A strongly-named assembly is required
[ "", "c#", ".net", "" ]
I have a block of code that works and I wanted to ask what exactly is happening here? ``` Class<?> normalFormClass = null; ``` ---added--- The wildcard "`<?>`" is the part that is confusing for me. Why would this be used rather than not using it (generics)?
That means it can be a Class of any type. ? is a wildcard denoting the set of all types, or 'any'. So you can later do ``` Integer normalForm = new Integer(); normalFormClass = normalForm.getClass(); ``` or ``` String normalForm = new String(); normalFormClass = normalForm.getClass(); ``` If you are not aware of ge...
Also, the generic version ``` Class<?> normalClass = null; ``` is pretty much equivalent to the raw type version, ``` Class normalClass = null; ``` the main difference is that the latter will be compatible with versions of Java that do not support generics, like Java 1.4.
Java Class Type
[ "", "java", "generics", "" ]
Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?
Your best bet is probably to run the java interpreter within a loop, and just exit. For example: ``` #!/bin/sh while true do java MainClass done ``` If you want the ability to reboot or shutdown entirely, you could test the exit status: ``` #!/bin/sh STATUS=0 while [ $STATUS -eq 0 ] do java MainClass STA...
IBM's JVM has a feature called "resettable" which allows you to effectively do what you are asking. <http://publib.boulder.ibm.com/infocenter/cicsts/v3r1/index.jsp?topic=/com.ibm.cics.ts31.doc/dfhpj/topics/dfhpje9.htm> Other than the IBM JVM, I don't think it is possible.
Any way to "reboot" the JVM?
[ "", "java", "jvm", "" ]
I am building a WPF application. Inside that application I am using the XmlReader class to parse several local XML files. The code I have written **works perfectly** during debugging, but fails once I publish the application and install it. I have the XML documents as CONTENT in build action, and I have them set to CO...
By your publish description I assume you are using clickonce to install the application. Clickonce has different default behavior for xml files - it assumes they are data files and places them in a different install location from your other files. Please double check that your xml files really are being installed whe...
Can you describe "but fails once I publish the application and install it" ? It would be helpful if you could describe what doesn't work, what the error is and provide exception information. --- Unrelated to your question, I cringe in horror every time I see empty catch blocks in production code!!
Parsing a local XML Document in WPF (works in debug, fails once published)
[ "", "c#", "wpf", "xml", "" ]
I'm working on a program that searches entire drives for a given file. At the moment, I calculate an MD5 hash for the known file and then scan all files recursively, looking for a match. The only problem is that MD5 is painfully slow on large files. Is there a faster alternative that I can use while retaining a very s...
I hope you're checking for an MD5 match only if the file size already matches. Another optimization is to do a quick checksum of the first 1K (or some other arbitrary, but reasonably small number) and make sure those match before working the whole file. Of course, all this assumes that you're just looking for a match...
Regardless of cryptographic requirements, the possibility of a hash collision exists, so no hashing function can be used to *guarantee* that two files are identical. I wrote similar code a while back which I got to run pretty fast by indexing all the files first, and discarding any with a different size. A fast hash c...
Faster MD5 alternative?
[ "", "c#", "md5", "hash", "" ]
The JUnit framework contains 2 `Assert` classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is? The classes I'm referring to are: [`junit.framework.Assert`](http://junit.org/junit/javadoc/4.5/junit/framework/Assert.html) and [`org.junit.Assert`](ht...
The old method (of JUnit 3) was to mark the test-classes by extending `junit.framework.TestCase`. That inherited `junit.framework.Assert` itself and your test class gained the ability to call the assert methods this way. Since version 4 of JUnit, the framework uses `Annotations` for marking tests. So you no longer nee...
JUnit 3.X: `junit.framework.Assert` JUnit 4.X: `org.junit.Assert` Prefer the newest one, especially when running JDK5 and higher with annotation support.
differences between 2 JUnit Assert classes
[ "", "java", "unit-testing", "junit", "junit4", "assert", "" ]
I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended? I have tried this with a function returning a string and it did work. Can anyone e...
> When the function terminates, the > following steps happen: > > * The function’s return value is > copied into the placeholder that was > put on the stack for this purpose. > * Everything after the stack frame > pointer is popped off. This destroys > all local variables and arguments. > * The return value is ...
It really depends on what kind of variable you are returning. If you return a primitive then it is returned by copy, not by reference so the value is copied to the top of the stack (or, more often placed into a register) where the calling function can get it. If you allocate an object or memory on the heap and return a...
Scope and return values in C++
[ "", "c++", "return-value", "scope", "" ]
I have an application which I have made a 256 x 256 Windows Vista icon for. I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form. I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection. I am...
Today, I made a very nice function for **extracting the 256x256 Bitmaps from Vista icons**. Like you, Nathan W, I use it to display the large icon as a Bitmap in "About" box. For example, this code gets Vista icon as PNG image, and displays it in a 256x256 PictureBox: ``` picboxAppLogo.Image = ExtractVistaIcon(myIcon...
Found info [here](http://www.geekpedia.com/tutorial219_Extracting-Icons-from-Files.html). To get the large Vista icon, you need to use Shell32's SHGetFileInfo method. I've copied the relevant text below, of course you'll want to replace the filename variable with "Assembly.GetExecutingAssembly().Location". ``` using S...
Using a 256 x 256 Windows Vista icon in an application
[ "", "c#", "vb.net", "png", "icons", "" ]
I need to generate random numbers within a specified interval, [max;min]. Also, the random numbers should be uniformly distributed over the interval, not located to a particular point. Currenly I am generating as: ``` for(int i=0; i<6; i++) { DWORD random = rand()%(max-min+1) + min; } ``` From my tests, random ...
## Why `rand` is a bad idea Most of the answers you got here make use of the `rand` function and the modulus operator. That method [may not generate numbers uniformly](https://learn.microsoft.com/en-us/events/goingnative-2013/rand-considered-harmful) (it depends on the range and the value of `RAND_MAX`), and is theref...
**Warning: Do not use `rand()` for statistics, simulation, cryptography or anything serious.** It's good enough to make numbers *look* random for a typical human in a hurry, no more. See [Jefffrey's reply](https://stackoverflow.com/a/20136256/4513656) for better options, or [this answer](https://stackoverflow.com/a/2...
Generate random numbers uniformly over an entire range
[ "", "c++", "random", "" ]
Once a programmer decides to implement `IXmlSerializable`, what are the rules and best practices for implementing it? I've heard that `GetSchema()` should return `null` and `ReadXml` should move to the next element before returning. Is this true? And what about `WriteXml` - should it write a root element for the object...
Yes, GetSchema() [should return null](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.getschema.aspx). > IXmlSerializable.GetSchema Method This > method is reserved and should not be > used. When implementing the > IXmlSerializable interface, you should > return a null reference (Noth...
I wrote one article on the subject with samples as the MSDN documentation is by now quite unclear and the examples you can find on the web are most of the time incorrectly implemented. Pitfalls are handling of locales and empty elements beside what Marc Gravell already mentioned. <http://www.codeproject.com/KB/XML/Im...
Proper way to implement IXmlSerializable?
[ "", "c#", "xml", "xml-serialization", "" ]
Writing a JSP page, what exactly does the `<c:out>` do? I've noticed that the following both has the same result: ``` <p>The person's name is <c:out value="${person.name}" /></p> <p>The person's name is ${person.name}</p> ```
`c:out` escapes HTML characters so that you can avoid cross-site scripting. if `person.name = <script>alert("Yo")</script>` the script will be executed in the second case, but not when using `c:out`
As said Will Wagner, in old version of jsp you should always use `c:out` to output dynamic text. Moreover, using this syntax: ``` <c:out value="${person.name}">No name</c:out> ``` you can display the text "No name" when name is null.
JSP : JSTL's <c:out> tag
[ "", "java", "jsp", "jstl", "tags", "" ]
I work on a medium sized development team that maintains a 8+ years old web application written in Java 1.4. For new development I always try to convince people to adhere to newer standards and best practices, That goes from simple things like using new naming standards like HtmlImplementation over HTMLImplementation,...
Check out these links : * [Best Practice Software Engineering](http://best-practice-software-engineering.ifs.tuwien.ac.at/) (more in depth) * [Software Engineeting Best Practices](http://prof.tfh-berlin.de/edlich/lecture-results/swt-best-practices/) (lists briefly out some practices and tools by name) One book (that ...
I really don't think there's anything in the same league as Effective Java. The cost of buying a book is much smaller than the developer time spent reading it (or other material anyway) - so I would strongly recommend going for EJ rather than trying to find anything similar. There may be an online version of Effective...
Can you help me gather a Java Best Practices online material collection?
[ "", "java", "reference", "" ]
This works, but is it the proper way to do it??? I have a custom server control that has an [input] box on it. I want it to kinda mimic the ASP.NET TextBox, but not completely. When the textbox is rendered i have a javascript that allows users to select values that are then placed in that input box. I have a public t...
I find using IStateManager works the best. For example: ``` partial class MyControl : System.Web.UI.UserControl, IStateManager { [Serializable()] protected struct MyControlState { public bool someValue; public string name; } protected MyControlState state; public bool someVal...
If you need to maintain state on postback, you must provide your own methods of recording what the user has done with your control on the client side and either update the server control later on the server with the changes, or redo the changes on the client side when the page refreshes.
What is the proper way to maintain state in a custom server control?
[ "", "c#", "asp.net", "custom-server-controls", "servercontrols", "" ]
Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window). A little Googling on the subject offers a few sugg...
On recent Python (> 2.7) versions, you can use the [`ttk`](https://docs.python.org/2/library/ttk.html) module, which provides access to the *Tk themed widget* set, which has been introduced in `Tk 8.5`. Here's how you import `ttk` in Python 2: ``` import ttk help(ttk.Notebook) ``` In Python 3, the [`ttk`](https://d...
If anyone still looking, I have got this working as Tab in tkinter. Play around with the code to make it function the way you want (for example, you can add button to add a new tab): ``` from tkinter import * class Tabs(Frame): """Tabs for testgen output""" def __init__(self, parent): super(Tabs, se...
Notebook widget in Tkinter
[ "", "python", "wxpython", "tabs", "tkinter", "" ]
let me tell you a bit about where this question came from. I have been playing around with the SDK of Serious Sam 2, a first person shooter which runs on the Serious Engine 2. This engine introduces something called MetaData. MetaData is used in the engine to serialize classes and be able to edit them in the editor env...
This looks somewhat similar to Qt's moc (meta object compiler). In Qt's case, it generates extra C++ source files which are then compiled and linked together with the original source files. A possible implementation in your example would be for the generated files to implement a set of functions which can be called to...
To get a definitive answer, study the [PE File Format](http://en.wikipedia.org/wiki/Portable_Executable). This is the low level file format for binaries on Win32. ie. DLLs, EXEs, COM, etc. There are many books that discribe PE File layout and features. And many tools that allow you to explore it. The short answer is ...
Saving extra data in a dll, how did they do it?
[ "", "c++", "serialization", "" ]
So I've got a program that needs to be multilingual. The only difference between what I'm needing and what I've found on the web is that all the computers my program will run on are set to the localization of EN. We have spanish speaking employees that will use the program just like the english speaking employees. So ...
You can set the culture you want in code, e.g.: ``` Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES"); ``` See [this MSDN article](http://msdn.microsoft.com/en-us/library/b28bx3bh(VS.80).aspx) for more info.
It is a pain, but its not hard. Within VS2008's WinForm designer, select the form, view its properties and set Localizable=True (if you view the partial class/code behind file you will see a new line that looks something like ``` resources.ApplyResources(this, "$this") ``` Then, for each locale you want to support,...
Multilingual Winforms in .Net - opinions and suggestions
[ "", "c#", "winforms", "multilingual", "" ]
How can I generate valid XML in C#?
It depends on the scenario. `XmlSerializer` is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, `XDocument`, etc. are also very friendly. If the size is very large, then `XmlWriter` is your friend. For an `XDocument` example: ``` Console.WriteLine( new XElement("Foo", ...
The best thing hands down that I have tried is [LINQ to XSD](http://linqtoxsd.codeplex.com/) (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and...
How can I build XML in C#?
[ "", "c#", "xml", "" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
You're looking for calls to `sys.exit()` (`exit()` calls `sys.exit()`) in the script. The argument to that method is returned to the environment as the exit code. It's fairly likely that the script is never calling the *exit* method, and that 0 is the default exit code.
From the documentation for [`sys.exit`](https://docs.python.org/2/library/sys.html#sys.exit): > The optional argument arg can be an > integer giving the exit status > (defaulting to zero), or another type > of object. If it is an integer, zero > is considered “successful termination” > and any nonzero value is conside...
Exit codes in Python
[ "", "python", "exit-code", "" ]
I have a form that contains a bunch of checkboxes. Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that. So I might have: Red Orange X Yellow Blue X Green And I'd like my textfield to end up with the content "Yellow, Green" . This doesn't seem t...
Just use this code: ``` $(function(){ $('#YourFormID').bind('submit',function(){ var serializedCheckboxes = ''; $("input[type=checkbox]").each(function() { if($(this).attr("checked")) { serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value"); ...
First hack at it (without testing): ``` var serializedCheckboxes = ''; $("input type='checkbox'").each(function() { if($(this).attr("checked")) { serializedCheckboxes += $(this).attr("value") + ','; } }); $("input name='allchecks').attr("value", serializedCheckboxes); ```
How to use jQuery to grab the values of checkboxes and spit them into a different form field
[ "", "javascript", "jquery", "forms", "" ]
I am trying to use the Event Log to write some debug information and I can't make it works. It complains about not being able to find the Event Source. Do I have to install something on the OS?
Here a code that I modified from one of our application. This might help you to start with the creation. ``` System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog(); string eventLogName = "StackOverFlowEventName"; string eventLogSource = "StackOverFlowWebsite"; //This code HERE will create the Event...
What code are you using currently in your project? I'm currently using this line to write to the event log. ``` System.Diagnostics.EventLog.WriteEntry(assemblyName, "Error stuff", System.Diagnostics.EventLogEntryType.Error); ``` Watch out though, this will throw an exception if the log file is full
Event log code error not being able to find the Event Source?
[ "", "c#", "events", "c#-2.0", "" ]
I'm trying to get the following SQL statement to work: ``` UPDATE myschema.tableA update_tableA SET field_id = ( SELECT src.field_id FROM myschema.srcTable src INNER JOIN myschema.tableB tableB ON update_tableA.id = tableB.id AND SDO_ANYINTERACT( tableB.shape, src.sh...
I don't believe you can JOIN on a column (i.e. use it in the ON clause) that's not in one of the tables being joined. Additional predicates need to be in a WHERE clause. Try this: ``` UPDATE myschema.tableA update_tableA SET field_id = ( SELECT src.field_id FROM myschema.srcTable src INNER J...
Looking at the SQL above, here is what I am thinking 1) myschema.tableA doesn't have ID column (it could be field\_id) 2) The SELECT doesn't seem to provide a join condition `SELECT src.field_id FROM myschema.srcTable src INNER JOIN myschema.tableB tableB ON` Where is the condition to JOIN src with tableB?
In SQL, can I use a variable scoped outside a nested select within the nested select itself?
[ "", "sql", "oracle", "ora-00904", "" ]
I have an `ICollection<T>` called `foos` in my class which I want to expose as read-only (see [this question](https://stackoverflow.com/questions/284090/how-to-get-a-readonlycollectiont-of-the-keys-in-a-dictionaryt-s)). I see that the interface defines a property `.IsReadOnly`, which seems appropriate... My question is...
I seem to have settled on returning IEnumerable **with the objects cloned.** ``` public IEnumerable<Foose> GetFooseList() { foreach(var foos in Collection) { yield return foos.Clone(); } } ``` * requires a Clone method on Foos. This allows no changes in the collection. Remember that ReadonlyCollection is ...
You can make "foos" a ReadOnlyCollection like this: ``` ReadOnlyCollection<T> readOnlyCollection = foos.ToList<T>().AsReadOnly(); ``` Then you can expose it as a property of your class. EDIT: ``` class FooContainer { private ICollection<Foo> foos; public ReadOnlyCollection<Foo> ReadOnlyFoos ...
Best practice: How to expose a read-only ICollection
[ "", "c#", "collections", "c#-2.0", "" ]
I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle. Briefly: It's simple tool that lets people download files once they login with a password. So my questions are: 1) How should I handle configuration values? I'...
# Configuration You can use a php file like this: ``` <?php return array( 'option1' =&gt; 'foobar', 'option2' =&gt; 123, //and so on... ); ?> ``` And in the main class just use: ``` $config = (array) include 'path/to/config/file'; ``` And if you plan to mostly distribute your class as a component in other ...
1. Can config be local to class instances? Or could you create a little class that you could create an instance of to query for config values? Also prepending any global vars with you application's name should go some way to stop clashes. 2. If your templating is really simple, just write a short templater. It'll be ea...
Distributing a small PHP application
[ "", "php", "distribution", "" ]
I'm learning c# , and I reached the LinkedList<T> type and I still need to know more, like when should I use it, how do I create one, how do I to use it. I just want information. If any one knows a good article about this subject, or if you can show me some examples with explanation, such as how to create, how to add ...
You can find more information on [LinkedList<T>](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx) at MSDN, including an example of how to create and use one. [Wikipedia](http://en.wikipedia.org/wiki/Linked_list) has a reasonable article on linked lists, including their history, usage, and some implementation deta...
Linked is a collection to store sequences of values of the same type, which is a frequent task, e.g. to represent a queue of cars waiting at a stoplight. There are many different collection types like linked list, array, map, set etc. Which one to use when depends on their properties, e.g.: * do you need some type of...
I want to know more about LinkedList<T>
[ "", "c#", "linked-list", "" ]
I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags. ``` Dim oXmlSettings As Xml.XmlReaderSettings = New Xml...
Probably the library parses the DOCTYPE element into an internal structure and then converts the structure back to text. It doesn't store the original string form.
There is a bug in System.Xml when you set XmlDocument.XmlResolver = null. The workaround is to create a custom XmlTextWriter: ``` private class NullSubsetXmlTextWriter : XmlTextWriter { public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding) : base(inputFileName, encoding) ...
.NET XmlDocument : Why DOCTYPE changes after Save?
[ "", "c#", "xml", "vb.net", "doctype", "xmldocument", "" ]
I have an auditing trigger that automatically places the time something was updated and the user that updated in fields in all my tables. I have another set of triggers that write event information from updates to an events table. The issue is when someone updates something, the event information is fired twice because...
Look into TRIGGER\_NESTLEVEL function. It returns the current level of trigger nesting. You can check that to prevent the duplicates.
I guess you have 2 choices: 1. Either combine both sets of triggers into one. 2. Or, there is a per database setting that allows recursive firing of triggers to be disabled.
SQL Server Triggers Firing Each other Question
[ "", "sql", "triggers", "" ]
When Xdebug is installed/enabled, standard PHP errors (when set to display in the browser) are replaced with more informative messages that include stack traces for each. Also, I've noticed that it also seems to improve output in other areas such as the var\_dump() function, formatting/color-coding the output to make i...
As for your debugging you'll only find access through PHP extensions, regardless of what IDE you are using. Xdebug is the most popular due to it's extra features, beyond that of what you've even described. Xdebug will do profiling (tracing) into the valgrind format that you can use programs like Kcachegrind and wincac...
dBug offers quite a nice replacement for print\_r: <http://dbug.ospinto.com/>
Other packages with Xdebug-like features (informative PHP errors, formatted var_dump()s, etc.)?
[ "", "php", "xdebug", "" ]
Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow. Is this something I should try to farm out ...
You could try the [Microsoft Windows MultiPoint Software Development Kit 1.1](http://www.microsoft.com/downloads/details.aspx?familyid=F851122A-4925-4788-BC39-409644CE0F9B&displaylang=en) or the new [Microsoft Windows MultiPoint Software Development Kit 1.5](http://www.microsoft.com/downloads/details.aspx?FamilyID=0eb...
Yes. I know of at least one program that does this, [KidPad](http://www.cs.umd.edu/hcil/kiddesign/introduction.shtml). I think it's written in Java and was developed by [Juan Pablo Hourcade](http://www.cs.uiowa.edu/~hourcade/), now at the University of Iowa. You'd have to ask him how it was implemented.
Multiple mouse pointers?
[ "", "python", "user-interface", "mouse", "multi-user", "" ]
I normally use the following idiom to check if a String can be converted to an integer. ``` public boolean isInteger( String input ) { try { Integer.parseInt( input ); return true; } catch( Exception e ) { return false; } } ``` Is it just me, or does this seem a bit hackish? Wh...
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using `Integer.parseInt()`. ``` public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false;...
You have it, but you should only catch `NumberFormatException`.
What's the best way to check if a String represents an integer in Java?
[ "", "java", "string", "int", "" ]
I am just getting started with IoC containers so apologies if this is a stupid question. I have code like the following in an app ``` internal static class StaticDataHandlerFactory { public static IStaticDataHandler CreateHandler(StaticDataUpdate staticDataUpdate) { if (staticDataUpdat...
Actually, although it is possible to replace some of the code with an inversion of control system, it's not obvious to me it's a good idea. Dependency injection tends to be best for configuration of systems, not dynamic creation of objects. To put it a different way, the container itself is a huge global variable and a...
You're not far off course at all; the way I understand it, you're pretty close. The way I would most commonly structure this sort of thing is to turn your Factory class into your IoC container, simply by allowing the UpdateHandlers that are returned to be specified using Dependency Injection. So instead of having the ...
Does an IoC container replace the use of Factories
[ "", "c#", "inversion-of-control", "factory", "" ]
I have an input which at some points happens to have the focus. If the user click in the "background" of the page, the input loses its focus. I was trying to simulate the click on the background with the following code, but this doesn't work (you will notice that the input still has the focus). Any suggestion on how to...
I would imagine using `blur()` would do the trick: ``` <script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() { document.getElementById("input").focus(); document.getElementById("input").blur(); }); </script> ```
Try using the `blur` event. If you're using jQuery there is a method you can call on the DOM object to raise this event. The `blur()` method should also work without jQuery. <http://docs.jquery.com/Events/blur>
How to simulate a click to make the current input lose its focus with JavaScript
[ "", "javascript", "focus", "yui", "" ]
I'm using Emacs with [C# Mode](http://mfgames.com/linux/csharp-mode) and when I turn on the speedbar, no files show up by default. I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name. How do I properly configure speedbar so it shows up with .cs files by def...
I think ECB with CEDET is simply too bloated. I use speedbar alone with emacs and I use the original parser for C/C++. Just add this line to your .emacs and you'll be ok: ``` (speedbar-add-supported-extension ".cs") (add-to-list 'speedbar-fetch-etags-parse-list '("\\.cs" . speedbar-parse-c-or-c++tag)...
I used speedbar earlier and got really irritated. I now use [ECB](http://ecb.sourceforge.net/). [ECB](http://ecb.sourceforge.net/) uses its own buffer for the tree and can optionally show the outline of the CS file in a separate buffer. They all fit in the same frame while Speedbar has its own frame. I have some [cust...
How do I configure Emacs speedbar for C# mode?
[ "", "c#", "emacs", "" ]
Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.
## Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a sing...
We use it with custom memory pools. Just a sketch: ``` class Pool { public: Pool() { /* implementation details irrelevant */ }; virtual ~Pool() { /* ditto */ }; virtual void *allocate(size_t); virtual void deallocate(void *); static Pool *Pool::misc_pool() { return misc_pool_p; /* global MiscPool...
What uses are there for "placement new"?
[ "", "c++", "memory-management", "new-operator", "placement-new", "" ]
If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.) Elementary example: ``` ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails() { //Do stuff to members of MyClass that never...
If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked. If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its cod...
They most likely will if the optimization level causes them to inline the code. If not, they would have to generate two different translations of the same code to make it work, which could open up a lot of edge case problems.
Will the c++ compiler optimize away unused return value?
[ "", "c++", "visual-c++", "gcc", "compiler-construction", "return", "" ]
I would like to add a backcolor for specific line depending of a Property of the object binded. The solution I have (and it works) is to use the Event `DataBindingComplete` but I do not think it's the best solution. Here is the event: ``` private void myGrid_DataBindingComplete(object sender, DataGridViewBinding...
You can also attach an event handler to RowPostPaint: ``` dataGridView1.RowPostPaint += OnRowPostPaint; void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem; DataGridViewCellStyle style = dataGridView1.Rows[e.RowInde...
I would suggest a few things: * look at modifying your rows at \_OnRowDatabound * Do not set color in your code!!! This would be a big mistake. Use the attributes property and set the cssclass. Wag of the finger to people still doing this. Let me know if you struggle with the implementation and i'll post a snippet.
(DataGridView + Binding)How to color line depending of the object binded?
[ "", "c#", ".net", "winforms", ".net-2.0", "c#-2.0", "" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class ...
A bit reversed, but this should work: ``` def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 ``` If you want the counter initialization code at the top instead of the bottom, you can create a decorator: ``` def static_vars(**kwargs): def decorate(func): for k in kwarg...
You can add attributes to a function, and use it as a static variable. ``` def myfunc(): myfunc.counter += 1 print myfunc.counter # attribute must be initialized myfunc.counter = 0 ``` Alternatively, if you don't want to setup the variable outside the function, you can use `hasattr()` to avoid an `AttributeError...
What is the Python equivalent of static variables inside a function?
[ "", "python", "static", "" ]
I'm a big fan of [simpletest](http://www.simpletest.org/) because it's what I know. It has excellent support for mocking and web-testing. But I'm always scared of stagnating so any compelling arguments to switch would be appreciated.
I don't think either is going away anytime soon. Simpletest is maintained by a small, but involved group of people. PHPUnit seems to have a bigger userbase, which may count as an argument for switching. I'm quite happy with Simpletest though.
I haven't used SimpleTest myself, so I can't say much in a way of comparison. Just by observation though, the PHPUnit syntax seems much more verbose. The [PHPUnit Manual](http://www.phpunit.de/pocket_guide/3.3/en/index.html) is a great source of documentation, and covers most areas of the framework. My only complaint ...
which unit-test framework for PHP: simpletest, phpunit or?
[ "", "php", "unit-testing", "phpunit", "simpletest", "" ]
I am setting-up my DataGridView like this: ``` jobs = new List<DisplayJob>(); uxJobList.AutoGenerateColumns = false; jobListBindingSource.DataSource = jobs; uxJobList.DataSource = jobListBindingSource; int newColumn; newColumn = uxJobList.Columns.Add("Id", "Job No."); ...
If you want to support sorting and searching on the collection, all **it takes it to derive a class from your BindingList parameterized type**, and override a few base class methods and properties. The best way is to extend the BindingList and do those following things: ``` protected override bool SupportsSearchingCo...
Daok's solution is the right one. It's also very often more work than it's worth. The lazy man's way to get the functionality you want is to create and populate a DataTable off of your business objects, and bind the DataGridView to that. There are a lot of use cases that this approach won't handle (like, editing), an...
DataGridView Column sorting with Business Objects
[ "", "c#", ".net", "datagridview", "" ]
We have an application that generates simulated data for one of our services for testing purposes. Each data item has a unique Guid. However, when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid. There was a single data object created, then a for loop w...
Does Submit do an async call, or does the ticket object go into another thread at any stage. In the code example you are reusing the same object. What if Submit sends the ticket in a background thread after a short delay (and does not take a copy). When you change the CacheId you are actually updating all the pending ...
Thousands of developers use Guids in .NET. If Guid.NewGuid() had any tendency at all to get "stuck" on one value, the problem would have been encountered long ago. The minor code changes are the sure culprit here. The fact that [Thread.Sleep](https://stackoverflow.com/questions/143429/whats-the-least-useful-comment-yo...
Duplicate returned by Guid.NewGuid()?
[ "", "c#", "guid", "" ]
I sign up Spring courses tomorrow morning (transferring in to the Computer Science program). Since I'm a transfer student, I get the last pick of leftover classes not already taken. Emphasis on 'last pick' and 'leftover'. It's highly probable that whatever classes I intend on picking tomorrow, I might not even get beca...
**Selenium** can automate most browser based tasks. <http://selenium.seleniumhq.org/> **The Grinder** comes with a local proxy that can record traffic and is scriptable with Python. <http://grinder.sourceforge.net/>
I would highly suggest you check out your university's *acceptable use policy*, at mine, such a thing would be considered a serious infraction and possibly get you kicked out.
Script for College Class Registration
[ "", "javascript", "" ]
How come the following doesn't work? ``` CREATE FUNCTION Test (@top integer) RETURNS TABLE AS RETURN SELECT TOP @top * FROM SomeTable GO ``` I just want to be able to be able to specify the number of results to be returned. [SQL Server 2000.] Thanks!
For MS SQL 2000, you can use: ``` CREATE FUNCTION Test (@top integer) RETURNS TABLE AS SET ROWCOUNT @top RETURN SELECT * FROM SomeTable ```
Support for this was added to SQL Server 2005, but it's not available in 2000. You'd have to use (shudder) dynamic sql or some other number trick instead.
SQL User-Defined Functions: Fetching TOP n records in a user-defined function
[ "", "sql", "sql-server", "sql-server-2000", "user-defined-functions", "" ]
I'm trying to perform a simple LINQ query on the Columns property of a DataTable: ``` from c in myDataTable.Columns.AsQueryable() select c.ColumnName ``` However, what I get is this: > Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider exp...
How about: ``` var x = from c in dt.Columns.Cast<DataColumn>() select c.ColumnName; ```
With Linq Method Syntax: ``` var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName); ```
Querying DataColumnCollection with LINQ
[ "", "c#", "linq", "datatable", "asqueryable", "datacolumncollection", "" ]
I have a few questions related: 1) Is possible to make my program change filetype association but only when is running? Do you see anything wrong with this behavior? 2) The other option that I'm seeing is to let users decide to open with my application or restore default association ... something like: "capture all ....
Regarding file associations, I've wrote an answer earlier that at least [covers the "How"](https://stackoverflow.com/questions/212906/script-to-associate-an-extension-to-a-program#212921). This should also point you to the right direction how to handle backup and restore. With direct registry access through c#, there ...
You can implement an "on the fly" file association change by associating a small executable with that file extension that upon start will check if your main application is running and pass the file name to it or if it's not running it'll invoke the "regular" associated application. The main advantage of this approach ...
Filetype association with application (C#)
[ "", "c#", ".net", "registry", "file-type", "" ]
I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like... ``` DataView dvOptions = new DataView(DataTableWithOptions); dvOptions.Sort = "Description"; ddlOptions.DataSource = dvOptions; ddlOptions.DataTextField = "Descr...
A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI): ``` public static void ReorderAlphabetized(this DropDownList ddl) { List<ListItem> listCopy = new List<ListItem>(); foreach (ListItem item in ddl.Items) listCopy.Add(item); ddl.Items.Clear(); foreach (...
Sorting a DropDownList? - C#, ASP.NET
[ "", "c#", "asp.net", "drop-down-menu", "" ]
I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class? Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate? The p...
Multiple threads would share an instance. For this reason a static class can be convenient for passing state between threads, but you need to be very careful not to introduce race conditions (`Monitor` or `lock` your properties). However, multiple *processes* should be in separate AppDomains and therefore each have th...
Static classes exist once per application domain. In your case, it would depend on whether the adapter is using multiple threads in the same application domain (thus sharing a single instance of the static class) or using multiple processes (thus having separate instances of the static class).
What is the scope of a Static Class?
[ "", "c#", "static", "biztalk", "applicationdomain", "" ]
So here's my current code: ``` List<string> rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value); bool found = false; System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()); foreach (string group in row...
Well, to fix the problem I just had to specifically add each user of the group instead of the group name.
I have to point out, are you actually escaping your '\' character correctly inside your strings? As in "domainA\\groupA"?
WindowsPrincipal.IsInRole() not returning the expected result
[ "", "c#", "security", "active-directory", "security-roles", "iprincipal", "" ]
For my application there are several entity classes, User, Customer, Post, and so on I'm about to design the database and I want to store the date when the entities were created and updated. This is where it gets tricky. Sure one option is to add created\_timestamp and update\_timestamp columns for each of the entity ...
The single-log-table-for-all-tables approach has two main problems that I can think of: 1. The design of the log table will (probably) constrain the design of all the other tables. Most likely the log table would have one column named TableName and then another column named PKValue (which would store the primary key v...
I do the latter, with a "log" or "events" table. In my experience, the "updated" timestamp becomes frustrating pretty quick, because a lot of the time you find yourself in a fix where you want not just the very latest update time.
SQL - Table Design - DateCreated and DateUpdated columns
[ "", "sql", "timestamp", "insert-update", "" ]
The [jQuery documentation](http://docs.jquery.com/Events/bind#typedatafn) says the library has built-in support for the following events: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, key...
You can add and remove events of any kind by using the [`.on()`](http://api.jquery.com/on/) and [`off()`](http://api.jquery.com/off) methods Try this, for instance ``` jQuery(document).on('paste', function(e){ alert('pasting!') }); ``` jQuery is actually quite indifferent to whether the event type you assign is supp...
Various clipboard events are available in Javascript, though support is spotty. QuicksMode.org has a [compatibility grid](http://www.quirksmode.org/dom/events/cutcopypaste.html) and [test page](http://www.quirksmode.org/dom/events/tests/cutcopypaste.html). The events are not exposed through jQuery, so you'll either hav...
How do you handle oncut, oncopy, and onpaste in jQuery?
[ "", "javascript", "jquery", "event-handling", "webkit", "" ]
When I create a new `Date` object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?
`java.util.Date` has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time? To be precise: the value within a `java.util.Date` is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch...
# tl;dr ``` Instant.now() // Capture the current moment in UTC. ``` Generate a String to represent that value: ``` Instant.now().toString() ``` > 2016-09-13T23:30:52.123Z # Details As [the correct answer by Jon Skeet](https://stackoverflow.com/a/308689/642706) stated, a java.util.Date object has **no time zone*...
How can I get the current date and time in UTC or GMT in Java?
[ "", "java", "date", "localization", "timezone", "gmt", "" ]
I'm looking for a QR-Code library for C/C++, not Java or .Net please. Anyone knows of one? Note: There was a [similar question](https://stackoverflow.com/questions/231741/qr-code-2d-barcode-coding-and-decoding-algorithms) a while back however but it didn't get answered properly.
How is this one? <http://megaui.net/fukuchi/works/qrencode/index.en.html>
The [zxing library](http://code.google.com/p/zxing) is primarily Java, but, includes a [port of the QR Code detector and decoder to C++](http://code.google.com/p/zxing/source/browse/#svn/trunk/cpp).
Does anyone know of a C/C++ Unix QR-Code library?
[ "", "c++", "c", "qr-code", "" ]
`Html.TextBox("ParentPassword", "", new { @class = "required" })` what the gosh darned heck is the @ for the @class.
`class` is a reserved keyword, so you can't use this as a variable name. The @ operator allows you to get around this rule. The reason why its being done here is that the anonymous object is used to populate attributes on a HTML element. A valid attribute name is "class", which lets you set the CSS class on the elemen...
`class` is a keyword. To use `class` as the name of a variable/property, in C#, you can prepend `@` to it, as `@class`. In the IL, for all .net is concerned, the name of the variable/property is still `class` - `@` is the way you have to do it in C#.
What does the @ in this code sample mean?
[ "", "c#", ".net", "variables", "keyword", "variable-names", "" ]
I'm constructing a method to take in an ArrayList(presumably full of objects) and then list all the fields(and their values) for each object in the ArrayList. Currently my code is as follows: ``` public static void ListArrayListMembers(ArrayList list) { foreach (Object obj in list) { T...
``` foreach (Object obj in list) { Type type = obj.GetType(); foreach (var f in type.GetFields().Where(f => f.IsPublic)) { Console.WriteLine( String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj)); } } ``` Note that this code requires .NET 3.5 to work...
You can obtain all the object Fields declared directly in the class with the BindingFlags: ``` GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) ``` and all object Fields including inherited with: ``` GetFields(BindingFlags.Public | BindingFlags.Instance) ```
How can I find all the public fields of an object in C#?
[ "", "c#", "object", "field", "public", "" ]
At my workplace, we tend to use **iostream**, **string**, **vector**, **map**, and the odd **algorithm** or two. We haven't actually found many situations where template techniques were a best solution to a problem. What I am looking for here are ideas, and optionally sample code that shows how you used a template tec...
I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to *write* any. One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the `ExeFile` class that I'd written to handle the files only wo...
**General info on templates:** Templates are useful anytime you need to use the same code but operating on different data types, where the types are known at compile time. And also when you have any kind of container object. A very common usage is for just about every type of data structure. For example: Singly linke...
Where do you find templates useful?
[ "", "c++", "templates", "metaprogramming", "generic-programming", "" ]
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do ``` Obj *obj = libname_newDevice(); ``` Now, should I use delete or should I do `obj->deleteMe();`? I ask because I am not exactly doing...
I would take one step further. If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object. ``` class ObjWrap { public: ObjWrap() :obj(libname_newDevice()) {} ...
Since you are abstracting the creation inside `libname_newDevice()` (which I have to say isn't a good approach), you should destroy using something like `libname_destroyDevice (obj)`. And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need ...
delete or virtual delete?
[ "", "c++", "virtual", "" ]
I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure: ``` ALTER procedure [dbo].[sp_SELECT_Security_ALL] ( @UID Varchar(15) ) as DECLARE @A_ID int If ISNULL(@UID,'') = '' SELECT DISTINCT App_ID, App_Name, App_Description, ...
Scott Guthrie has covered this case [in a blog post](http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx). Scroll down to "Handling Multiple Result Shapes from SPROCs."
The problem isn't with Intellisense. `dataContext.sp_SELECT_Security_ALL()` is returning a fixed data type. You may be hiding that behind a "var", but it's nevertheless a concrete type with a fixed number of properties. There is still C# remember, and a function can only return one type of object. Look in your dataCont...
Linq to SQL, Stored Procedure with different return types based on an If/Else
[ "", "c#", "linq-to-sql", "stored-procedures", "" ]
I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler? ``` struct InterfaceWrapper { InterfaceWrapper( SomeHugeStructure& src ):m_i...
As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you. If the purpose is to limit access to friends of the class, th...
If you really need to construct the class without having an element, a reference is not the way to go. If your only reason to use a reference is to avoid copying, I'd suggest using a pointer. You can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private co...
How can you initialize a class with a reference member from a private constructor?
[ "", "c++", "constructor", "reference", "" ]
Steve Yegge recently posted an [interesting blog post](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html) on what he calls the universal design pattern. In there he details using prototypes as a modelling tool, instead of classes. I like the way this introduces less coupling compared to inheritance....
One interesting bit is that it's easy to make a prototype-based language act OO but it's difficult to make an OO language act prototype-based. * Alex Arnell's [inheritance.js](http://code.google.com/p/inheritance/) is a short and sweet chunk of code that makes JavaScript act OO, complete with access to the parent 'Cla...
Prototypes are a form of inheritance, it's just that objects inherit attributes and behavior directly from other objects, instead of getting their attributes and behavior from their class, which inherits from other classes. For examples, check out any object oriented code in a [prototype based language](http://en.wiki...
prototypes versus classes
[ "", "javascript", "oop", "prototype", "" ]
In particular, would it be possible to have **code similar to this c++ code executed at compile time in c#**? ``` template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value...
No, metaprogramming of this complexity is not supported directly by the C# language. However, like [@littlegeek](https://stackoverflow.com/questions/237326/is-metaprogramming-possible-in-c#237644) said, the [Text Template Transformation Toolkit](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGener...
Metaprogramming is possible in .NET (see compiler compilers, regular expressions, code DOM, reflection etc.) but C# is not capable of *template* metaprogramming because it does not have that language feature.
Is metaprogramming possible in C#?
[ "", "c#", "metaprogramming", "" ]
The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data: ``` if table t has a row exists that has key X: update t set mystuff... where mykey=X else insert into t mystuff... ``` Since Oracle doesn't have a specific UPSERT statement, what's...
An alternative to MERGE (the "old fashioned way"): ``` begin insert into t (mykey, mystuff) values ('X', 123); exception when dup_val_on_index then update t set mystuff = 123 where mykey = 'X'; end; ```
The [MERGE statement](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606) merges data between two tables. Using DUAL allows us to use this command. Note that this is not protected against concurrent access. ``` create or replace procedure ups(xa number) as begin merge into mergete...
How to UPSERT (update or insert into a table?)
[ "", "sql", "oracle", "merge", "upsert", "" ]
I am trying to call a setTimeout from within a setInterval callback: ``` function callback() { //assign myVar var myVar = document.getElementById("givenID"); //... //now wait 2 secs then call some code that uses myVAr setTimeout("myVar.innerHTML = 'TEST'", 2000); } setInterval("callback();", 10000); ``...
This is a perfect candidate for closures: ``` setInterval( function () { var myVar = document.getElementById("givenID"); setTimeout( function() { // myVar is available because the inner closure // gets the outer closures scope myVar.i...
I had a similar problem. The issue was that I was trying to call a method from within itself through a setTimeout(). Something like this, WHICH DIDN'T WORK FOR ME: ``` function myObject() { this.egoist = function() { setTimeout( 'this.egoist()', 200 ); } } myObject001 = new myObject(); myObject001.egois...
How to solve Var out of scope within setTimeout call
[ "", "javascript", "scope", "" ]
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? ``` Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core...
You must make sure that django is in your PYTHONPATH. To test, just do a `import django` from a python shell. There should be no output: ``` ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credit...
I have the same problem on Windows and it seems I've found the problem. I have both 2.7 and 3.x installed. It seems it has something to do with the associate program of .py: In commandline type: > assoc .py and the result is: .py=Python.File which means .py is associated with Python.File then I tried this: > fty...
No Module named django.core
[ "", "python", "django", "" ]
In some code I've inherited, I see frequent use of `size_t` with the `std` namespace qualifier. For example: ``` std::size_t n = sizeof( long ); ``` It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?). Isn't it true that `size_t` is built into C++ and therefore i...
There seems to be confusion among the stackoverflow crowd concerning this `::size_t` is defined in the backward compatibility header `stddef.h` . It's been part of `ANSI/ISO C` and `ISO C++` since their very beginning. Every C++ implementation has to ship with `stddef.h` (compatibility) and `cstddef` where only the la...
Section 17.4.1.2 of the C++ standard, paragraph 4, states that: "In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std." This includes items found in headers of the pattern *cname*, including *...
Does "std::size_t" make sense in C++?
[ "", "c++", "size-t", "" ]
Is it possible to detect, on the client side, whether the user is using an encrypted page or not? Put another way -- I want to know if the URL of the current page starts with http or https.
Use `window.location.protocol` to check if it is `https:` ``` function isSecure() { return window.location.protocol == 'https:'; } ``` Alternatively you can omit specifying "window" if you don't have a locally scoped location. ``` function isSecure() { return location.protocol == 'https:'; } ```
As google analytics taught me: ``` if ("https:" == document.location.protocol) { /* secure */ } else { /* unsecure */ } ```
How can I use JavaScript on the client side to detect if the page was encrypted?
[ "", "javascript", "http", "https", "" ]
Is there a better way to do this? ``` string[] s = {"zero", "one", "two", "three", "four", "five"}; var x = s .Select((a,i) => new {Value = a, Index = i}) .Where(b => b.Value.StartsWith("t")) .Select(c => c.Index); ``` i.e. I'm looking for a more efficient or more elegant way to get the positions of the items match...
You could easily add your own extension method: ``` public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) { int index=0; foreach (T element in source) { if (predicate(element)) { yield return index; } index++; } }...
If you're just using the example as a way to learn LINQ, ignore this post. --- It's not clear to me that LINQ is actually the best way to do this. The code below seems like it would be more efficient since no new anonymous type needs to be created. Granted, your example may be contrived and the technique might be mor...
Getting a collection of index values using a LINQ query
[ "", "c#", ".net", "arrays", "linq", "indexof", "" ]
Ok, so i have been trying to put everyone one of my classes in some root folder, either: UI BusinessLogic DataAccess BusinessObjects Interfaces i have a few more where i can't seem to bucket very well so i am looking for suggestions 1. A Cache class that maintains a private dictionary and allows different ac...
I try to align my assembly names with their namespaces, and use the .NET Framework itself as a guideline. I firmly believe that working with a namespace structure that drives a folder structure makes for a much more maintainable codebase. For example, I have a caching provider that is part of the global developer fram...
I usually like to stick to the 1 class, 1 file rule, but when it comes to EventArgs, I actually like to declare them in the same file that I define the delegate or event. Unless, the args are used by more than one class hierarchy, which doesn't tend to happen to me often. As for the cache, I would put in the folder of...
Class bucketing . .
[ "", "c#", "projects-and-solutions", "directory-structure", "" ]
I know that [buffer overruns](http://en.wikipedia.org/wiki/Buffer_overflow) are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of? **EDIT:** Here's an exam...
C strings lack the following aspects of their C++ counterparts: * Automatic memory management: you have to allocate and free their memory manually. * Extra capacity for concatenation efficiency: C++ strings often have a capacity greater than their size. This allows increasing the size without many reallocations. * No ...
There are a few disadvantages to C strings: 1. Getting the length is a relatively expensive operation. 2. No embedded nul characters are allowed. 3. The signed-ness of chars is implementation defined. 4. The character set is implementation defined. 5. The size of the char type is implementation defined. 6. Have to kee...
What are some of the drawbacks to using C-style strings?
[ "", "c++", "c", "string", "" ]
I would like to know which one is the best material that I can hand out to my students about "*C# comments*".
This is quite interesting to do with the xml comments: <http://thoughtpad.net/alan-dean/cs-xml-documentation.html> These get read by [sandcastle](http://blogs.msdn.com/sandcastle/) too... :o)
Something that I read a while ago (and have lost track of where) is: * Beginners comment nothing * Apprentices comment the obvious * Journeymen comment the reason for doing it * Masters comment the reason for not doing it another way
C# comments tutorial
[ "", "c#", "comments", "" ]
Is it possible to check if a dynamically loaded assembly has been signed with a specific strong name? Is it enough / secure to compare the values returned from **AssemblyName.GetPublicKey()** method? ``` Assembly loaded = Assembly.LoadFile(path); byte[] evidenceKey = loaded.GetName().GetPublicKey(); if (evidenceKey...
There is no managed way to check the signature of an assembly and checking the public key leaves you vulnerable to spoofing. You will have to use [P/Invoke](http://en.wikipedia.org/wiki/Platform_Invocation_Services) and call the **StrongNameSignatureVerificationEx** function to check the signature ``` [DllImport("msco...
Checking strong name using StrongNameSignatureVerificationEx from mscoree.dll is deprecated under .NET 4 according to <http://msdn.microsoft.com/pl-pl/library/ms232579.aspx>. .NET 4 way of doing it is: ``` var clrStrongName = (IClrStrongName)RuntimeEnvironment.GetRuntimeInterfaceAsObject(new Guid("B79B0ACD-F5CD-409b-...
Checking an assembly for a strong name
[ "", "c#", "security", "strongname", "" ]
I'm starting to learn about using Memcached with PHP and I was wondering; is there a point at which you should start using it? Is it always more efficient to cache data or does it only become effective once your site gets a certain number of hits? Presumably there is an overhead associated with Memcached, so when does ...
You should start using memcached when not using it starts to affect your site / server. So when you just have 100 visitors a day and your site still responds quickly, don't bother using it. But when you have running times somewhere near 200ms or more per page, and the site feels slow too, you should look out for the ...
The #1 rule when it comes to performance optimization is: Don't optimize until you need to! If you don't have performance problems, then you don't need to optimize. Other good rules include: * Don't optimize until you're done writing the application. You rarely know where real-world performance problems will crop up ...
When should you start using Memcached?
[ "", "php", "caching", "memcached", "" ]
HI All, I have a piece of javaScript that removes commas from a provided string (in my case currency values) It is: ``` function replaceCommaInCurrency(myField, val) { var re = /,/g; document.net1003Form.myField.value=val.replace(re, ''); } ``` 'MyField' was my attempt to dynamically ha...
You can use eval to make your code snippet work: ``` eval("document.net1003Form." + myField + ".value=val.replace(re, '');"); ``` As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those: ``` document.net1003Form[myField].value=val.replace(re, ''); ``` Alternativ...
If you code it right into the markup like that, e.g. onblur="replaceCommaInCurrency(this)", the control originating the event gets passed as the parameter. Then you should be able to do something like: ``` myField.value = myField.value.replace(re, ''); ``` with jQuery: ``` var jqField = $(myField); jqField.val(jqFie...
JavaScript: Dynamic Field Names
[ "", "javascript", "parsing", "" ]
What are the coolest examples of metaprogramming that you've seen in C++? What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think [Boost.Spirit](http://www.boost.org/doc/libs/release/libs/spirit/doc/html/index.html) is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
The most practical use of meta programming is turning a runtime error into a compile time error. Example: Lets call the interface IFoo. One of my programs dealt with a COM object that had multiple paths to IFoo (very complicated inheritance hierarchy). Unfortunately the underlying COM object implementation didn't real...
What are the coolest examples of metaprogramming that you've seen in C++?
[ "", "c++", "templates", "metaprogramming", "template-meta-programming", "" ]
I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like: ``` class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 ``` This does not work (subcla...
I simply prefer to repeat the `property()` as well as you will repeat the `@classmethod` decorator when overriding a class method. While this seems very verbose, at least for Python standards, you may notice: 1) for read only properties, `property` can be used as a decorator: ``` class Foo(object): @property ...
I don't agree that the chosen answer is the ideal way to allow for overriding the property methods. If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like `lambda self: self.<property func>`. This works (at least) for Python versions 2.4 to 3.6. ...
python properties and inheritance
[ "", "python", "inheritance", "properties", "polymorphism", "" ]
I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog. ([this](https://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse) is a similar question on stackoverflow, but I think it applies to wind...
I've managed to fix this now. In `Window>Preferences>Pydev>Interpreter-Python` remove the python interpreter and reload it (select `New`) after installing pylons. In the Terminal cd into the projects directory. Then type `sudo python setup.py develop` Not sure what this does, but it does the trick (if any one wants t...
I got it running basically almost the same way - although you do not have to do the setup.py develop step - it works fine without that. What it does is that is sets global link to your project directory for a python package named after your project name.
Debugging pylons in Eclipse under Ubuntu
[ "", "python", "eclipse", "debugging", "ubuntu", "pylons", "" ]
A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, an...
This should do it: ``` <?php function array_depth(array $array) { $max_depth = 1; foreach ($array as $value) { if (is_array($value)) { $depth = array_depth($value) + 1; if ($depth > $max_depth) { $max_depth = $depth; } } } return $...
Here's another alternative that avoids the problem Kent Fredric pointed out. It gives [print\_r()](http://php.net/print_r) the task of checking for infinite recursion (which it does well) and uses the indentation in the output to find the depth of the array. ``` function array_depth($array) { $max_indentation = 1;...
Is there a way to find out how "deep" a PHP array is?
[ "", "php", "arrays", "associative-array", "" ]