Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to find whether number is prime or not for 1000 digit long. Algorithm i am thinking to use is 6k+/-1 problem i am facing is how can i store such a long number in java, it is taken string as input. or for doing divisibility should is consider only the last few digits of the number. please advise
If it is sufficient to determine whether or not a number is PROBABLY prime, you can use the built in [isProbablePrime](http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html#isProbablePrime(int)) function * if the call returns true, the probability that the number is prime exceeds (1 - 1/(2^certainty)). * If the call returns false, the number is definately not prime.
You should use a [Lucas pseudoprime test](http://mathworld.wolfram.com/LucasPseudoprime.html) and a [Rabin-Miller strong pseudoprime test](http://mathworld.wolfram.com/Rabin-MillerStrongPseudoprimeTest.html) in bases 2 and 3. If all three give a result of *probably prime*, then for all practical reasons you should consider it so. There are no known counterexamples to this test. If you have to generate a certificate of primality, then you could use an [elliptic curve primality prover](http://mathworld.wolfram.com/EllipticCurvePrimalityProving.html), but it will be tremendously slower.
how to test a prime number 1000 digits long?
[ "", "java", "algorithm", "" ]
I'm currently using JAXB to generate java classes in order to unmarshall XML. Now I would like to create a new schema very similar to the first and have the classes that are generated implement the same interface. Say for example, I have two schema files which define XML with similar tags: adult.xsd ``` <?xml version="1.0" encoding="UTF-8"?> <xs:element name="Person"> <xs:complexType> <xs:sequence> <xs:element name="Name" type="xs:string" /> <xs:element name="Age" type="xs:integer" /> <xs:element name="Job" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> ``` kid.xsd ``` <?xml version="1.0" encoding="UTF-8"?> <xs:element name="Person"> <xs:complexType> <xs:sequence> <xs:element name="Name" type="xs:string" /> <xs:element name="Age" type="xs:integer" /> <xs:element name="School" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> ``` Using JAXB and XJC I'd like to generate two class files: ``` public class Adult implements Person { ... public String getName() { ... } public int getAge() { ... } public String getJob { ... } } public class Kid implements Person { ... public String getName() { ... } public int getAge() { ... } public String getSchool { ... } } ``` where the Person interface defines the `getName()` and `getAge()` methods. I've looked at some of the [documentation](https://jaxb.dev.java.net/guide/Mapping_interfaces.html) for mapping interfaces but this appears to only be for the situation when you already have java classes that you want to map to a DOM. Also, I've tried to use this [external plugin](http://xml.w-wins.com/xjc-plugins/interfaces/) but it doesn't appear to work. Here is my xjb binding file: ``` <jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:ext="http://xml.w-wins.com/xjc-plugins/interfaces" jxb:extensionBindingPrefixes="xjc"> <jxb:bindings schemaLocation="xsd/adult.xsd" node="xs:schema/xs:complexType[@name='Person']"> <ext:interface>mypackage.Hello</ext:interface> </jxb:bindings> </jxb:bindings> ``` but this gives the following error: ``` $ java -cp "lib/activation.jar;lib/InterfacesXJCPlugin.jar;lib/jaxb1-impl.jar;lib/jaxb-api.jar;lib/jaxb-xjc.jar;lib/jsr173_1.0_api.jar" com.sun.tools.xjc.XJCFacade -p mypackage.myxml -extension -Xinterfaces xsd/adult.xsd -b binding.xjb parsing a schema... [ERROR] XPath evaluation of "xs:schema/xs:complexType[@name='Person']" results in empty target node line 8 of file:/C:/dev/jaxb/jaxb-ri/binding.xjb Failed to parse a schema. ``` Is it possible to generate a class with JAXB that implements an interface? **Update** I've tried using the [Interface Insertion](https://jaxb2-commons.dev.java.net/interface-insertion/) plugin but for some reason can't get it to work. This is how I'm calling xjc yet it is as if the plugin jar is not getting picked up from the classpath: ``` $ java -cp "lib/xjc-if-ins.jar;lib/jaxb-xjc.jar" com.sun.tools.xjc.XJCFacade -p mypackage -extension -Xifins myschema.xsd -b binding.xjb ``` I get the error: ``` unrecognized parameter -Xifins ``` Any ideas?
Unfortunately, it looks like the interface-injection plugin mentioned in some of the other answers is no longer well-supported. In fact, I'm having trouble finding the JAR for download. Thankfully, the [JAXB2 Basics Plugins](https://github.com/highsource/jaxb2-basics/wiki) provides a similar mechanism for adding an interface to the generated JAXB stubs (see the [Inheritance plugin](https://github.com/highsource/jaxb2-basics/wiki/JAXB2-Inheritance-Plugin)). The Inheritance plugin documentation has an example showing what the XML schema file might look like. However, since you cannot modify the schema, you can use an external bindings file instead: ``` <?xml version="1.0"?> <jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:inheritance="http://jaxb2-commons.dev.java.net/basic/inheritance" jxb:extensionBindingPrefixes="xjc"> <jxb:bindings schemaLocation="xsd/adult.xsd"> <jxb:bindings node="//xs:complexType[@name='Person']"> <inheritance:implements>mypackage.Hello</inheritance:implements> </jxb:bindings> </jxb:bindings> </jxb:bindings> ``` The JAXB2 Basics Plugins documentation includes instructions for using the plugin with Ant and Maven. You can also use it straight from the command line, but the command is a bit messy (due to the number of jars you have to add to the classpath): ``` java -jar jaxb-xjc.jar -classpath jaxb2-basics-0.5.3.jar,jaxb2-basics-runtime-0.5.3.jar, jaxb2-basics-tools-0.5.3.jar,commons-beanutils-0.5.3.jar, commons-lang.jar,commons-logging.jar -p mypackage.myxml -extension -Xinheritance xsd/adult.xsd -b binding.xjb ``` The JAXB2 Basics Plugins provides a number of other utilities which you might also find useful (such as autogeneration of equals, hashCode, and toString methods).
It might be overkill for your situation, but I have done this using AspectJ (we were already using aspects on that project so we already had the dependency and the exposure). You'd declare an aspect along the lines of: ``` public aspect MyAspect { declare parents: com.foo.generated.Adult implements com.foo.Person; declare parents: com.foo.generated.Kid implements com.foo.Person; } ``` Which will add the interface `com.foo.Person` to the classes `com.foo.generated.Adult` and `com.foo.generated.Kid` Might be overkill for your purpose, but it worked for us.
Generating a JAXB class that implements an interface
[ "", "java", "xsd", "jaxb", "xjc", "jaxb2-basics", "" ]
I'm trying to read some large text files (between 50M-200M), doing simple text replacement (Essentially the xml I have hasn't been properly escaped in a few, regular cases). Here's a simplified version of the function: ``` <?php function cleanFile($file1, $file2) { $input_file = fopen($file1, "r"); $output_file = fopen($file2, "w"); while (!feof($input_file)) { $buffer = trim(fgets($input_file, 4096)); if (substr($buffer,0, 6) == '<text>' AND substr($buffer,0, 15) != '<text><![CDATA[') { $buffer = str_replace('<text>', '<text><![CDATA[', $buffer); $buffer = str_replace('</text>', ']]></text>', $buffer); } fputs($output_file, $buffer . "\n"); } fclose($input_file); fclose($output_file); } ?> ``` What I don't get is that for the largest of files, around 150mb, PHP memory usage goes off the chart (around 2GB) before failing. I thought that this was the most memory efficient way to go about reading large files. Is there some method I am missing that would be more efficient for memory? Perhaps some setting that's keeping things in memory when it should be being collected? In other words, it's not working and I don't know why, and as far as I know I am not doing things incorrectly. Any direction for me to go? Thanks for any input.
PHP isn't really designed for this. Offload the work to a different process and call it or start it from PHP. I suggest using [Python](http://www.python.org/) or [Perl](http://www.perl.org/).
From my meagre understanding of PHP's garbage collection, the following might help: 1. `unset` `$buffer` when you are done writing it out to disk, explicitly telling the GC to clean it up. 2. put the `if` block in another function, so the GC runs when that function exits. The reasoning behind these recommendations is I suspect the garbage collector is not freeing up memory because everything is done inside a single function, and the GC is garbage.
Parsing Large Text Files with PHP Without Killing the Server
[ "", "php", "memory", "parsing", "" ]
I would like to use the [java.text.Normalizer](http://java.sun.com/javase/6/docs/api/java/text/Normalizer.html) class from Java 1.6 to do Unicode normalization, but my code has to be able to run on Java 1.5. I don't mind if the code running on 1.5 doesn't do normalization, but I don't want it to give `NoClassDefFoundError`s or `ClassNotFoundException`s when it runs. What's the best way to achieve this?
The usual way of doing this is via reflection, i.e. don't refer directly to the class in question, but invoke it programmatically. This allows you to catch exceptions gracefully if the code in question doesn't exist, and either ignore it, or try something else. Reflection throws `ClassNotFoundException`, which is a nice normal exception, rather than `NoClassDefFoundError`, which is a bit scarier. In the case of `java.text.Normalizer`, this should be pretty easy, since it's just a couple of static methods, and easy to invoke via reflection.
``` public interface NfcNormalizer { public String normalize(String str); } public class IdentityNfcNormalizer implements NfcNormalizer { public String normalize(String str) { return str; } } public class JDK16NfcNormalizer implements NfcNormalizer { public String normalize(String str) { return Normalizer.normalize(str, Normalizer.Form.NFC); } } ``` In your client code: ``` NfcNormalizer normalizer; try { normalizer = Class.forName("JDK16NfcNormalizer").newInstance(); } catch(Exception e) { normalizer = new IdentityNfcNormalizer(); } ```
How do I refer to Java 1.6 APIs while degrading gracefully against Java 1.5?
[ "", "java", "graceful-degradation", "" ]
I'm supposed to write a library in c++ that should handle the connections to the kad network. I'm trying to build a packet accordant to those used by aMule&co. And I really can't understand the difference between this code: ``` buffer = "\xe4\x20\x02"; ``` and, for example, this code: ``` char p_buffer[36]; p_buffer[0] = 0xe4; p_buffer[1] = 0x20; p_buffer[2] = 0x02; buffer = p_buffer; ``` (buffer is a private attribute of the class, while p\_buffer is a local variable) capturing the packets with wireshark gives me different results (the first one is right as I wanted, the second one not), like I was doing something wrong with little endian / big endian notations, I guess... and why in the constructor of a class can't I modify a [private] "char\* buffer" like this: ``` buffer[0] = 0xe4; ``` ? (it does not work, exits without any trace back error) (if it can matter, I'm using crypto++ and boost libraries) thanks in advance for any help\_
Your first code sample is roughly equivalent to: ``` static const char buffer_internal[4] = { 0xe4, 0x20, 0x02, 0x00 }; buffer = buffer_internal; ``` The two differences here are: * The buffer is null-terminated * The buffer is unmodifiable. Attempting to modify it is likely to crash. Your second sample allocates a 36-byte modifiable buffer. However said buffer will also be discarded when it goes out of scope - be very careful here that it's not used after being freed. As for the third sample, have you initialized 'buffer', if it is a pointer? You've not given enough information to really diagnose your error - the full class declaration and constructor would be helpful.
`""` literals have implicit NUL termination unless constrained by an explicit array length (not in this case). Also in the second case, since `p_buffer` is a local variable i.e. an automatic variable allocated on the stack, the contents of it are not initialized to zero or anything but will contain whatever junk there is in the underlying stack memory.
char array assignment and management
[ "", "c++", "char", "byte", "" ]
I have an error in compiling a project. I'm trying to link to a library I have on windows, using visual studio. When trying to create the obkect (with new), I get the following error: > Error 2 error LNK2005: "public: \_\_thiscall std::basic\_string,class std::allocator >::~basic\_string,class std::allocator >(void)" (??1?$basic\_string@DU?$char\_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) already defined in RMLibV053.lib(Inifile.obj) msvcprtd.lib I used #ifndef I used disable warning
It may be that your code is set up to use a different run-time environment (single-threaded, multi-threaded, multi-threaded DLL) than your PTLibV002.lib library when it was built.
If PTLibV002.lib was compiled to use C++ library statically linked and your binary uses C++ library as DLL, then this is the linking error you'd receive. This is because PTLibV002.lib will contain the definitions of functions from STL it uses, and your binary contains another definition pointing to the C++ library DLL.
C++ Linking problem
[ "", "c++", "visual-studio", "" ]
Is there a built-in function that works like [`zip()`](https://docs.python.org/3/library/functions.html#zip) but that will pad the results so that the length of the resultant list is the length of the *longest* input rather than the *shortest* input? ``` >>> a = ['a1'] >>> b = ['b1', 'b2', 'b3'] >>> c = ['c1', 'c2'] >>> zip(a, b, c) [('a1', 'b1', 'c1')] >>> What command goes here? [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)] ```
In Python 3 you can use [`itertools.zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) ``` >>> list(itertools.zip_longest(a, b, c)) [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)] ``` You can pad with a different value than `None` by using the `fillvalue` parameter: ``` >>> list(itertools.zip_longest(a, b, c, fillvalue='foo')) [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')] ``` With Python 2 you can either use [`itertools.izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest) (Python 2.6+), or you can use `map` with `None`. It is a little known [feature of `map`](https://docs.python.org/2/library/functions.html#map) (but `map` changed in Python 3.x, so this only works in Python 2.x). ``` >>> map(None, a, b, c) [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)] ```
For Python 2.6x use `itertools` module's [`izip_longest`](http://docs.python.org/library/itertools.html#itertools.izip_longest). For Python 3 use [`zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) instead (no leading `i`). ``` >>> list(itertools.izip_longest(a, b, c)) [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)] ```
Is there a zip-like function that pads to longest length?
[ "", "python", "list", "zip", "" ]
Is there a way to define a global variable by user input? Lets say I use ``` #include... #define N 12 double array[N][N]; void main();... ``` But I would like the user to be able to choose what N is. Do I have to have N as a local variable or is there a way around this(without macros)? I've a pretty small program but with a lot of different variables that need the N value. Alternatively, is there a way I could send a group of variables into a function without having to explicitly write them out every time. for example ``` myfunction(var1,var2,var3...) ``` and instead write something like ``` myfunction(Allvariables) ``` Thanks a lot for Your answers! This is a great forum.
``` int* data; int main() { int n; // get n from the user. data = new int[n]; // use data. . . delete[] data; } ``` or just forget pointers for ever and use vector! ``` std::vector<int> data; data.push_back(55); // just push_back data! ``` ======================================================================= EDIT :: If you want to use Edouard A. way :) ``` #include <iostream> #include <sstream> #include <vector> int main(int argc, char* argv[]) { std::vector<double>::size_type dataSize = 0; std::stringstream convertor(argv[1]); { if(argc > 1) { convertor >> dataSize; if(convertor.fail() == true) { // do whatever you want here in case // the user didn't input a number. } } } std::vector<double> data(dataSize); // use the vector here. return 0; } ``` I prefere to use lexical\_cast in this case, but I am not sure if you have Boost. ``` #include <iostream> #include <vector> #include <boost/lexical_cast.hpp> int main(int argc, char* argv[]) { typedef std::vector<double>::size_type vectorSize; if(argc < 2) { // err! The user didn't input anything. } vectorSize dataSize = boost::lexical_cast<vectorSize>(argv[1]); std::vector<double> data(dataSize); // use the vector here. return 0; } ```
1/ Yes but you need dynamic memory allocation. The program parameters are passed as argc and argv to the main function ``` int main(int argc, char **argv) ``` argc is the number of parameters argv is the array of null terminated strings representing these arguments argv[0] is the program itself. 2/You can either use variadic function va\_start & the like, or functions overriding, or group your data in a structure and pass that to the function
change global variables in c++
[ "", "c++", "variables", "global", "" ]
We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new `nullptr`. Well, no need anymore for the nasty macro `NULL`. ``` int* x = nullptr; myclass* obj = nullptr; ``` Still, I am not getting how `nullptr` works. For example, [Wikipedia article](http://en.wikipedia.org/wiki/C%2B%2B11#Null_pointer_constant) says: > C++11 corrects this by introducing a new **keyword** to serve as a distinguished null pointer constant: nullptr. It is of **type nullptr\_t**, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool. How is it a keyword and an instance of a type? Also, do you have another example (beside the Wikipedia one) where `nullptr` is superior to good old `0`?
> How is it a keyword and an instance of a type? This isn't surprising. Both `true` and `false` are keywords and as literals they have a type ( `bool` ). `nullptr` is a *pointer literal* of type `std::nullptr_t`, and it's a prvalue (you cannot take the address of it using `&`). * `4.10` about pointer conversion says that a prvalue of type `std::nullptr_t` is a null pointer constant, and that an integral null pointer constant can be converted to `std::nullptr_t`. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing `nullptr` to select the pointer version. Passing `NULL` or `0` would confusingly select the `int` version. * A cast of `nullptr_t` to an integral type needs a `reinterpret_cast`, and has the same semantics as a cast of `(void*)0` to an integral type (mapping implementation defined). A `reinterpret_cast` cannot convert `nullptr_t` to any pointer type. Rely on the implicit conversion if possible or use `static_cast`. * The Standard requires that `sizeof(nullptr_t)` be `sizeof(void*)`.
## Why nullptr in C++11? What is it? Why is NULL not sufficient? C++ expert [Alex Allain says it perfectly here](https://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html) (my emphasis added in bold): > ...imagine you have the following two function declarations: > > ``` > void func(int n); > void func(char *s); > > func( NULL ); // guess which function gets called? > ``` > > **Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead.** This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. **A language feature that looks like a compiler bug is, well, not something you want.** > > **Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers;** in other words, wherever you were writing NULL before, you should use nullptr instead. **It's no more clear to you, the programmer**, (everyone knows what NULL means), **but it's more explicit to the compiler**, which will no longer see 0s everywhere being used to have special meaning when used as a pointer. Allain ends his article with: > Regardless of all this--the rule of thumb for C++11 is simply to start using `nullptr` whenever you would have otherwise used `NULL` in the past. (My words): Lastly, don't forget that `nullptr` is an object--a class. It can be used anywhere `NULL` was used before, but if you need its type for some reason, it's type can be extracted with [`decltype(nullptr)`](https://en.cppreference.com/w/cpp/language/decltype), or directly described as [`std::nullptr_t`](https://en.cppreference.com/w/cpp/types/nullptr_t), which is simply a `typedef` of `decltype(nullptr)`, as shown here: **Defined in header `<cstddef>`:** See: 1. <https://en.cppreference.com/w/cpp/types/nullptr_t> 2. and <https://en.cppreference.com/w/cpp/header/cstddef> ``` namespace std { typedef decltype(nullptr) nullptr_t; // (since C++11) // OR (same thing, but using the C++ keyword `using` instead of the C and C++ // keyword `typedef`): using nullptr_t = decltype(nullptr); // (since C++11) } // namespace std ``` ## References: 1. [Cprogramming.com: Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint](https://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html) 2. <https://en.cppreference.com/w/cpp/language/decltype> 3. <https://en.cppreference.com/w/cpp/types/nullptr_t> 4. <https://en.cppreference.com/w/cpp/header/cstddef> 5. <https://en.cppreference.com/w/cpp/keyword/using> 6. <https://en.cppreference.com/w/cpp/keyword/typedef>
What is the nullptr keyword, and why is it better than NULL?
[ "", "c++", "pointers", "c++11", "nullptr", "" ]
I have a `Dictionary` that for most operations I just need to retrieve a single entry by key, but for a few operations I will need to work with the entries associated with a range of keys. The way that occurs to me to do this is to use `GetKeys` and a `FindAll` that will match the range I am interested in, but was wondering if someone could suggest a better method.
A `Dictionary` which is implemented as a hash table is not particularly suited to efficiently perform range selection operations on keys. You'll have to visit all keys to find all of them in a specified range. A nice way to accomplish it is to query its collection of keys with a simple LINQ expression.
A `SortedList` or `SortedDictionary` would have the items sorted so you can try to get the key at the bottom of your range then traverse the elements to the top of your range. Using binary search on a `SortedList` will give you the index of the key matching the bottom of your range, or the nearest higher value. See [How to perform a binary search on IList<T>?](https://stackoverflow.com/questions/967047/how-to-perform-a-binary-search-on-ilistt)
Efficient way to get a range of Keys from Dictionary
[ "", "c#", "generics", "dictionary", "" ]
How can I make a reference to a TYPE so I can use myreference name subsequently... In its easiest form... MyInt -- derived from int Then, elsewhere, I would refer to MyInt. The kicker is that I need this "#define" respective within a class definition that would be subclassed and could be a different type. The actual intent is ``` MyTypeSQLCmd = OleDbCommand OR MyTypeSQLCmd = SQLiteCommand ``` and my subclass would just refer to, and be able to create a new MyTypeSQLCmd(); --- let me elaborate a bit more. I have one class that connects to an OleDB type of database. I have ANOTHER class that connect to a SQLite database. I have ANOTHER class that will derive from EITHER of the above, but will have additional functions. So, instead of knowing which back-end I will connect to, I don't want to have IFs all over the place like... ``` if(connectingToSQLite) MyCmd = new SQLiteCommand(); else MyCmd = new OleDbCommand(); ``` since subsequently, the common methods available that I need are the same references, such as MyCmd.Parameters.Add(...) So, I can't pre-declare the variable as one "type" or another such as OleDbCommand MyCmd; SQLiteCommand MyCmd; I want just one instance, so I was hoping to get sort of an "aliased" type that would be accepted and allow to continue without compiler errors.
Aren't you really looking for an interface, i.e. [IDbCommand](http://msdn.microsoft.com/en-us/library/system.data.idbcommand.aspx)
You can either inherit from it or use the `using` statement. ``` using SomeClass = SomeOtherClass; ```
Defining your own TYPE based on existing type
[ "", "c#", "types", "" ]
Is this legal? ``` <?php function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) { //lots_of_awesome_code } ?> ``` where `MENU_DEFAULT_VALUE` and `ODP_DEFAULT_VALUE` are constants defined previously in the file.
Yes, that is legal. From [the manual](http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default): > The default value must be a constant > expression, not (for example) a > variable, a class member or a function > call. Constants fit that bill perfectly.
In an OOP context, you can also use a class member constant as a default method argument value. ``` class MyClass { const A = 1; public function __construct($arg = self::A) { echo $arg; } } ```
Using constants as default function values in PHP
[ "", "php", "function", "constants", "" ]
I want to have a line of code similar to below: ``` var name = $('#input-name').attr("value"); ``` However, the id 'input-name' is not guaranteed to exist. How do I check for its existence so that the assignment does not throw an error?
``` if ($('#input-name').length) { // do something } ```
Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.
How check for ID existence using jQuery?
[ "", "javascript", "jquery", "html", "" ]
I'd like to measure how long it takes to run the whole $().ready() scope in each of page. For profiling specific functions I just set a new Date() variable at the beginning of the relevant part and then check how long it takes to get to the end of the relevant part. The problem with measuring the whole $().ready scope is that it can sometimes run some of the code asynchronously and then I can not wait for it all to finish and see how long it has taken. Is there any event which is fired once the page has completely finished running all $().ready code? **EDIT**: Using Firebug or other client debuggers are not an option since I also need to collect this profiling information from website users for monitoring and graphing our web site's page load speeds Thanks!
There will be no event fired because its virtually impossible for ready() to know when any asynchronous functions are done processing. Thus, you'll need to bake this functionality in yourself; you could use jQuery's custom events, or perhaps set a function to run on setInterval() that can introspect the environment and deduce whether or not everything else is done.
Swap out the jQuery ready function with a function that does your start and finish tracking, and calls the original method. ``` jQuery.ready = (function() { var original = jQuery.ready; return function() { alert('starting profiler'); original(); alert('ending profiler'); }; })(); $(function() { alert('this message will appear between the profiler messages above...'); }); ```
jQuery profiling - measure complete onReady runtime
[ "", "javascript", "jquery", "profiling", "" ]
So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.
If your keys (not necessarily the values) are strings, the [shelve](http://docs.python.org/library/shelve.html) standard library module does what you want pretty seamlessly.
# Use JSON Similar to Pete's answer, I like using JSON because it maps very well to python data structures and is very readable: Persisting data is trivial: ``` >>> import json >>> db = {'hello': 123, 'foo': [1,2,3,4,5,6], 'bar': {'a': 0, 'b':9}} >>> fh = open("db.json", 'w') >>> json.dump(db, fh) ``` and loading it is about the same: ``` >>> import json >>> fh = open("db.json", 'r') >>> db = json.load(fh) >>> db {'hello': 123, 'bar': {'a': 0, 'b': 9}, 'foo': [1, 2, 3, 4, 5, 6]} >>> del new_db['foo'][3] >>> new_db['foo'] [1, 2, 3, 5, 6] ``` In addition, JSON loading doesn't suffer from the same security issues that `shelve` and `pickle` do, although IIRC it is slower than pickle. ## If you want to write on every operation: If you want to save on every operation, you can subclass the Python dict object: ``` import os import json class DictPersistJSON(dict): def __init__(self, filename, *args, **kwargs): self.filename = filename self._load(); self.update(*args, **kwargs) def _load(self): if os.path.isfile(self.filename) and os.path.getsize(self.filename) > 0: with open(self.filename, 'r') as fh: self.update(json.load(fh)) def _dump(self): with open(self.filename, 'w') as fh: json.dump(self, fh) def __getitem__(self, key): return dict.__getitem__(self, key) def __setitem__(self, key, val): dict.__setitem__(self, key, val) self._dump() def __repr__(self): dictrepr = dict.__repr__(self) return '%s(%s)' % (type(self).__name__, dictrepr) def update(self, *args, **kwargs): for k, v in dict(*args, **kwargs).items(): self[k] = v self._dump() ``` Which you can use like this: ``` db = DictPersistJSON("db.json") db["foo"] = "bar" # Will trigger a write ``` Which is woefully inefficient, but can get you off the ground quickly.
With Python, can I keep a persistent dictionary and modify it?
[ "", "python", "dictionary", "persistence", "object-persistence", "" ]
We are using a macro wrapper to Bind Where Parameter function. ``` #define bindWhereClause(fieldName, fieldDataType, fieldData) _bindWhereClause(fieldName, fieldDataType, sizeof(fieldData), &fieldData) void _bindWhereClause(const char *name, int dataType, int dataSize, void *data) { // Implementation } Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, name.getFirstName()); ``` When I tried to call the macro with a function as parameter (as above) I am getting the error message "error: non-lvalue in unary `&'". I am able to call the macro with normal variables like ``` Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, firstName); ``` How to resolve this? Do I need to use inline functions instead of macro? Appreciate your help in advance. Thanks, Mathew Liju
You can't take the address of the return value of a function - it is ephemeral. You need to use a real variable: ``` Nametype first_name = name.getFirstName(); Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, first_name); // ... and maybe name.setFirstName(first_name); here ``` Using an inline function would make it compile but it is unlikely to actually *work*. Presumably this is followed by something like: ``` Database.execute(); ``` ...which expects the objects whose addresses you passed earlier to still be valid. If you use an inline function instead of a macro, those objects will no longer exist, since they were just local to the inline function which has already exited.
For this case you will be just fine using an inline function. It is much better in general and you should use inline functions unless using macros is absolutely necessary.
error: non-lvalue in unary `&' in C++
[ "", "c++", "macros", "" ]
As you might be aware an update to visual studio 2005 was auto updated on most machines last week. This update included a new version of the visual c runtime library. As a result any binaries built after the update also require a new redistributable installed on client systems. See <http://support.microsoft.com/kb/971090/> And here is the installer for the new redistributable: <http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=766a6af7-ec73-40ff-b072-9112bab119c2> This is fine for distributing new binaries to customers, I will ship the new redistributable with the installer and it will all work. However I am really worried about my ability to hotfix existing customer sites if they discover a bug. In this case normally I would just send the dll or exe that was fixed. However if I do this now, I will have to send these customers the new redistributable and now I will be using two different versions of the c runtime library in the same executable. * Is this a problem? * Can this cause my application to crash? * What happens if I allocate memory in one dll then deallocate it in another? Normally this works if the same release runtime library is used. I went through the our code about 3 years ago cleaning this up, but I cannot be sure that I have found and fixed all occurrences. * Is the allocate/deallocate in different dlls still a problem? Now that in the era of smart pointers etc it is very had to enforce this. * Can I control what runtime library version I depend on by changing manifests? Any pointers or advice would be grateful. **Updated:** I have just noticed this question [VC++: KB971090 and selecting Visual C Runtime DLL dependencies](https://stackoverflow.com/questions/1238376/vc-kb971090-and-selecting-visual-c-runtime-dll-dependencies) This is very similar, but my question is more concerned with using two different version of the runtime in one executable.
The version number specified in the application’s manifest file/resource only specifies the minimum version required to run the application. The default behavior of the loader is to first check the WINDOWS\WinSxS folder for the identical version or a superseding version of a dependency identified in an application manifest, and to use that version regardless of whether or not a private assembly containing the dependency has been provided with the application. (See <http://msdn.microsoft.com/en-us/library/aa375674(VS.85).aspx>). So chances are your old binaries will also use the latest version of the Microsoft run time library anyway. Try to run the release build of your application (built before you update your Visual Studio) on a fully patched machine and use process explorer to see which DLLs it loads. The only problem is you will have to include the new run time redistributable file in your patch. If you are still worried, you can try the method described here: <http://tedwvc.wordpress.com/2009/08/10/avoiding-problems-with-vc2005-sp1-security-update-kb971090/>
Yes you will not have to wait too much to see the problems using two runtime libraries. If you allocate memory with a runtime and try to release it with another, your application will crash. It is and will continue being a problem. Only the runtime what reserved the memory can track it. It is imposible for the other runtime to know how much memory you reserved. You may want to read [this](http://kobyk.wordpress.com/2007/07/20/dynamically-linking-with-msvcrtdll-using-visual-c-2005/), is a really good post about linking with msvcrt.dll.
Does the latest Visual Studio 2005 Security Update cause C runtime library issues when hot fixing customer sites
[ "", "c++", "visual-studio", "visual-c++-2005", "hotfix", "" ]
I found this code below in a script, I am trying to figure out if it is actually supposed to do more then I am seeing, As far as I can tell it results in an array of: $maxSize[0] with $new\_width $maxSize[1] with $source\_width ``` $maxSize = array($new_width ? $new_width : $source_width, $new_height ? $new_height : $source_height); ```
It's using inline if statments. If $new\_width is set, it will use that value. Otherwise, it defaults to $source\_width. The same is true for $new\_height. And Yes, you do get a numerically keyed array with two values.
It results in an array with 2 indexes. But it does 2 ternary comparison checks to see what those indexes should equal. For the first one if $new\_width has a value, it'll use that other wise it'll use $source\_width. For the second one if $new\_height has a value it'll use that other wise it'll use $source\_height. This can be expanded as: ``` $maxSize = array(); if ($new_width) $maxSize[] = $new_width; else $maxSize[] = $source_width; if ($new_height) $maxSize[] = $new_height; else $maxSize[] = $source_height; ```
What is this php supposed to do?
[ "", "php", "" ]
i have need webpage-content. I need to get some data from it. It looks like: > < div class="deg">DATA< /div> As i understand, i have to use regex, but i can't choose one. I tried the code below but had no any results. Please, correct me: ``` regexHandler = re.compile('(<div class="deg">(?P<div class="deg">.*?)</div>)') result = regexHandler.search( pageData ) ```
If you want the div tags included in the matched item: ``` regexpHandler = re.compile('(<div class="deg">.*?</div>)') ``` If you don't want the div tags included, only the DATA portion: ``` regexpHandler = re.compile('<div class="deg">(.*?)</div>') ``` Then to run the match and get the result: ``` result = regexHandler.search( pageData ) matchedText = result.groups()[0] ```
I suggest using a good HTML parser (such as [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) -- but for your purposes, i.e. with well-formed HTML as input, the ones that come with the Python standard library, such as [HTMLParser](http://docs.python.org/library/htmlparser.html), should also work well) rather than raw REs to parse HTML. If you want to persist with the raw RE approach, the pattern: ``` r'<div class="deg">([^<]*)</div>' ``` looks like the simplest way to get the string 'DATA' out of the string '`<div class="deg">DATA</div>`' -- assuming that's what you're after. You may need to add one or more `\s*` in spots where you need to tolerate optional whitespace.
Python and web-tags regex
[ "", "python", "regex", "" ]
**This works.** ``` function get_distinct_size_for_bracelets() { $sql = "SELECT DISTINCT size FROM mytable WHERE id = 27 AND type='plastic' ORDER BY size"; } ``` **This does not work and stops php dead with no error reporting.** ``` function get_distinct_size_for_bracelets($myvalue) { $sql = "SELECT DISTINCT size FROM mytable WHERE id = 27 AND type=".$myvalue." ORDER BY size"; } ``` I have tried a number of configurations and nothing is working.
``` function get_distinct_size_for_bracelets($myvalue) { $sql = "SELECT DISTINCT size FROM mytable WHERE id = 27 AND type='".$myvalue."' ORDER BY size"; } ``` You still need the single quotes in the SQL query.
Remember to quote the passed value: ``` function get_distinct_size_for_bracelets($myvalue) { $sql = "SELECT DISTINCT size FROM mytable WHERE id = 27 AND type=".$myvalue." ORDER BY size"; } ``` Should be: ``` function get_distinct_size_for_bracelets($myvalue) { $sql = "SELECT DISTINCT size FROM mytable WHERE id = 27 AND type='".$myvalue."' ORDER BY size"; } ``` Note the added single quotes at `type`.
PHP Variable Passing not working in database call
[ "", "php", "mysql", "parameter-passing", "" ]
I have to do a first query which is `SELECT * from table WHERE NOT column=0`, and use the results from that to do a foreach loop something like below. ``` foreach($results as $result) { $nox = $result[field_x]; //Use nox for whatever; //Then update some fields in SQL; } ``` And keep doing that until all the items in the first query are done. What would the syntax be?
. ``` $sql = "SELECT * FROM `myTable` WHERE `column` = 0"; // query the database $resource = mysql_query($sql); // loop through the results while ($result = mysql_fetch_assoc($resource)) { // grab the value $nox = $result['field_x']; // you should use quotes here, btw // make your modifications; ++$nox; // or whatever // build the query $sql = sprintf( "UPDATE `myTable` SET `field_x` = %d WHERE `id` = %d" , $nox , $result['id'] ); // run the query mysql_query($sql); } ```
Unless you have some extensive processing done in PHP you can most likely do that in a single, [multi-table UPDATE](http://dev.mysql.com/doc/refman/5.1/en/update.html). For example: ``` UPDATE table1 t1 JOIN table2 t2 ON t2.id = t1.id SET t1.col = t2.col + 1 WHERE t1.somecol <> 0 ```
Using foreach to update fields in a mysql database based on another query
[ "", "php", "mysql", "loops", "foreach", "" ]
I am building a large website where members will be allowed to upload content (images, videos) up to 20MB of size (maybe a little less like 15MB, we haven't settled on a final upload limit yet but it will be somewhere between 10-25MB). My question is, should I go with HTTP or FTP upload in this case. Bear in mind that 80-90% of uploads will be smaller size like cca 1-3MB but from time to time some members will also want to upload large files (10MB+). Is HTTP uploading reliable enough for such large files or should I go with FTP? Is there a noticeable speed difference between HTTP and FTP while uploading files? I am asking because I'm using Zend Framework which already has HTTP adapter for file uploads, in case I choose FTP I would have to write my own adapter for it. Thanks!
HTTP definitely puts less of a burden on your clients. A lot of places have proxies or firewalls that block all FTP traffic (in or out).
The big advantage of HTTP is that it goes over firewalls and it's very easy to encrypt---just use HTTPS on port 443 instead of HTTP on port 80. Both go through proxies and firewalls. And these days it's pretty easy to upload a 20MB files over HTTP/HTTPS using a POST. The problem with HTTP is that it is not restartable for uploads. If you get 80% of the file sent and then there is a failure, you will need to restart at the beginning. That's why vendors are increasingly using flash-based, java-based or javascript-based uploaders and downloaders. These systems can see how much of the file has been sent, send a MAC to make sure that it has arrived properly, and resend the parts that are missing. A MAC is more important than you might think. TCP checksums are only 32 bits, so there is a 1-in-4-billion chance of an error not being detected. That potentially happens a lot with today's internet.
HTTP vs FTP upload
[ "", "php", "zend-framework", "upload", "file-upload", "" ]
I've got an dynamically-generated PHP file that is included (via include) in other PHP script. When the first one (for some obscure reason) is generated with parse-errors, causes the main script parse-error an stop the execution. Is there any way to detect parse errors when including a file so I can regenerate dynamically that file?
You can run the command line version of PHP to check the syntax: ``` php -l filename ``` If you need to check the syntax from within the PHP script, use the `exec()` function to call the command line program. See also the deprecated function [`php_check_syntax()`](https://www.php.net/manual/en/function.php-check-syntax.php)
SYNTAX.php?filename.php WHERE SYNTAX.php is: ``` <?php error_reporting(E_ALL); ini_set('display_errors','On'); include($_SERVER['QUERY_STRING']); ?> ```
PHP include files with parse errors
[ "", "php", "include", "" ]
I have created a windows service that has the Account set to user. Which means that when I install the service I need to pass a user name and password. Is there a way to set these maybe in the ProjectInstaller class maybe in the BeforeInstall event? if so HOW?
Take a look at [System.ServiceProcess.ServiceProcessInstaller](http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceprocessinstaller.username.aspx)
The below addition to a project installer will assign the service Log On information during installation. ``` public ProjectInstaller() { InitializeComponent(); serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.<account type>; serviceProcessInstaller1.Username = <domain\userId>; serviceProcessInstaller1.Password = <password>; } ```
Is it possible to programmatically set the user account for a windows service?
[ "", "c#", "windows", "vb.net", "windows-services", "" ]
I've got two ways of fetching a bunch of data. The data is stored in a sorted `vector<map<string, int> >`. I want to identify whether there are inconsistencies between the two vectors. What I'm currently doing (pseudo-code): ``` for i in 0... min(length(vector1), length(vector2)): for (k, v) in vector1[i]: if v != vector2[i][k]: // report that k is bad for index i, // with vector1 having v, vector2 having vector2[i][k] for i in 0... min(length(vector1), length(vector2)): for (k, v) in vector2[i]: if v != vector1[i][k]: // report that k is bad for index i, // with vector2 having v, vector1 having vector1[i][k] ``` This works in general, but breaks horribly if `vector1` has `a, b, c, d` and `vector2` has `a, b, b1, c, d` (it reports brokenness for `b1`, `c`, and `d`). I'm after an algorithm that tells me that there's an extra entry in `vector2` compared to `vector1`. I think I want to do something where when I encountered mismatches entries, I look at the next entries in the second vector, and if a match is found before the end of the second vector, store the index `i` of the entry found in the second vector, and move to matching the next entry in the first vector, beginning with `vector2[i+1]`. Is there a neater way of doing this? Some standard algorithm that I've not come across? I'm working in C++, so C++ solutions are welcome, but solutions in any language or pseudo-code would also be great. ## Example Given the arbitrary map objects: `a`, `b`, `c`, `d`, `e`, `f` and `g`; With `vector1`: `a`, `b`, `d`, `e`, `f` and `vector2`: `a`, `c`, `e`, `f` I want an algorithm that tells me either: > Extra `b` at index 1 of `vector1`, and `vector2's c != vector1's d`. or (I'd view this as an effectively equivalent outcome) > `vector1's b != vector2's c` and extra `d` at index 2 of `vector1` # Edit I ended up using `std::set_difference`, and then doing some matching on the diffs from both sets to work out which entries were similar but different, and which had entries completely absent from the other vector.
Something like the [std::mismatch](http://www.cppreference.com/wiki/stl/algorithm/mismatch) algorithm You could also use [std::set\_difference](http://www.cppreference.com/wiki/stl/algorithm/set_difference)
It sounds like you're looking for the [diff](http://en.wikipedia.org/wiki/Diff#Algorithm) algorithm. The idea is to identify the [longest common subsequence](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Print_the_diff) of the two vectors (using map equality), then recurse down the non-common portions. Eventually you'll have an alternating list of vector sub-sequences that are identical, and sub-sequences that have no common elements. You can then easily produce whatever output you like from this. Apply it to the two vectors, and there you go. Note that since map comparison is expensive, if you can hash the maps (use a strong hash - collisions will result in incorrect output) and use the hashes for comparisons you'll save a lot of time. Once you're down to the mismatched subsequences at the end, you'll have something like: ``` Input vectors: a b c d e f, a b c' d e f Output: COMMON a b LEFT c RIGHT c' COMMON d e f ``` You can then individually compare the maps `c` and `c'` to figure out how they differ. If you have a mutation and insertion next to each other, it gets more complex: ``` Input vectors: a b V W d e f, a b X Y d e f Output: COMMON a b LEFT V W RIGHT X Y COMMON d e f ``` Determining whether to match `V` and `W` against `X` or `Y` (or not at all) is something you'll have to come up with a heuristic for. Of course, if you don't care about how the content of the maps differ, then you can stop here, and you have the output you want.
Comparing two vectors of maps
[ "", "c++", "diff", "" ]
I have a program written in C#. I want the Timer class to run a function at a specific time. E.g : run function X at 20:00 PM How can I do that using the Timer class?
Use the Timer Tick event to check (Set the tick to a suitable value) then in the tick event: ``` DateTime Now = DateTime.Now; if(Now.Hours == DateTimeCallX.Hours && Now.Minutes == DateTimeCallX.Minutes && xHasRan == false) { x(); xHasRan = true; } ``` DateTimeCallX being a DateTime object set to 20:00. xHasRan is a boolean stating whether the function has been called, this will be initially set to false and set to true after x has been called so that if the timer tick runs again in the same minute then it won't run the function again.
[Good way of firing an event at a particular time of day?](https://stackoverflow.com/questions/725917/good-way-of-firing-an-event-at-a-particular-time-of-day)
Timer class and C#
[ "", "c#", "" ]
I've been given no other choice but to access a set of classes, which I cannot modify, with this structure through reflection. Using the method shown in the main method below however, throws a NullPointerException. The null pointer being "table" in the constructor when f1.get(null) is called. I am unable to instantiate the classes beforehand because the only constructor is the one shown, which is private. So there is no way for me to explicitly set table either. Anyone know of a way for me to reflectively call Legacy.A? ``` public class Legacy { public static final Legacy A = new Legacy("A"); public static final Legacy B = new Legacy("B"); private String type0; private static Map<String, Legacy> table = new HashMap<String, Legacy>(); private Legacy(String id) { type0 = id; table.put(type0, this); } public static void main(String[] args) throws Exception { Field f1 = Legacy.class.getDeclaredField("A"); Object o = f1.get(null); } } ``` In before "Reflection == BAD!!!"
The order of the static initializers is wrong, table must come before the constructor calls. This is the reason that you get the exception when the class is loaded and initialized. This has nothing to do with reflection.
Since this is confusing, I would write it like this: ``` public class Legacy { static { table = new HashMap<String, Legacy>(); A = new Legacy("A"); B = new Legacy("B"); } public static final Legacy A; public static final Legacy B; private String type0; private static Map<String, Legacy> table; private Legacy(String id) { type0 = id; table.put(type0, this); } public static void main(String[] args) throws Exception { Field f1 = Legacy.class.getDeclaredField("A"); Object o = f1.get(null); } } ``` This way, even if the members change location (due to refactoring, line alignment or whatever) the code will always work.
Reflectively accessing a static variable in a Java class
[ "", "java", "reflection", "initialization", "" ]
I'm trying to check that a user of this code runs this program from command line using only one command line parameter (the name of the file). When I run this code like this (I'm on windows) ``` C:\>python program.py Usage: program.py <file.txt> C:\> ``` Right. But when I run this program using a file I want to manipulate, I get nothing printed: ``` C:\>python program.py file.txt C:\> ``` Where's the problem, my code is here ``` #!/Python26/ # -*- coding: utf-8 -*- import sys def main(argv): if len(argv) < 2: sys.stderr.write("Usage: %s <file.txt>" % (argv[0],)) return 1 if __name__ == "__main__": sys.exit(main(sys.argv)) f = open(sys.argv[1]) lines = f.readlines() f.close() for line in lines: line = line.strip() etc... ```
I guess you want: ``` #!/Python26/ # -*- coding: utf-8 -*- import sys def main(argv): if len(argv) < 2: sys.stderr.write("Usage: %s <file.txt>" % (argv[0],)) return 1 f = open(sys.argv[1]) lines = f.readlines() f.close() for line in lines: line = line.strip() etc... if __name__ == "__main__": sys.exit(main(sys.argv)) ```
You need to move the `f = open...` and beyond into the main function. As it stands, it never gets executed because execution ends at the sys.exit call. [EDIT] Structuring a module this way is a common Python idiom, BTW. In this way, a file may contain class and function definitions which can be imported by another module and it can also contain code, for example, tests, that is executed only when the file is run directly as a script.
Program invoking: at least one command line parameter
[ "", "python", "" ]
Does anyone know all the possible results for the 3rd value returned from PHP's getimagesize() function? Example this code below will return: * `$imageinfo['2'] = 2;` for a `jpg` image, * `$imageinfo['2'] = 3;` for a `png` image, * `$imageinfo['2'] = 0;` for a `gif` image. The numbers might not be correct above but you get the idea. I can't find on php.net or anywhere else a list of all possible results for the 3rd value. ``` $imageinfo = getimagesize($imageurl); $image_type = $imageinfo['2']; ```
Execute this: ``` print_r(get_defined_constants()); ``` And then look for constants prefixed with IMAGETYPE\_. On my PHP 5.3 installation I got these values: ``` [IMAGETYPE_GIF] => 1 [IMAGETYPE_JPEG] => 2 [IMAGETYPE_PNG] => 3 [IMAGETYPE_SWF] => 4 [IMAGETYPE_PSD] => 5 [IMAGETYPE_BMP] => 6 [IMAGETYPE_TIFF_II] => 7 [IMAGETYPE_TIFF_MM] => 8 [IMAGETYPE_JPC] => 9 [IMAGETYPE_JP2] => 10 [IMAGETYPE_JPX] => 11 [IMAGETYPE_JB2] => 12 [IMAGETYPE_SWC] => 13 [IMAGETYPE_IFF] => 14 [IMAGETYPE_WBMP] => 15 [IMAGETYPE_JPEG2000] => 9 [IMAGETYPE_XBM] => 16 [IMAGETYPE_ICO] => 17 [IMAGETYPE_UNKNOWN] => 0 [IMAGETYPE_COUNT] => 18 ``` As you can see Flash SWF are considered images, and actually `getimagesize()` is able to read the width and height of a SWF object. To me it seemed like a curiosity when I first discovered it, that's why mentioned it here.
That index contains the value of one of PHP's [IMAGETYPE\_XXX constants](https://www.php.net/image.constants). An entire list of them can be found on that page, towards the bottom. That page doesn't provide the actual INT value of each one but you should be able to print a few to get the values as necessary. You could also do a comparison check if you're looking for a specific one: ``` if ($imageinfo[2] == IMAGETYPE_IFF) { // Code here } ```
What kind of file types does PHP getimagesize() return?
[ "", "php", "getimagesize", "" ]
I am considering writing a 2D RTS in C#/.NET and i was wondering what options are available for a graphics library aside from XNA. What are they?
The answers posted so far (apart from SDL.NET) have all just said to use OpenGL, DirectX or some variant of the 2. Personally, I wouldn't use either of these for a 2D game when you already have XNA. XNA already has some classes for doing 2D graphics (the main one being the SpriteBatch). If you do use XNA, not only can you make a game that runs on Windows, but also one for XBox, Zune and Silverlight as well (Zune and Silverlight require that you don't use the 3D part of XNA though, but that shouldn't worry you). Basically, XNA will save you the trouble of writting all of the low level management code that DirectX or OpenGL need (such as handling window switching and a plethora of other problems). I haven't used SDL at all, so I can't give you any personal opinions on it, but I have heard it is quite good for 2D graphics, so I'd recommend looking into SDL.NET or just going with XNA, the other suggestions here require a lot more work with little advantage (most people just want to make the game and not worry about the HAL interfaces and getting everything to play nice with the OS).
Going straight to [DirectX](http://msdn.microsoft.com/en-us/directx/default.aspx) is a perfectly valid option, although for only 2D, you probably need to know a bit too much about 3D graphics to effectively use it. Back when I was into game development, I was quite fond of the Artificial Heart graphics engine, which was somewhat basic but incredibly easy to use. Unfortunately, the [website](http://www.3dlevel.com/gamedev/news.php) appears to have been replaced with a parked domain. Perhaps the company went out of business. If so, it is a shame. For a more extensive catalogue, take a look at the [DevMaster game engine database](http://www.devmaster.net/engines)
Writing a 2D RTS game in C#: graphics library options?
[ "", "c#", ".net", "graphics", "" ]
There was an article i found long ago (i cant find it ATM) which states reasons why the new keyword in C++ is bad. I cant remember all of the reasons but the two i remember most is you must match new with delete, new[] with delete[] and you cannot use #define with new as you could with malloc. I am designing a language so i like to ask how would you change the C++ language so new is more friendly. Feel free to state problems with new and articles. I wish i can find the article link but i remember it was long and was written by a professor at (IIRC) a known school.
### Problem match new, delete, new[], delete[] Not really a big deal. You should be wrapping memory allocation inside a class so this does not really affect normal users. A single obejct can be wrapped with a smart pointer. While an array can be represented by std::Vector<> ### cannot use #define with new as you could with malloc. The reason to mess with malloc like this was to introduce your own memory management layer between your app and the standard memory management layer. This is because in C you were not allowed to write your own version of malloc. In C++ it is quite legal to write your own version of the new which makes this trick unnecessary.
I cannot see any reason to replace the `new` keyword with something else (and seems to be that C++ committee agree with me). It is clear and makes what it should. You could override `operator new` in your class, no need to use defines. To eliminate `new[]`/`delete[]` problem you could use `std::vector`. If you want to use smart pointer you could use it, but I want to control when smart pointer will be used. That's why I like how it works in C++ — high level behavior with ability to control low level details.
How would you replace the 'new' keyword?
[ "", "c++", "language-design", "new-operator", "keyword", "" ]
I would like to get the two **attribute-assignment** lines below into one line since I'm going to build them into an application where they will be numerous. **Is there a way to express those two lines in one line of elegantly constructed C#, perhaps with a ?? operator like this?** ``` string nnn = xml.Element("lastName").Attribute("display").Value ?? ""; ``` Here's the code: ``` using System; using System.Xml.Linq; namespace TestNoAttribute { class Program { static void Main(string[] args) { XElement xml = new XElement( new XElement("employee", new XAttribute("id", "23"), new XElement("firstName", new XAttribute("display", "true"), "Jim"), new XElement("lastName", "Smith"))); //is there any way to use ?? to combine this to one line? XAttribute attribute = xml.Element("lastName").Attribute("display"); string lastNameDisplay = attribute == null ? "NONE" : attribute.Value; Console.WriteLine(xml); Console.WriteLine(lastNameDisplay); Console.ReadLine(); } } } ```
Sure you can! Just do this: ``` string lastNameDisplay = (string)xml.Element("lastName").Attribute("display") ?? "NONE"; ```
Sure, but it's awful, not elegant: ``` string lastNameDisplay = xml.Element("lastName").Attribute("display") == null ? "NONE" : xml.Element("lastName").Attribute("display").Value; ``` If you're willing, you could write an extension method: ``` public static string GetValue(this XAttribute attribute) { if (attribute == null) { return null; } return attribute.Value; } ``` Usage: ``` var value = attribute.GetValue(); ```
How can I use ?? to combine these two lines into one?
[ "", "c#", "" ]
I know that the Random class can generate pseudo-random numbers but is there a way to generate truly random numbers?
The answer here has two main sides to it. There are some quite important subtleties to which you should pay due attention... ## The Easy Way (for simplicity & practicality) The [`RNGCryptoServiceProvider`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx), which is part of the Crypto API in the BCL, should do the job for you. It's still technically a pseudo-random number generated, but the quality of "randomness" is much higher - suitable for cryptographic purposes, as the name might suggest. There are other crypographic APIs with high quality pseudo random generaters available too. Algorithms such as the [Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_twister) are quite popular. Comparing this to the `Random` class in the BCL, it is significantly better. If you plot the numbers generated by `Random` on a graph, for example, you should be able to recognise patterns, which is a strong sign of weakness. This is largely due to the fact that the algorithm simply uses a seeded lookup table of fixed size. ## The Hard Way (for high quality theoretical randomness) To generate *truly* random numbers, you need to make use of some natural phenomenon, such as nuclear decay, microscopic temperature fluctuations (CPU temperature is a comparatively conveient source), to name a few. This however is much more difficult and requires additional hardware, of course. I suspect the practical solution (`RNGCryptoServiceProvider` or such) should do the job perfectly well for you. Now, note that if you *really do require truly random numbers*, you could use a service such as [*Random.org*](http://www.random.org/), which generates numbers with very high randomness/entropy (based on *atmospheric noise*). Data is freely available for download. This may nonetheless be unnecessarily complicated for your situation, although it certainly gives you data suitable for scientific study and whatnot. The choice is yours in the end, but at least you should now be able to make an informative decision, being aware of the various types and levels of RNGs.
short answer: It is not directly possible to generate *TRULY RANDOM NUMBERS* using only C# (i.e. using only a purely mathematical construction). long(er) answer: Only by means of employing an external device capable of generating "randomness" such as a [white noise generator or similar](http://world.std.com/~reinhold/truenoise.html) - and capturing the output of that device as a seed for a pseudo random number generator (PRG). That part could be accomplished using C#.
How can I generate truly (not pseudo) random numbers with C#?
[ "", "c#", "algorithm", "math", "" ]
In C++, why is private the default visibility for members of classes, but public for structs?
C++ was introduced as a superset of C. Structs were carried over from C, where the semantics of their members was that of public. A whole lot of C code exists, including libraries that were desired to work with C++ as well, that use structs. Classes were introduced in C++, and to conform with the OO philosophy of encapsulation, their members are private by default.
Because a class is a usual way of doing object orientation, which means that member variables should be private and have public accessors - this is good for creating [low coupling](http://en.wikipedia.org/wiki/Coupling_(computer_science)#Low_coupling). Structs, on the other hand, have to be compatible with C structs, which are always public (there is no notion of public and private in C), and don't use accessors/mutators.
default visibility of C++ class/struct members
[ "", "c++", "class", "struct", "member", "" ]
![alt text](https://farm3.static.flickr.com/2504/3806628370_c50137228d_o.jpg) Do you know any rounded corners tab like this one that I can download? Or how can I create a tab like that? Do the use of images in the tab menus are required or not? I used the: ``` -moz-border-radius-topleft: 5px; -moz-border-radius-topright: 5px; border-top-left-radius:5px; border-top-right-radius:5px; ``` but it is not perfect. Do you know any helpful links/tutorials about rounded corner tab?
The best-looking rounded corners are always going to be those done using an image. Anything else is the browser's best attempt, which may not be what you want. It's also far easier to just use images. You just need a small image for each corner, and another tileable set of images for the rest of the border. Plug it all into CSS classes and you're good to go.
Not yet supported by all browsers, but you can use CSS3 to easily display rounded corners without the need for images or javascript: ``` <div style="-moz-border-radius: 5px; -webkit-border-radius: 5px;"> Rounded corners! </div> ``` More info: <http://www.css3.info/preview/rounded-border> This should allow for graceful degradation in older browsers (just won't show as rounded), but I'd still be inclined to go with images if you want to ensure all your users have the same experience.
Javascript: How to create a rounded corner tab menu?
[ "", "javascript", "rounded-corners", "" ]
I'm trying to parse ouput from the Python doctest module and store it in an HTML file. I've got output similar to this: ``` ********************************************************************** File "example.py", line 16, in __main__.factorial Failed example: [factorial(n) for n in range(6)] Expected: [0, 1, 2, 6, 24, 120] Got: [1, 1, 2, 6, 24, 120] ********************************************************************** File "example.py", line 20, in __main__.factorial Failed example: factorial(30) Expected: 25252859812191058636308480000000L Got: 265252859812191058636308480000000L ********************************************************************** 1 items had failures: 2 of 8 in __main__.factorial ***Test Failed*** 2 failures. ``` Each failure is preceded by a line of asterisks, which delimit each test failure from each other. What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing). How can I do this using just Python or some combination of UNIX shell utilities? EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file. ``` python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX` ```
This is a quick and dirty script that parses the output into tuples with the relevant information: ``` import sys import re stars_re = re.compile('^[*]+$', re.MULTILINE) file_line_re = re.compile(r'^File "(.*?)", line (\d*), in (.*)$') doctest_output = sys.stdin.read() chunks = stars_re.split(doctest_output)[1:-1] for chunk in chunks: chunk_lines = chunk.strip().splitlines() m = file_line_re.match(chunk_lines[0]) file, line, module = m.groups() failed_example = chunk_lines[2].strip() expected = chunk_lines[4].strip() got = chunk_lines[6].strip() print (file, line, module, failed_example, expected, got) ```
You can write a Python program to pick this apart, but maybe a better thing to do would be to look into modifying doctest to output the report you want in the first place. From the docs for doctest.DocTestRunner: ``` ... the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. ```
How can I process this text file and parse what I need?
[ "", "python", "parsing", "shell", "doctest", "" ]
I have a datamapper class that will eager load any property that does not have a Lazy attribute attached to it. I have two entities, State and Country, Country has an inverse relationship to state in that it contains a list of all the states of that country and State has a forward relationship to Country in that it has a property Country that eager loads the country that it is assigned to. However if I try and retrieve one of these objects, lets say a State this is what happens: 1. State is loaded by mapper 2. Mapper reaches an eager property Country 3. Mapper retrieves the country for that state 4. Mapper loads the country 5. Mapper reaches an eager collection property of States 6. Mapper loads a list of states and begins mapping each individual one using the cache where it can. 7. GOTO 1 for each state loaded in country I am at a loss as to how I can avoid this loop. So mainly I am looking for ideas. I will post any code anyone asks, but this process encompasses A LOT of lines of code so I didn't want to flood the question with code. Thanks in advance! Edit: Alright after following Matt Howells advice and investigating deeper into the datamapper pattern Martin Fowler does indeed speak about a cyclic reference on page 169 and 170. His suggestion is to use an empty object and load it into an identity map and return it thus stopping the recursive loading. I've read this paragraph about 1000 times now and I still don't understand how this stops the load and beyond that I am lost as to when or how I would know when to load this empty object into my identity map. I apologize for being dense here, but this just seems to be flying right over my head. Thanks again.
Consider loading objects through a Repository that keeps track of which objects have been loaded. Edit: If you are doing your own ORM (and even if you are not) I highly recommend Martin Fowler's book Patterns of Enterprise Application Architecture. I vaguely recall him talking about this loop situation in the book so it might help you. Edit 2: At steps 4 and 5 of your loop if you have already loaded the country then there is no need to eagerly load its states because they should already be loaded. This breaks the infinite loop.
The datamapper should catch circular references. Is it a homegrown datamapper?
How do I control the fetch depth of an eager loading datamapper?
[ "", "c#", ".net", "database", "design-patterns", "c#-2.0", "" ]
Example: 1. In the main page cliked on a button (NEW), the page then will using Javascript to open a new page in a new window by calling redirectPage(). 2. In the main page clicked on a button (EXIT), then page then will call confirmExit(), then closeChildWindows() to closed all popup new window before redirect to another new page. 3. However, the JS variable (childWindowHandles) will be always reset if I refresh the main page, and this cause the page unable to close all other popup window before relocated while EXIT button being clicked Does anyone know how can I solve this problem? By able to keep the JS variable (childWindowHandles) even the main page being refresh? ``` var childWindowHandles = new Array(); function redirectPage(url) { childWindowHandles[childWindowHandles.length] = window.open(url) } function confirmExit(url) { closeChildWindows() window.location=url } function closeChildWindows() { for (var loop=0; loop<childWindowHandles.length; loop++) { if (!childWindowHandles[loop].closed) { childWindowHandles[loop].close(); } } } ```
You can use cookies or window.name:) [window.name to store session variables](http://ajaxian.com/archives/whats-in-a-windowname)
You can use [cookies](https://developer.mozilla.org/en/DOM/document.cookie) to persist values... **Edit:** You might find useful a simple object that I use: *Usage:* ``` // Store a key/value for 1 day: cookieManager.set('name', 'a value', 1); // Retrieve a value associated to a key: var value = cookieManager.get('name'); // Remove a key/value: cookieManager.remove('name'); ``` *Implementation:* ``` var cookieManager = { set: function (name, value, expireDays) { var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + expireDays); document.cookie = name + "=" + escape(value) + ((!expireDays) ? "" : ";expires="+expireDate.toGMTString()); }, get: function (key) { var start,end; if (document.cookie.length > 0) { start = document.cookie.indexOf(key + "="); if (start != -1) { start = start + key.length + 1; end = document.cookie.indexOf(";",start); if (end == -1) { end = document.cookie.length; } return unescape(document.cookie.substring(start,end)); } } return ""; }, remove: function (key) { this.set(key, '', -1); } } ```
Does anyone know how can I keep the Javascript variable even though the page has been refreshed?
[ "", "javascript", "" ]
I'm using Code::Blocks with MinGW to write my C++ applications in Windows XP. Now I want to compile my code to run under an MS DOS environment, so I can put it on my DOS formatted floppy disc. Can anyone help me? Thanks in advance. P.S. I don't mean the Command Prompt, but really the good old MS DOS Operating System.
It's pretty old, but [DJGPP](http://www.delorie.com/djgpp/) exists precisely for DOS development. I hasn't been updated since 2000, but it works. It's basically the same as MinGW, but exclusively for DOS.
What year was this written??? (Says four months ago.) Uh, no, DJGPP is still supported, it has G++ 4.4.1 (or unofficial 4.4.2, even)!! The libc itself is still being (very slowly) tweaked, but even 2.03p2 "stable" is from 2002 and 2.04 "beta" from 2003. Where did you get year 2000 and GCC 2.96 (never supported by DJGPP, 2.96 wasn't even an official FSF release, it was a Red Hat fork) from????
MinGW compile for MS DOS
[ "", "c++", "mingw", "dos", "codeblocks", "" ]
I'm having a really nasty problem with some code that I've written. I found someone else that had the same problem on stackoverflow and I tried the solutions but none worked for me. I typedef several common STL types that I'm using and none of the others have any problem except when I try to typedef a map. I get a "some\_file.h:83: error: expected initializer before '<' token" error when including my header in a test program. Here's the important part of the header(some\_file.h): ``` #ifndef SOME_FILE_H #define SOME_FILE_H // some syntax-correct enums+class prototypes typedef std::string str; typedef std::vector<Column> col_vec; typedef col_vec::iterator col_vec_i; typedef std::vector<Row> row_vec; typedef row_vec::iterator row_vec_i; typedef std::vector<str> str_vec; typedef str_vec::iterator str_vec_i; typedef std::vector<Object> obj_vec; typedef obj_vec::iterator obj_vec_i; typedef std::map<Column, Object> col_obj_map; // error occurs on this line typedef std::pair<Column, Object> col_obj_pair; ``` The includes in some\_file.cpp are: ``` #include <utility> #include <map> #include <vector> #include <iostream> #include <string> #include <stdio.h> #include <cc++/file.h> #include "some_file.h" ``` The test file simply includes string, vector, and my file in that order. It has a main method that just does a hello world sort of thing. The funny thing is that I quickly threw together a templated class to see where the problem was (replacing the "`std::map<Column...`" with "`hello<Column...`") and it worked without a problem. I've already created the operator overload required by the map if you're using a class without a '`<`' operator.
You are getting this problem because the compiler doesn't know what a map is. It doesn't know because the map header hasn't been included yet. Your header uses the STL templates: string, vector, map, & pair. However, it doesn't define them, or have any reference to where they are defined. The reason your test file barfs on map and not on string or vector is that you include the string and vector headers before some\_file.h so string and vector are defined, but map is not. If you include map's header, it will work, but then it may complain about pair (unless your particular STL implementation includes pair in map's header). Generally, the best policy is to include the proper standard header for every type you use in your own header. So some\_file.h should have, at least, these headers: ``` #include <string> #include <map> #include <utility> // header for pair #include <vector> ``` The downside to this approach is that the preprocessor has to load each file every time and go through the `#ifdef` ... `#endif` conditional inclusion processing, so if you have thousands of files, and dozens of includes in each file, this could increase your compilation time significantly. However, on most projects, the added aggravation of having to manage the header inclusion manually is not worth the miniscule gain in compilation time. That is why Scott Meyers' [Effective STL](http://my.safaribooksonline.com/9780321545183 "Effective STL") book has "Always #include the proper headers" as [item #48](http://my.safaribooksonline.com/9780321545183/ch07lev1sec6 "Effective STL: Item 48 (excerpt)").
Is there a `#include <map>` somewhere in your header file? Put that in there to at least see if it works. You should be doing that anyway.
C++ STL map typedef errors
[ "", "c++", "stl", "compiler-errors", "typedef", "" ]
I'm trying to bind the **dhcpctl** library to Java using JNA. This is mi code (I didn't declare all the functions yet): ``` package com.abiquo.abicloud.omapi; import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPCtrlDataString; import com.abiquo.abicloud.omapi.DHCPControlStructure.DHCPHandle; import com.abiquo.abicloud.omapi.OmapiControlStructure.OmapiObjectTypeT; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; /** * Binding of the dhcpctl header. * @author jdevesa@abiquo.com */ public interface DHCPControlLibrary extends Library { /** * Create the loaded instance of the native library */ DHCPControlLibrary INSTANCE = (DHCPControlLibrary) Native.loadLibrary("dhcpctl", DHCPControlLibrary.class); /** * Define as synchronized */ DHCPControlLibrary SYNC_INSTANCE=(DHCPControlLibrary) Native.synchronizedLibrary(INSTANCE); int dhcpctl_initialize (); int dhcpctl_connect (DHCPHandle handle1, String address, int port, DHCPHandle.ByValue handle2); int dhcpctl_wait_for_completion (DHCPHandle handle, Pointer int1); int dhcpctl_get_value (DHCPCtrlDataString dataString , DHCPHandle.ByValue handleValue, String str1); int dhcpctl_get_boolean (Pointer int1, DHCPHandle.ByValue handleValue, String str1); int dhcpctl_set_value (DHCPHandle.ByValue handleValue, DHCPCtrlDataString dataString, String str1); ... etc ... } ``` **dhcpctl** uses **omapi** library to call the remote DHCP server. So, when I try to load the library with: ``` DHCPControlLibrary dhcpExecutor = DHCPControlLibrary.INSTANCE; ``` it throws the following error: ``` Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'dhcpctl': /usr/lib/libdhcpctl.so: undefined symbol: omapi_type_generic at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:160) at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:228) at com.sun.jna.Library$Handler.<init>(Library.java:140) at com.sun.jna.Native.loadLibrary(Native.java:372) at com.sun.jna.Native.loadLibrary(Native.java:357) at com.abiquo.abicloud.omapi.DHCPControlLibrary.<clinit>(DHCPControlLibrary.java:40) at com.abiquo.abicloud.omapi.DHCPexecution.main(DHCPexecution.java:11) ``` **omapi\_\_type\_\_generic** is an external variable stored in omapi.h. I think I have to do a sort of linking when i load the library, but I don't know how to do it. Many thanks.
`omapi_type_generic` is not "an external variable stored in omap.h". This variable must be defined in some .c file somewhere and hence in some .so or .a. If it is not defined in any .c file then there is your problem right there. Find out why it is so and fix it and you should overcome this exception.
I think u forget extern "C" while writing c++ code. In my case c++ code: ``` #include <stdlib.h> #include <iostream> using namespace std; extern "C" { void test() { cout << "TEST" << endl; } int addTest(int a,int b) { int c = a + b ; return c ; } } ``` and java code ``` import com.sun.jna.Library; import com.sun.jna.Native; public class jnatest1 { public interface Clibrary extends Library { Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello", Clibrary.class); void test(); int addTest(int a,int b); } public static void main(String[] args) { Clibrary.INSTANTCE.test(); int c = Clibrary.INSTANTCE.addTest(10,20); System.out.println(c); } } ``` it works for me
JNA undefined symbol
[ "", "java", "jna", "" ]
What is a "namespace alias" in C++? How is it used?
A namespace alias is a convenient way of referring to a long namespace name by a different, shorter name. As an example, say you wanted to use the numeric vectors from Boost's uBLAS without a `using namespace` directive. Stating the full namespace every time is cumbersome: ``` boost::numeric::ublas::vector<double> v; ``` Instead, you can define an alias for `boost::numeric::ublas` -- say we want to abbreviate this to just `ublas`: ``` namespace ublas = boost::numeric::ublas; ublas::vector<double> v; ```
Quite simply, the #define won't work. ``` namespace Mine { class MyClass { public: int i; }; } namespace His = Mine; namespace Yours { class Mine: public His::MyClass { void f() { i = 1; } }; } ``` Compiles fine. Lets you work around namespace/class name collisions. ``` namespace Nope { class Oops { public: int j; }; } #define Hmm Nope namespace Drat { class Nope: public Hmm::Oops { void f () { j = 1; } }; } ``` On the last line, "Hmm:Oops" is a compile error. The pre-processor changes it to Nope::Oops, but Nope is already a class name.
What is a namespace alias?
[ "", "c++", "namespaces", "namespace-alias", "" ]
I have made a generic parser for parsing ascii files. When I want to parse dates, I use ParseExact function in DateTime object to parse, but I get problems with the year. The text to parse is i.e. "090812" with the parseExact string "yyMMdd". I'm hoping to get a DateTime object saying "12/8-2009", but I get "12/8-1909". I know, that I could make an ugly solution by parsing it afterwards, and thereby modifying the year.. Anyone know of a smart way to solve this ?? Thanks in advance.. Søren
Theoretically elegant way of doing this: change the `TwoDigitYearMax` property of the `Calendar` used by the `DateTimeFormatInfo` you're using to parse the text. For instance: ``` CultureInfo current = CultureInfo.CurrentCulture; DateTimeFormatInfo dtfi = (DateTimeFormatInfo) current.DateTimeFormat.Clone(); // I'm not *sure* whether this is necessary dtfi.Calendar = (Calendar) dtfi.Calendar.Clone(); dtfi.Calendar.TwoDigitYearMax = 1910; ``` Then use `dtfi` in your call to `DateTime.ParseExact`. Practical way of doing this: add "20" to the start of your input, and parse with "yyyyMMdd".
You will need to determine some kind of threshold date appropriate for your data. If the parsed date is before this date, add 100 years. A safe way to do that is to prefix the input string with the appropriate century. In this example I've chosen 1970 as the cutoff: ``` string input = ...; DateTime myDate; if (Convert.ToInt32(input.Substring(0, 2)) < 70) myDate = DateTime.ParseExact("20" + input, ...); else myDate = DateTime.ParseExact("19" + input, ...); ``` Jon Skeet also posted a nice example using `DateTimeFormatInfo` that I had momentarily forgotten about :)
DateTime string parsing
[ "", "c#", ".net", "c#-2.0", "" ]
How can I determine the size of an ImageSource *in pixels*? The ImageSource object has a Height and a Width property, but they return the size in 1/96 inches..
You have to multiply the value with Windows's DPI resolution in order to obtain the amount of physical pixels. One way to get the DPI resolution is to get hold of a [`Graphics`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics%28loband%29.aspx) object and read its [`DpiX`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.dpix%28loband%29.aspx) and [`DpiY`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.dpiy%28loband%29.aspx) properties.
Super old post, but for anyone else having problems with this, you don't have to do anything crazy or complicated. ``` (ImageSource.Source as BitmapSource).PixelWidth (ImageSource.Source as BitmapSource).PixelHeight ```
Pixel size of ImageSource
[ "", "c#", "wpf", "image", "" ]
I need some clarification re cascade deletes in Entity Framework and despite searching for hours am no closer to a solution. In a nutshell, if I have an entity (MyObject) that has a 1->0..1 relationship with a child (MyObjectDetail) then I can't delete MyObject without an UpdateException complaining about constraints - but **ONLY IF** the child MyObjectDetail is not loaded into memory. ``` System.Data.UpdateException: A relationship is being added or deleted from an AssociationSet 'FK_MyObjectDetail_MyObject'. With cardinality constraints, a corresponding 'MyObjectDetail' must also be added or deleted. ``` **If the child is loaded (i.e. MyObject.MyObjectDetailReference.Load() before deleting the MyObject) then it works fine.** My issue is, of course, that I don't want to (read: cannot) load the varbinary field from MyObjectDetail everytime I want to delete the parent MyObject. Is this possible, or am I going to have to hack in some manual SQL calls to make this work? In SQL server: ``` MyObject [PK:Id<int>] -> MyObjectDetail [PK:MyObjectId<int>, Data<varbinary>] ``` The relationship is set to "Cascade" for update and delete. In EF Designer: ``` MyObject [1] -> [0..1] MyObjectDetail ``` In EF XML: SSDL: ``` <Association Name="FK_MyObjectDetail_MyObject"> <End Role="MyObject" Type="MyEntities.Store.MyObject" Multiplicity="1"> <OnDelete Action="Cascade" /> </End> <End Role="ObjectDetail" Type="MyEntities.Store.ObjectDetail" Multiplicity="0..1" /> <ReferentialConstraint> <Principal Role="MyObject"> <PropertyRef Name="Id" /> </Principal> <Dependent Role="ObjectDetail"> <PropertyRef Name="MyObjectId" /> </Dependent> </ReferentialConstraint> </Association> ``` CSDL: ``` <Association Name="FK_MyObjectDetail_MyObject"> <End Type="MyEntities.MyObject" Role="MyObject" Multiplicity="1"> <OnDelete Action="Cascade" /> </End> <End Type="MyEntities.MyObjectDetail" Role="ObjectDetail" Multiplicity="0..1" /> <ReferentialConstraint> <Principal Role="MyObject"> <PropertyRef Name="Id" /></Principal> <Dependent Role="ObjectDetail"> <PropertyRef Name="MyObjectId" /> </Dependent> </ReferentialConstraint> </Association> ``` (The <OnDelete> in the CSDL having been added by me manually as per articles like <http://codepolice.net/2008/12/16/cascade-delete-in-entity-framework/>) Am I doing anything wrong, or is this simply not possible in v1 of the EF?
i think you can get around this by updating the myObject.myPropertyReference = new EntityKey with the id of the related object.. something like: myObject.myPropertyReference.EntityKey = EFExtensions.GetEntityKey(context, "myObjectID", myObject.myObjectID); search for EFExtension .. you don't need this as there is a way to create the EntityKey without it. hope that helps!
The EF relies on the database doing the cascade delete. The exception is when the child entity is in memory. Then the EF will delete it too, not to satisfy the cascade delete rule. But rather because it needs to do so to keep the ObjectContext in sync with what it expects the database to look like after the Principal is deleted in the database. What this means is if you don't have a cascade setup in the database, and the dependent entities are not loaded, the EF won't delete them when you delete the principle, because it assumes the database will do it. See [Tip 33 - How cascade delete really works](http://blogs.msdn.com/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx) for more information. Does this help? Alex James Entity Framework Team
Deleting an entity that has an un-loaded child entity
[ "", "c#", "entity-framework", "ado.net", "" ]
I'm trying to extract some data from various HTML pages using a python program. Unfortunately, some of these pages contain user-entered data which occasionally has "slight" errors - namely tag mismatching. Is there a good way to have python's xml.dom try to correct errors or something of the sort? Alternatively, is there a better way to extract data from HTML pages which may contain errors?
You could use [HTML Tidy](http://utidylib.berlios.de/) to clean up, or [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) to parse. Could be that you have to save the result to a temp file, but it should work. Cheers,
If jython is acceptable to you, tagsoup is very good at parsing junk - if it is, I found the jdom libraries far easier to use than other xml alternatives. This is a snippet from a demo mockup to do with screen scraping from tfl's journey planner: ``` private Document getRoutePage(HashMap params) throws Exception { String uri = "http://journeyplanner.tfl.gov.uk/bcl/XSLT_TRIP_REQUEST2"; HttpWrapper hw = new HttpWrapper(); String page = hw.urlEncPost(uri, params); SAXBuilder builder = new SAXBuilder("org.ccil.cowan.tagsoup.Parser"); Reader pageReader = new StringReader(page); return builder.build(pageReader); } ```
Python xml.dom and bad XML
[ "", "python", "xml", "dom", "expat-parser", "" ]
I want to reset the time of a date time picker to 00:00 manually. When i select the date from it i get the time of the instance i select the time is there any way i can reset it to given time?
How about this: ``` picker.Value = picker.Value.Date; ``` EDIT: To specify a particular time, you'd use something like: ``` TimeSpan time = new TimeSpan(3, 30, 0); // 3 hours and 30 minutes picker.Value = picker.Value.Date + time; ```
Reset time to 00:00:00 ``` dateTimePicker.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); ``` Before reset: ``` 2009-08-15 20:27:42 ``` After reset ``` 2009-08-15 00:00:00 ```
how to reset the time of datetimepicker in C#
[ "", "c#", "winforms", "datetime", "" ]
I have a class that inherits from httplib.HTTPSConnection. ``` class MyConnection(httplib.HTTPSConnection): def __init__(self, *args, **kw): httplib.HTTPSConnection.__init__(self,*args, **kw) ... ``` Is it possible to turn off the SSL layer when the class is instantiatied so I can also use it to communicate with non-secure servers? I my case it is known before initialisation if SSL should be used so another solution would be to try to switch the inheritance from *httplib.HTTPSConnection* to *httplib.HTTPConnection*, but I am also not sure how to do this in a sensible way?
As per my comment on @Mark's answer, I like the factory approach he's advocating. However, I wouldn't do it exactly his way, because he makes a new class afresh every time. Rather, this is a nice use case for mixin MI and `super`, as follows: ``` class MyConnectionPlugin(object): def __init__(self, *args, **kw): super(MyConnectionPlugin, self).__init__(*args, **kw) # etc etc -- rest of initiatizations, other methods class SecureConnection(MyConnectionPlugin, httplib.HTTPSConnection, object): pass class PlainConnection(MyConnectionPlugin, httplib.HTTPConnection, object): pass def ConnectionClass(secure): if secure: return SecureConnection else: return PlainConnection conn = ConnectionClass(whatever_expression())() ``` etc. Now, alternatives ARE possible, since a Python object can change its own `__class__`, and so forth. However, like shooting flies with a rhino rifle, using excessive force (extremely powerful, deep, and near-magical language features) to solve problems that can be nicely solved with reasonable restraint (the equivalent of a flyswatter), is NOT recommended;-). **Edit**: the extra injection of `object` in the bases is needed only to compensate for the sad fact that in Python 2.\* the HTTPConnection class is old-style and therefore doesn't play well with others -- witness...: ``` >>> import httplib >>> class Z(object): pass ... >>> class Y(Z, httplib.HTTPConnection): pass ... >>> Y.mro() [<class '__main__.Y'>, <class '__main__.Z'>, <type 'object'>, <class httplib.HTTPConnection at 0x264ae0>] >>> class X(Z, httplib.HTTPConnection, object): pass ... >>> X.mro() [<class '__main__.X'>, <class '__main__.Z'>, <class httplib.HTTPConnection at 0x264ae0>, <type 'object'>] >>> ``` The method-resolution order (aka MRO) in class Y (without the further injection of an `object` base) has object before the class from httplib (so `super` doesn't do the right thing), but the extra injection jiggles the MRO to compensate. Alas, such care is needed in Python 2.\* when dealing with bad old legacy-style classes; fortunately, in Python 3, the legacy style has disappeared and every class "plays well with others" as it should!-)
Per your last paragraph, in Python you can use something like a factory pattern: ``` class Foo: def doit(self): print "I'm a foo" class Bar: def doit(self): print "I'm a bar" def MakeClass(isSecure): if isSecure: base = Foo else: base = Bar class Quux(base): def __init__(self): print "I am derived from", base return Quux() MakeClass(True).doit() MakeClass(False).doit() ``` outputs: ``` I am derived from __main__.Foo I'm a foo I am derived from __main__.Bar I'm a bar ```
Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection
[ "", "python", "http", "https", "" ]
I researched for a while, hasn't found a CSS solution yet, `em` and `ex` units are not correct in this case. What I want is simply a div box that exactly fits 80x25 monospace text. Do I have to resort to Javascript solutions?
`em` does work in this case, if you know the proper ratios involved with your font. Try the following HTML: (The danger with this is that some browsers adjust the font, which can alter the width/height of the font. For 100% accuracy, you might have to go with JavaScript.) ``` <style type="text/css"> #text-container { border: #f00 solid 1px; font: 10px/1.2 Courier, monospace; width: 48em; /* 80 x 0.6 (the width/height ratio of Courier) */ height: 30em; /* 25 x 1.2 (line-height is 1.2) */ overflow: hidden; } </style> <div id="text-container"> 00000000001111111111222222222233333333334444444444555555555566666666667777777777 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890123456789012345678901234567890 </div> ```
Try using the `ch` unit described [in the CSS3 specification](http://www.w3.org/TR/css3-values/#font-relative-lengths): > Equal to the used advance measure of the "0" (ZERO, U+0030) glyph found in the font used to render it. Thus `width: 80ch` specifies an 80 character width limit.
How to set width of <div> to fit constant number of letters in monospace font?
[ "", "javascript", "html", "css", "" ]
How can I explode a string at the position after every third semicolon (;)? example data: ``` $string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;'; ``` Desired output: ``` $output[0] = 'piece1;piece2:piece3;' $output[1] = 'piece4;piece5;piece6;' $output[2] = 'piece7;piece8;' ``` Notice the trailing semicolons are retained.
I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time. ``` $tmp = explode(";", $string); $i=0; $j=0; foreach($tmp as $piece) { if(! ($i++ %3)) $j++; //increment every 3 $result[$j] .= $piece; } ```
Easiest solution I can think of is: ``` $chunks = array_chunk(explode(';', $input), 3); $output = array_map(create_function('$a', 'return implode(";",$a);'), $chunks); ```
Split a string AFTER every third instance of character
[ "", "php", "arrays", "split", "preg-split", "delimited", "" ]
Just like we do with \_\_ToString, is there a way to define a method for casting? ``` $obj = (MyClass) $another_class_obj; ```
There is no need to type cast in php. --- **Edit:** *Since this topic seems to cause some confusion, I thought I'd elaborate a little.* In languages such as Java, there are two things that may carry type. The compiler has a notion about type, and the run time has another idea about types. The compilers types are tied to variables, whereas the run time engine tracks the type of values (Which are assigned to variables). The variable types are known at compile time, whereas the value types are only known at run time. If a piece of input code violates the compilers type system, the compiler will barf and halt compilation. In other words, it's impossible to compile a piece of code that violates the static type system. This catches a certain class of errors. For example, take the following piece of (simplified) Java code: ``` class Alpha {} class Beta extends Alpha { public void sayHello() { System.out.println("Hello"); } } ``` If we now did this: ``` Alpha a = new Beta(); ``` we would be fine, since `Beta` is a subclass of `Alpha`, and therefore a valid value for the variable `a` of type `Alpha`. However, if we proceed to do: ``` a.sayHello(); ``` The compiler would give an error, since the method `sayHello` isn't a valid method for `Alpha` - Regardless that we know that `a` is actually a `Beta`. Enter type casting: ``` ((Beta) a).sayHello(); ``` Here we tell the compiler that the variable `a` should - in this case - be treated as a `Beta`. This is known as type casting. This loophole is very useful, because it allows polymorphism in the language, but obviously it is also a back door for all sorts of violations of the type system. In order to maintain some type safety, there are therefore some restrictions; You can only cast to types that are related. Eg. up or down a hierarchy. In other words, you wouldn't be able to cast to a completely unrelated class `Charlie`. It's important to note that all this happens in the compiler - That is, it happens before the code even runs. Java can still get in to run time type errors. For example, if you did this: ``` class Alpha {} class Beta extends Alpha { public void sayHello() { System.out.println("Hello"); } } class Charlie extends Alpha {} Alpha a = new Charlie(); ((Beta) a).sayHello(); ``` The above code is valid for the compiler, but at run time, you'll get an exception, since the cast from `Beta` to `Charlie` is incompatible. *Meanwhile, back at the PHP-farm.* The following is valid to the PHP-compiler - It'll happily turn this into executable byte code, but you'll get a run time error: ``` class Alpha {} class Beta extends Alpha { function sayHello() { print "Hello"; } } $a = new Alpha(); $a->sayHello(); ``` This is because PHP variables don't have type. The compiler has no idea about what run time types are valid for a variable, so it doesn't try to enforce it. You don't specify the type explicitly as in Java either. There are type hints, yes, but these are simply run time contracts. The following is still valid: ``` // reuse the classes from above function tellToSayHello(Alpha $a) { $a->sayHello(); } tellToSayHello(new Beta()); ``` Even though PHP *variables* don't have types, the *values* still do. A particular interesting aspect of PHP, is that it is possible to change the type of a value. For example: ``` // The variable $foo holds a value with the type of string $foo = "42"; echo gettype($foo); // Yields "string" // Here we change the type from string -> integer settype($foo, "integer"); echo gettype($foo); // Yields "integer" ``` This feature some times confused with type casting, but that is a misnomer. The type is still a property of the value, and the type-change happens in runtime - not at compile time. The ability to change type is also quite limited in PHP. It is only possible to change type between simple types - not objects. Thus, it isn't possible to change the type from one class to another. You can create a new object and copy the state, but changing the type isn't possible. PHP is a bit of an outsider in this respect; Other similar languages treat classes as a much more dynamic concept than PHP does. Another similar feature of PHP is that you can clone a value as a new type, like this: ``` // The variable $foo holds a value with the type of string $foo = "42"; echo gettype($foo); // Yields "string" // Here we change the type from string -> integer $bar = (integer) $foo; echo gettype($bar); // Yields "integer" ``` Syntactically this looks a lot like how a typecast is written in statically typed languages. It's therefore also often confused with type casting, even though it is still a runtime type-conversion. **To summarise:** Type casting is an operation that changes the type of a variable (*not* the value). Since variables are without type in PHP, it is not only impossible to do, but a nonsensical thing to ask in the first place.
Although there's no need to type cast in PHP, you might come across a situation where you would like to convert a parent object into a child object. ## Simple ``` //Example of a sub class class YourObject extends MyObject { public function __construct(MyObject $object) { foreach($object as $property => $value) { $this->$property = $value; } } } $my_object = new MyObject(); $your_object = new YourObject($my_object); ``` So all you do is pass the parent object down to the child object's constructor, and let the constructor copy over the properties. You can even filter / change them as needed. ## Advanced ``` //Class to return standard objects class Factory { public static function getObject() { $object = new MyObject(); return $object; } } //Class to return different object depending on the type property class SubFactory extends Factory { public static function getObject() { $object = parent::getObject(); switch($object->type) { case 'yours': $object = new YourObject($object); break; case 'ours': $object = new OurObject($object); break; } return $object; } } //Example of a sub class class YourObject extends MyObject { public function __construct(MyObject $object) { foreach($object as $property => $value) { $this->$property = $value; } } } ``` It's not type casting, but it does what you need.
Type casting for user defined objects
[ "", "php", "casting", "" ]
Well, simple situation. I've created about 5000 frames as PNG files which I want to display as an animation inside a .NET application. Every image is 1920x1080 in size and the PNG file uses alpha channels for (partial) transparency. And that's going to complicate things a bit, because I would prefer to keep it transparent. (But if that's impossible, I'll just add a background image to every PNG.) Because of the large amount of images, I would need lots of memory. Well, a 1 TB harddisk and a 12 GB Quad-core Intel Xeon system running Vista 64-bits is solving those memory requirements. But unless a tool is created to support 64-bits, it will probably choke after loading perhaps 800 of the 5000 images. So I need a tool that can do this. The movie format isn't that important. Neither is compression, as long as the image quality stays high. (And there's a reason why I've used such a huge resolution!) Lossless compression would be preferred, though. My system is fast enough to replay the movie afterwards again so I'm not worried about it's speed. However, image quality is the most important factor here. So far, I've come up with two options: 1) I find some free tool which can handle this much data. (Free, or very cheap.) 2) I write such a tool myself... Option 1 is a bit out-of-place here. Besides, as a software engineer, my hands are just twitching to write it myself! In C# with preferably no third-party libraries. So my question: - Where to start writing this myself? --- (In case you're wondering, this movie is an animation where a young woman is walking through the streets of some city, passing several signs which mention features of a product. At the end of the movie, she walks up to a bigger sign which shows the name of the product itself. And it's one long, continuous scene, no breaks. And real fun to create too! And about 10 GB of images...)
if you are on windows, you can also look into virtualdub. <http://www.virtualdub.org/> it can make AVIs from bmps, pngs, etc.
FFMPEG is capable of creating a movie file from a series of image files, this link to their manual shows an example: [http://ffmpeg.org/ffmpeg-doc.html#SEC5](http://ffmpeg.org/ffmpeg-doc.html#SEC5 "\"FMPEG") As for creating the movie file programaticcaly with no third party libraries... that is going to be a bit more difficult. Many movie formats are tremendously complicated and to create one without an existing library would be pretty painful(unless I misinterpreted your question and you're not actually asking about creating the actual encoder) If I didn't misinterpret your question, doing a simple implementation of a YUV based movie codec might be doable. [HuffYUV](http://wiki.multimedia.cx/index.php?title=HuffYUV "HuffyYUV") is one I'm aware of that might not be too challenging.
How to create a movie from 5000 PNG files?
[ "", "c#", "animation", "" ]
I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class: ``` class AssignmentFilterForm(forms.Form): filters = [] filter = forms.ChoiceField() def __init__(self, *args, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) self.filters.append(PatientFilter('All')) self.filters.append(PatientFilter('Assigned', 'service__isnull', False)) self.filters.append(PatientFilter('Unassigned', 'service__isnull', True)) for i, f in enumerate(self.filters): self.fields["filter"].choices.append((i, f.name)) ``` When I output this form to a template using: ``` {{ form.as_p }} ``` I see the correct choices. However, after refreshing the page, I see the list three times in the select box. Hitting refresh again results in the list showing 10 times in the select box! Here is my view: ``` @login_required def assign_test(request): pg = PhysicianGroup.objects.get(pk=physician_group) if request.method == 'POST': form = AssignmentFilterForm(request.POST) if form.is_valid(): yes = False else: form = AssignmentFilterForm() patients = pg.allPatients().order_by('bed__room__unit', 'bed__room__order', 'bed__order' ) return render_to_response('hospitalists/assign_test.html', RequestContext(request, {'patients': patients, 'form': form,})) ``` What am I doing wrong? Thanks, Pete
I picked up the book Pro Django which answers this question. It's a great book by the way, and I highly recommend it! The solution is to make BOTH the choice field and my helper var both instance variables: ``` class AssignmentFilterForm(forms.Form): def __init__(self, pg, request = None): super(forms.Form, self).__init__(request) self.filters = [] self.filters.append(PatientFilter('All')) self.filters.append(PatientFilter('Assigned', 'service__isnull', False)) self.filters.append(PatientFilter('Unassigned', 'service__isnull', True)) self.addPhysicians(pg) self.fields['filter'] = forms.ChoiceField() for i, f in enumerate(self.filters): self.fields['filter'].choices.append((i, f.name)) ``` Clearing out the choices works but would surely result in threading issues.
This is actually a feature of Python that catches a lot of people. When you define variables on the class as you have with `filters = []` the right half of the expression is evaluated when the class is initially defined. So when your code is first run it will create a new list in memory and return a reference to this list. As a result, each `AssignmentFilterForm` instance will have its own filters variable, but they will all point to this same list in memory. To solve this just move the initialization of `self.filters` into your `__init__` method. Most of the time you don't run into this issue because the types you are using aren't stored as a reference. Numbers, booleans, etc are stored as their value. Strings are stored by reference, but strings are immutable meaning a new string must be created in memory every time it is changed and a new reference returned. Pointers don't present themselves often in scripting language, so it's often confusing at first when they do. Here's a simple IDLE session example to show what's happening ``` >>> class Test(): myList = [] def __init__( self ): self.myList.append( "a" ) >>> Test.myList [] >>> test1 = Test() >>> Test.myList ['a'] >>> test1.myList ['a'] >>> test2 = Test() >>> test2.myList ['a', 'a'] >>> test1.myList ['a', 'a'] >>> Test.myList ['a', 'a'] ```
Does django's Form class maintain state?
[ "", "python", "django", "" ]
Suppose I have two classes with identical members from two different libraries: ``` namespace A { struct Point3D { float x,y,z; }; } namespace B { struct Point3D { float x,y,z; }; } ``` When I try cross-casting, it worked: ``` A::Point3D pa = {3,4,5}; B::Point3D* pb = (B::Point3D*)&pa; cout << pb->x << " " << pb->y << " " << pb->z << endl; ``` Under which circumstances is this guaranteed to work? Always? Please note that it would be highly undesirable to edit an external library to add an alignment pragma or something like that. I'm using g++ 4.3.2 on Ubuntu 8.10.
If the structs you are using are just data and no inheritance is used I think it should always work. As long as they are POD it should be ok. <http://en.wikipedia.org/wiki/Plain_old_data_structures> According to the standard(1.8.5) "Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size. An object of POD5) type (3.9) shall occupy contiguous bytes of storage." If they occupy contiguous bytes of storage and they are the same struct with different name, a cast should succeed
If two POD structs start with the same sequence of members, the standard guarantees that you'll be able to access them freely through a union. You can store an A::Point3D in a union, and then read from the B::Point3D member, as long as you're only touching the members that are part of the initial common sequence. (so if one struct contained int, int, int, float, and the other contained int, int, int, int, you'd only be allowed to access the three first ints). So that seems like one guaranteed way in which your code should work. It also means the cast *should* work, but I'm not sure if this is stated explicitly in the standard. Of course all this assumes that both structs are compiled with the same compiler to ensure identical ABI.
Casting between unrelated congruent classes
[ "", "c++", "casting", "" ]
Say I want to insert into name, address, city, state, zip values $name, $address Etc..... How can I run `mysql_real_escape_string` on each of the variables before inserting. There has got to be a foreach or loop or while method instead of writing out each variable right? Thanks for the help. Tom so if I have ``` $data = array($address, $city, $name); array_map('mysql_real_escape_string', $data); ``` and ``` $columns = "name, address, city, state, zip"; $count = $dbh->exec("INSERT INTO customer($columns) VALUES ($data)"); ``` I get a ton of errors. ``` Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'root'@'localhost' (using password: NO) in /Users/tommyscott45/Sites/experiment/result.php on line 23 ``` now what?
A database error has occurred when trying to invoke `mysql_real_escape_string` and I see that you're using `$dbh->exec()` to execute the query. This suggests that you connect to the database with PDO, so you should rather use [`PDO::quote`](http://pl2.php.net/manual/en/pdo.quote.php) instead of `mysql_real_escape_string`. Moreover, as others have already mentioned, a better way to solve your problem would be to use prepared statements and [`PDO::prepare`](http://pl2.php.net/manual/en/pdo.prepare.php).
You use sprintf. For example ``` $query = sprintf("INSERT into TABLE name = '%s', address = '%s', city = '%s'", mysqli_escape_string($link, $name), mysqli_escape_string($link, $address), mysqli_escape_string($link, $city) ); ``` Or is that not exactly what you were looking for; a way to avoid typing "mysqli\_escape\_string" over and over again.
Mysql real escape string loop multiple variables
[ "", "php", "variables", "mysql-real-escape-string", "" ]
Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ? I mean the visual line, the browser computed line, and not the line in the source code .
## jQuery.fn.line: ``` jQuery.fn.line = function(line) { var dummy = this.clone().css({ top: -9999, left: -9999, position: 'absolute', width: this.width() }).appendTo(this.parent()), text = dummy.text().match(/\S+\s+/g); var words = text.length, lastTopOffset = 0, lineNumber = 0, ret = '', found = false; for (var i = 0; i < words; ++i) { dummy.html( text.slice(0,i).join('') + text[i].replace(/(\S)/, '$1<span/>') + text.slice(i+1).join('') ); var topOffset = jQuery('span', dummy).offset().top; if (topOffset !== lastTopOffset) { lineNumber += 1; } lastTopOffset = topOffset; if (lineNumber === line) { found = true; ret += text[i]; } else { if (found) { break; } } } dummy.remove(); return ret; }; ``` ## Usage: ``` $('#someParagraph').line(3); // blah blah blah ``` Example: **<http://jsbin.com/akave>** ## How it works: It goes through the entire element (actually, a clone of the element) inserting a **`<span/>`** element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.
Well, there's a way to guesstimate it, and it's not pretty, but I've used it before. The algorithm basically goes like this: 1. Create a "test" node, absolutely positioned within the block you want to measure. 2. Put some text in that test node. 3. Get the height of that test node. (We'll call it H.) This is your estimated height for a line. 4. Now create a duplicate block, with no text in it. 5. Iterate through a loop that will -- a) Take the content from the block, and add one word at a time to the new duplicate block. b) Check the height of the block. If the height falls between 4H and 6H, then you are within the range of the 5th line. Append that text to a buffer variable. 6. Your buffer variable will contain the text that is displayed on the fifth line. It's not pretty but it works if you duplicate the elements right.
Getting a specific line using jQuery
[ "", "javascript", "jquery", "ajax", "" ]
Here's the setup: My coworker has a Fedora x64\_86 machine with a gcc 4.3.3 cross compiler (from buildroot). I have an Ubuntu 9.04 x64\_86 machine with the same cross compiler. My coworker built an a library + test app that works on a test machine, I compiled the same library and testapp and it crashes on the same test machine. As far as I can tell, gcc built against buildroot-compiled ucLibc, so, same code, same compiler. What kinds of host machine differences would impact cross compiling? Any insight appreciated. Update: To clarify, the compilers are *identical*. The source code for the library and testapp is *identical*. The only difference is that the testapp + lib have been compiled on different machines..
If your code crashes (I assume you get a sigsegv), there seems to be a bug. It's most likely some kind of undefined behaviour, like using a dangling pointer or writing over a buffer boundary. The unfortunate point of undefined behaviour is, that it *may* work on some machines. I think you are experiencing such an event here. Try to find the bug and you'll know what happens :-)
In what way does it crash? Can you be more specific, provide output, return codes, etc... Have you tried plugging in some useful printf()'s? And, I think we need a few more details here: 1. Does the testapp link to the library? 2. Is the library static or dynamic? 3. Is the library in the library search path, or have you added its directory to ld.so.conf? 4. Are you following any installation procedures for the library and testapp? 5. Are the two libraries and testapps bit-for-bit compatible? Do you expect them to be? 6. Are you running as the same user as your coworker, with same environment and permissions?
Why does the library compiled on two slightly different machines behaves slightly different?
[ "", "c++", "gcc", "libraries", "cross-compiling", "buildroot", "" ]
I am using entities, C# and SQL Server to create an n-tier app. I am creating some base classes common to all my DAL components. In this base class, i want to handle the connection state of the ObjectContext base class inherited by entities object. Compiling throws the following error: > The type or namespace name 'Objects' > does not exist in the namespace > 'System.Data' (are you missing an > assembly reference?) Also, the using statement System.Data.Objects doesn't resolve for the same reason. I tried adding the assembly as reference, but couldn't find it in the .NET tab of assembly references. Any thoughts? Thanks!
You need to add a reference to the .NET assembly System.Data.Entity.dll.
If you are using Entity Framework 6, the name space has changed. You want to use ``` System.Data.Entity.Core.Objects.ObjectQuery ```
The type or namespace name 'Objects' does not exist in the namespace 'System.Data'
[ "", "c#", ".net", "visual-studio-2008", "linq-to-entities", "entities", "" ]
This would be similar to the `java.lang.Object.hashcode()` method. I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten.
``` id(x) ``` will do the trick for you. But I'm curious, what's wrong about the set of objects (which does combine objects by value)? For your particular problem I would probably keep the set of ids or of wrapper objects. A wrapper object will contain one reference and compare by `x==y` <==> `x.ref is y.ref`. It's also worth noting that Python objects have a `hash` function as well. This function is necessary to put an object into a set or dictionary. It is supposed to sometimes collide for different objects, though good implementations of `hash` try to make it less likely.
That's what "`is`" is for. Instead of testing "`if a == b`", which tests for the same value, test "`if a is b`", which will test for the same identifier.
Is there an object unique identifier in Python
[ "", "python", "" ]
Let's say I have a constructor like this: ``` MyColor(uint8 vec[]) { r = vec[0]; g = vec[1]; b = vec[2]; a = vec[3]; } ``` But I call it like this (3 elements instead of 4): ``` uint8 tmp[] = {1,2,3}; MyColor c(tmp); ``` But now `vec[3]` is undefined... is it safe to assign this value to `a`? If not, there's no nice workaround to check if `vec[3]` is set is there?
if you dont want to use vector try this... ``` MyColor(uint8 (&vec)[3]) { r = vec[0]; g = vec[1]; b = vec[2]; } MyColor(uint8 (&vec)[4]) { //... } uint8 a1[] = {1,2,3}; MyColor c1(a1); uint8 a2[] = {1,2,3,4}; MyColor c2(a2); uint8 a3[] = {1,2,3,4,5}; MyColor c3(a3); // error ``` you dont have to include the array's size explicitly and if you try to pass an array with wrong number of elements, compile error will be generated,
No it's not safe. It's undefined behavior as defined by the standard. It might blow the whole app up or return a random value. The workaround is to pass the size along with it, or use `vector` instead.
Is it safe to read past the end of an array?
[ "", "c++", "pointers", "" ]
This is a followup to my [own previous question](https://stackoverflow.com/questions/1218790/) and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA\_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward: ``` public static void startSecondJVM() throws Exception { String separator = System.getProperty("file.separator"); String classpath = System.getProperty("java.class.path"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp", classpath, AnotherClassWithMainMethod.class.getName()); Process process = processBuilder.start(); process.waitFor(); } ``` Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.
It's not clear to me that you would always want to use exactly the same parameters, classpath or whatever (especially -X kind of stuff - for example, why would the child need the same heap settings as its parents) when starting a secondary process. I would prefer to use an external configuration of some sort to define these properties for the children. It's a bit more work, but I think in the end you will need the flexibility. To see the extent of possible configuration settings you might look at thye "Run Configurations" settings in Eclipse. Quite a few tabs worth of configuration there.
I think that the answer is "Yes". This probably as good as you can do in Java using system independent code. But be aware that even this is only *relatively* system independent. For example, in some systems: 1. the JAVA\_HOME variable may not have been set, 2. the command name used to launch a JVM might be different (e.g. if it is not a Sun JVM), or 3. the command line options might be different (e.g. if it is not a Sun JVM). If I was aiming for maximum portability in launching a (second) JVM, I think I would do it using wrapper scripts.
Is *this* really the best way to start a second JVM from Java code?
[ "", "java", "jvm", "multiprocessing", "" ]
This could be a borderline advertisement, not to mention subjective, but the question is an honest one. For the last two months, I've been developing a new open source profiler for .NET called SlimTune Profiler (<http://code.google.com/p/slimtune/>). It's a relatively new effort, but when I looked at the range of profilers available I was not terribly impressed. I've done some initial work based on existing products, but I felt this would be a good place to ask: what exactly do you WANT from a profiler? I come from real time graphics and games, so it's important to me that a profiler be as fast as possible. Otherwise, the game becomes unplayable and profiling an unplayable slow game tends not to be very enlightening. I'm willing to sacrifice some accuracy as a result. I don't even care about exceptions. But I'm not very familiar with what developers for other types of applications are interested in. Are there any make or break features for you? Where do existing tools fall down? Again, I apologize if this is just way off base for StackOverflow, but it's always been an incredibly useful resource to me and there's a very wide range of developers here.
My requirements: * Collect stats without impact to application - e.g. don't fill up memory, allow data to be collected away from apps under question * Ability to specify measurements simply and repeatably (data driven) * Automatable so that I can repeat measurements without point and click, and without UI * Enable us to understand issues related to the WPF and other declarative technologies such as DLR or WF * No installation - no gac, msi etc, even better if can be run over a network * Support 64 bit from outset * Don't try to know all the the analysis that could be done - encourage an ecosystem. If the raw stats can be analysed using other tools so much the better. * UI if any should be good - but its the stats that matter. So don't spend time on that, get the core profiling good. + Support profiling of apps that are not straight exe's like services and web applications simply. would likes: * Consider cross app support - big apps often need to understand apps performance behavior across many executables. If your profiler allows easy correlation of this data then so much the better
My wish list: * Really easy to use - simple (yet powerful) GUI * **Spectacular performance** - ability to profile apps that are under extremely heavy usage. * **X64** and **X32** support * **Understands SQL**, is able to give me stack traces and duration for all my SQL calls, coupled with SQL. * Easy to profile, no need to go through a complex, recompile the app process. * Easy to profile services, web sites and processes which are launched as side effects * A "production mode" which allows you to gather key stats from a production based system. + "Automatic bottleneck finder" : run against a production app and using heuristics determine which methods are slow. * Per thread analysis, tell me which threads are doing all the work and where. * Profile at various granularities, allow to perform a "cheap" profile that only gathers key info and dig in with granular profiling. * Exception tracker, allow me to track all the exceptions which are thrown in my app (key stats and detailed info) * Per thread profiling - allow me to profile a single thread in an app
What features should a C#/.NET profiler have?
[ "", "c#", ".net", "performance", "profiler", "" ]
I have a problem, I wish to use reflection to generate instances of one of a set of classes at runtime. However, I have hit a snag. I want to get all of the classes involved to register themselves so the appropriate class can be chosen from a GUI. I can do this using a static code block in each file which provides a tidy OO solution. However, the java class loader specifically loads classes when they are required, hence if a needed class has not yet been used, it is not registered. Short of directly providing a static list of names, or running through the underlying class/java files (which would break when packaged into a jar anyway), is there any way to force classes of certain packages to be loaded? Basically, I want the ability to add new classes, from a specified superclass, without having to change/add any other code.
To clarify, your problem isn't about "dynamic class loading in Java", it's about **dynamic class enumeration** -- you know how to load classes, you just don't know what classes you want. A quick Google came up with this page: <http://forums.sun.com/thread.jspa?threadID=341935&start=0&tstart=0> Taken from that page, here's some sample code that ought to work: ``` public static Class[] getClasses(String pckgname) throws ClassNotFoundException { ArrayList<Class> classes = new ArrayList<Class>(); // Get a File object for the package File directory = null; try { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } String path = '/' + pckgname.replace('.', '/'); URL resource = cld.getResource(path); if (resource == null) { throw new ClassNotFoundException("No resource for " + path); } directory = new File(resource.getFile()); } catch (NullPointerException x) { throw new ClassNotFoundException(pckgname + " (" + directory + ") does not appear to be a valid package"); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension classes.add(Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6))); } } } else { throw new ClassNotFoundException(pckgname + " does not appear to be a valid package"); } Class[] classesA = new Class[classes.size()]; classes.toArray(classesA); return classesA; } ```
[Spring Framework](http://www.springsource.org) does component scanning based on annotations. Take a look at [ClassPathScanningCandidateComponentProvider](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html) class, for example. You can do the same thing based on interface / base class and it should work for all **LOCAL** classes. There is no way to do this for **ALL** classes in java.
Dynamic Class Loading in Java (Enumeration)
[ "", "java", "reflection", "oop", "" ]
I just saw a video of [Nicholas Zakas of Yahoo](http://www.youtube.com/watch?v=mHtdZgou0qU), at GoogleTalks talking about speeding up your website. One of the things he mentioned was doing loops in reverse order to skip one of two comparisons: `for (i = len; i--;) {}` And he said to keep away from JS libraries implementations of `for each`. Just for fun I thought I'd try it out. Turns out he was wrong. ``` var array1 = new Array(); var array2 = new Array(); var start = 0; var finished = 0; start = (new Date).getTime(); $("#newDivTest").children().each(function(i){ array1[i] = $(this).get(0).id; }); finished = (new Date).getTime() - start; alert(finished); start = (new Date).getTime(); var len = $("#newDivTest").children().length; for (i = len; i--;) { array2[i] = $(this).get(0).id; } finished = (new Date).getTime() - start; alert(finished); ``` newDivTest holds 1000 empty divs with an id starting at "0" and going up to "999". Another note is that `$(this).get(0).id` is about 3 times faster than `$(this).attr("id")` for some reason, anyone know why? For FF3.5, the results are "7" and "45", IE7 gives "30" and "45", Chrome2 gives "4" and "17", Opera10 gives "16" and "16", and lastly Safari4 gives "4" and "16". So it seems the approach Nicholas is hardest against is actually the faster in almost all instances. I'm not smart enough to know what's going on behind the scenes for jQuery's `each()`-method, but it must be doing something right...right?
One flaw in your setup is that your second test will not actually work. You wrote: ``` for (i = len; i--;) { array2[i] = $(this).get(0).id; } ``` But `this` is not defined there, so the entire operation will fail. You'd have to do something like: ``` var children = $("#newDivTest").children(); for (i = children.length; i--;) { array2[i] = children.get(i).id; } ``` And this gets at a more pressing issue than performance: although calls to something like jQuery's .each() function do result in added function calls (and the associated added overhead), they also tend to make it much easier to express what you want the code to do. Quoting Michael Jackson: "The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet."
I notice that your question is "JS looping and populating array. Which is faster?", but your examples are actually testing the speed of various selectors of JQuery, right? You might be interested in checking out :<http://mootools.net/slickspeed/> As for "JS looping and populating array. Which is faster?", see here : <http://blogs.oracle.com/greimer/resource/loop-test.html>
JS looping and populating array. Which is faster?
[ "", "javascript", "arrays", "optimization", "loops", "" ]
I'm trying to send a form to a PHP using `$.ajax` in [jQuery](http://en.wikipedia.org/wiki/JQuery). I send the whole thing as JSON, but, when I try to get the response, I get the 'parsererror'. What am I doing wrong? jQuery fragment: ``` $("form").submit(function(){ $.ajax({type: "POST", url: "inscrever_curso.php", data: {cpf : $("input#cpf").val(),nome : $("input#nome").val()}, dataType: "json", success: function(data){ alert("sucesso: "+data.msg); }, error: function(XMLHttpRequest, textStatus, errorThrown){ alert ("erro: "+textStatus); } }); return false; }); ``` PHP: ``` <?php $return[msg]="Testing, testing."; echo json_encode($return); ?> ```
I don't know if it's the cause of your problem, but here is one thing about your PHP code: ``` $return[msg]="Testing, testing."; echo json_encode($return); ``` Doing this, with E\_NOTICE error\_reporting level, you get: ``` Notice: Use of undefined constant msg - assumed 'msg' ``` If notices are enabled and displayed on your server, is will cause an output that is not valid JSON (the ouput contains the error message before the JSON string). To avoid that notice, you must use this syntax: ``` $return['msg']="Testing, testing."; echo json_encode($return); ``` Note the quotes around `msg`: the key of the array-element you are creating is a string constant, so, it is enclosed in quotes. If you don't put in these quotes, PHP searches for a [defined](http://php.net/define) constant called "msg", which probably doesn't exist. For more information about this, you can take a look at this section of the manual: *[Why is $foo[bar] wrong?](http://php.net/manual/en/language.types.array.php#language.types.array.foo-bar)*. (I am not sure it'll solve your problem, but it's good to know anyway.)
Your PHP code should probably be: ``` <?php $return = array(); $return['msg']="Testing, testing."; echo json_encode($return); ?> ```
jQuery, Ajax, JSON, PHP and parsererror
[ "", "php", "jquery", "ajax", "json", "" ]
is it possible to initialize a class by a string variable? I have code in PHP. ``` <?php $classname = "test"; $oTest = new $classname(); class test{ } ?> ``` how do I do this in c#?
``` System.Activator.CreateInstance(Type.GetType(className)) ``` The problem, however, is that C# 3.0 is a statically typed language. You can't just call random methods on the returned object. You can have the classes you might instantiate implement some common interface and cast the result of the above expression to the interface or manually use reflection to call methods on the returned object.
You can use the Activator.CreateInstance method to achieve a *similar* result. But you will have to provide the assembly name in addition to the fully qualified name of the type ``` var instance = Activator.CreateInstance("SomeAssemblyName","Some.Full.Type.Test"); ```
initialize a class by string variable in c#?
[ "", "c#", "class", "dynamic", "instance", "" ]
I have the following array setup, i,e: ``` var myArray = new Array(); ``` Using this array, I am creating a breadcrumb menu dynamically as the user adds more menu items. I am also allowing them to removing specific breadcrumb menu items by clicking on the cross alongside eatch breadcrumb menu item. Array may hold the following data: ``` myArray[0] = 'MenuA'; myArray[1] = 'MenuB'; myArray[2] = 'MenuC'; myArray[3] = 'MenuD'; myArray[4] = 'MenuE'; ``` My questions are: a) In JavaScript, how can I remove element [1] from myArray and then recalculate indexes or is this not possible? b) If I don't want menu option MenuB, do I need to splice it to remove it? My problem is, if the user removes menu items as well as create news one at the end, how will the indexes to these elements be spreadout? I just want to be able to remove items but don't know how the array indexes are handled.
I like [this implementation](http://ejohn.org/blog/javascript-array-remove/) of Array.remove, it basically abstracts the use of the [splice](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/splice) function: ``` // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; ``` Usage: ``` // Remove the second item from the array array.remove(1); // Remove the second-to-last item from the array array.remove(-2); // Remove the second and third items from the array array.remove(1,2); // Remove the last and second-to-last items from the array array.remove(-2,-1); ```
You could use `myArray.push('MenuA');` so you don't specify direct numbers when adding elements. To remove an element I.E. 'MenuB': ``` // another quick way to define an array myArray = ['MenuA', 'MenuB', 'MenuC', 'MenuD', 'MenuE']; // remove an item by value: myArray.splice(myArray.indexOf('MenuB'),1); // push a new one on myArray.push('MenuZ'); // myArray === ["MenuA", "MenuC", "MenuD", "MenuE", "MenuZ"] ```
Removing elements from JavaScript arrays
[ "", "javascript", "" ]
**How can you see the type of variables: POST, GET, cookie, other?, after running `var_dump($_REQUEST)`?** I run the following ``` start_session(); --- other code here -- var_dump($_REQUEST); ``` It gives me > array(3) { ["login"]=> string(0) "" ["sid"]=> string(32) > "b3408f5ff09bfc10c5b8fdeea5093d3e" > ["PHPSESSID"]=> string(32) > "b3408f5ff09bfc10c5b8fdeea5093d3e" }
I'm not sure I understand your question. Did you try: ``` var_dump($_POST); var_dump($_COOKIE); var_dump($_SESSION); ``` etc? `$_REQUEST` is a different variable than `$_POST` and the others. Was there something specific you are trying to see?
If by "the type of variables: POST, GET, cookie, other?" you mean "are the variables in `$_REQUEST`" coming from `$_GET`, `$_POST`, `$_COOKIE`, or environnement", I don't think there is a way : you will have to check inside those yourself... And, btw, you'll have to do that taking into account the order that PHP uses those to populate `$_REQUEST` ; it is configured by this directive : <http://php.net/manual/en/ini.core.php#ini.variables-order> But, still, why not work with `$_GET`, `$_POST` and others directly ? Would probably be much more easier...
To see the types of login variables in PHP's sessions
[ "", "php", "session", "" ]
I have a project that's intended to use some PHP as well as Java and Javascript, so I installed the PDT PHP plug-in for Eclipse, using the Install New Software menu option. Now Eclipse agrees PDT is installed, but no PHP features like creating or editing PHP files are appearing anywhere. Is there something else I need to do to activate PDT? (I did restart Eclipse like it said I needed to.)
The solution I eventually came up with was to just install Aptana Studio, a PHP IDE based on Eclipse, whose standalone version can coexist happily with the regular Eclipse on the same machine.
Right click on your project, Configure (it's at the bottom of the list)->Add PHP Support... After it's done, you should see a little P symbol in the project's icon.
Eclipse PDT installation
[ "", "php", "eclipse", "eclipse-pdt", "" ]
I just ran into a strange thing...there is some code on our site that is taking a giant SQL statement, modifying it in code by doing some search and replace based on some user values, and then passing it on to SQL Server as a query. I was thinking that this would be cleaner as a parameterized query to a stored proc, with the user values as the parameters, but when I looked more closely I see why they might be doing it...the table that they are selecting from is variably dependant on those user values. For instance, in one case if the values were ("FOO", "BAR") the query would end up being something like "SELECT \* FROM FOO\_BAR" Is there an easy and clear way to do this? Everything I'm trying seems inelegant. **EDIT:** I could, of course, dynamically generate the sql in the stored proc, and exec that (bleh), but at that point I'm wondering if I've gained anything. **EDIT2:** Refactoring the table names in some intelligent way, say having them all in one table with the different names as a new column would be a nice way to solve all of this, which several people have pointed out directly, or alluded to. Sadly, it is not an option in this case.
First of all, you should *NEVER* do SQL command compositions on a client app like this, *that's* what SQL Injection is. (Its OK for an admin tool that has no privs of its own, but not for a shared use application). Secondly, yes, a parametrized call to a Stored procedure is both cleaner and safer. *However*, as you will need to use Dynamic SQL to do this, you still do not want to include the passed string in the text of the executed query. Instead, you want to used the passed string to look up the names of the *actual* tables that the user should be allowed to query in the way. Here's a simple naive example: ``` CREATE PROC spCountAnyTableRows( @PassedTableName as NVarchar(255) ) AS -- Counts the number of rows from any non-system Table, *SAFELY* BEGIN DECLARE @ActualTableName AS NVarchar(255) SELECT @ActualTableName = QUOTENAME( TABLE_NAME ) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @PassedTableName DECLARE @sql AS NVARCHAR(MAX) SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';' EXEC(@SQL) END ``` --- Some have fairly asked why this is safer. Hopefully, little Bobby Tables can make this clearer: 0 ![alt text](https://imgs.xkcd.com/comics/exploits_of_a_mom.png) --- Answers to more questions: 1. QUOTENAME alone is not guaranteed to be safe. MS encourages us to use it, but they have not given a guarantee that it cannot be out-foxed by hackers. FYI, real Security is all about the guarantees. The table lookup with QUOTENAME, is another story, it's unbreakable. 2. QUOTENAME is not strictly necessary for this example, the Lookup translation on INFORMATION\_SCHEMA alone is normally sufficient. QUOTENAME is in here because it is good form in security to include a complete and correct solution. QUOTENAME in here is actually protecting against a distinct, but similar potential problem know as *latent injection*. --- I should note that you can do the same thing with dynamic Column Names and the `INFORMATION_SCHEMA.COLUMNS` table. You can also bypass the need for stored procedures by using a parameterized SQL query instead (see here: <https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8>). But I think that stored procedures provide a more manageable and less error-prone security facility for cases like this.
(Un)fortunately there's no way of doing this - you can't use table name passed as a parameter to stored code other than for dynamic sql generation. When it comes to deciding where to generate sql code, I prefer application code rather that stored code. Application code is usually faster and easier to maintain. In case you don't like the solution you're working with, I'd suggest a deeper redesign (i.e. change the schema/application logic so you no longer have to pass table name as a parameter anywhere).
How should I pass a table name into a stored proc?
[ "", "sql", "sql-server", "t-sql", "sql-injection", "parameterized", "" ]
I have two JSON objects in Javascript, identical except for the numerical values. It looks like this: ``` var data = { "eth0":{"Tx":"4136675","Rx":"13232319"}, "eth1":{"Tx":"4","Rx":"0"}, "lo":{"Tx":"471290","Rx":"471290"} } var old = { "eth0":{"Tx":"4136575","Rx":"13232219"}, "eth1":{"Tx":"4","Rx":"0"}, "lo":{"Tx":"471290","Rx":"471290"} } ``` One object called "data" has the current values, another object called "old" has the same values from 1 second ago. I'd like to output a JSON object with only the *change* in values so I can calculate data throughput on the network interfaces. ``` var throughput = { "eth0":{"Tx":"100","Rx":"100"}, "eth1":{"Tx":"0","Rx":"0"}, "lo":{"Tx":"0","Rx":"0"} } ``` I'm not sure how to go about traversing the JSON data - it could be for any number of interfaces. Can anyone please lend me a hand? Thanks in advance
You can iterate through the parent and child object properties: ``` var diff = {}; for(var p in data){ if (old.hasOwnProperty(p) && typeof(data[p]) == 'object'){ diff[p] = {}; for(var i in data[p]){ if (old[p].hasOwnProperty(i)){ diff[p][i] = data[p][i] - old[p][i]; } } } } ```
The basic premise for iterating over objects in JavaScript is like so ``` var whatever = {}; // object to iterate over for ( var i in whatever ) { if ( whatever.hasOwnProperty( i ) ) { // i is the property/key name // whatever[i] is the value at that property } } ``` Fixing up a checker wouldn't be too hard. You'll need recursion. I'll leave that as an exercise for you or another SOer.
Difference in JSON objects using Javascript/JQuery
[ "", "javascript", "jquery", "json", "" ]
I have been trying out the CTP Beta 1 of Visual Studio 2010 and I hate that VS10 doesn't autocomplete the best match when i press 'enter', or '.'. Visual Studio 2008 did this, and I haven't been able to find any options for this under Tools -> Options -> Text Editor. It kinda breaks my flow each time when I press enter (and get a new line), and I never really seem to get used to it. It's not too great having to press up, then down, then enter, to autocomplete the suggested member name. Also if there is any shortcut to autocomplete the (not selected) keyword, I'd be happy with that too.
As aaaaaa said, there are two modes of IntelliSense in Visual Studio 2010. The one you are used to is called stardard mode and it works similarly(1) as in previous versions. The new mode is called consume-first mode and is intended to ease life for those who code using types and members before they're defined. TDD practicioners use that a lot. In Beta 1, you can toggle between the two modes pressing `CTRL`+`ALT`+`SPACEBAR`. You can find more information about these changes at: * [What's New in the Visual Studio 2010](http://msdn.microsoft.com/en-us/library/dd465268(VS.100).aspx) * [List Members](http://msdn.microsoft.com/en-us/library/exbffbc2(VS.100).aspx) (1) When I stated above that it works similarly, that because in addition to working as it did before, there's an enhanced searching algorithim that can ease the finding of the member you want. Let's say you want to print a line to the console. You would use: ``` Console.WriteLine("...."); ``` When typing that you could do any of the following: * Type Console.WriteL and press Enter (2) * Console.WL and press down arrow key to the WriteLine member and then press Enter (2) * Console.line and press the down arrow key to the WriteLine member and then press Enter (2) (2) You can press Enter or any of the characters define in Tools -> Options -> Text Editor -> C# -> IntelliSense
VS10 has two modes of intellisense, one works like the old but the other searches not only from the beginning of the word but everywhere in it. If you have the second mode you won't be able to complete the word with enter. I can't remember how to switch between them though but might be a little help.
How to get VS10 Intellisense to complete suggested member on enter?
[ "", "c#", "visual-studio-2010", "intellisense", "" ]
We include the CSS file via standard HTML STYLE tag. Then we need the javascript code to access the CSS classes and attributes. in IE and Chrome all goes fine, but in Firefox it throws this exception: uncaught exception: Security error (NS ERROR DOM SECURITY ERR) here's the javascript code: ``` for (var i = 0; i != window.document.styleSheets.length; i++) { rules = window.document.styleSheets.item(i); if(rules.href.indexOf('someurl.com')){ break; } } return rules.cssRules || rules.rules; ``` it works fine in IE, Chrome and Safari, but it doens't in Firefox and Opera. any ideas? thanks in advance
JavaScript can be referenced from any domain, but can only enact changes to the exact domain of the document that is executing it. By exact domain I mean everything from the protocol to just before the first directory must be identical. You are not supposed to be able to use JavaScript to access a different domain. I am not sure why this is working in IE or Chrome, but it should not be. If the CSS is from domain different than the page executing the JavaScript you will be thrown a security error. The real question here is: what property is item? I do not see that defined in your code and I have not seen that used before. Why are you trying to change the stylesheet with JavaScript instead of simply applying style changes directly to the DOM where security issues are not raised?
I'd say you are trying to change the style before it has loaded at all in FF. You could try moving the Javascript invocation to just before the closing tag, and also creating that method on the window.onLoad event or it's equivalent if you are using a JS Library.
Accessing CSS classes in a css file, cross-domain, in javascript
[ "", "javascript", "css", "firefox", "" ]
Is it possible, using C# Automatic Properties, to create a new instance of an object? in C# I love how I can do this: ``` public string ShortProp {get; set;} ``` is it possible to do this for objects like List that first need to be instantiated? ie: ``` List<string> LongProp = new List<string>(); public List<string> LongProp { get { return LongProp ; } set { LongProp = value; } } ```
You can initialize your backing field on the constructor: ``` public class MyClass { public List<object> ClinicalStartDates {get; set;} ... public MyClass() { ClinicalStartDates = new List<object>(); } } ``` But... are you sure about making this list a property with a public setter? I don't know your code, but maybe you should expose less of your classes' properties: ``` public class MyClass { public List<object> ClinicalStartDates {get; private set;} ... public MyClass() { ClinicalStartDates = new List<object>(); } } ```
You will have to initialize it in the constructor: ``` class MyClass { public MyClass() { ShortProp = "Some string"; } public String ShortProp { get; set; } } ```
How to return a new instance of an object in C# Automatic Properties
[ "", "c#", ".net", "properties", "automatic-properties", "" ]
Let's say I have a bunch of HTML like below: ``` bla bla bla long paragraph here <br/> <br/> bla bla bla more paragraph text <br/> <br/> ``` Is there an easy way with Javascript to convert it to properly semantic `<p>` tags? E.g.: ``` <p> bla bla bla long paragraph here </p> <p> bla bla bla more paragraph text </p> ``` Output spacing is not important, ideally it will work with any input spacing. I'm thinking I might try to cook up a regex, but before I do that I wanted to make sure I was a) avoiding a world of hurt and b) there wasn't something else out there - I'd tried to do a google search but haven't yet come up with anything. Thanks for any advice!
I got bored. I'm sure there are optimizations / tweaks needed. Uses a little bit of jQuery to do its magic. Worked in FF3. And the answer to your question is that there isnt a very "simple" way :) ``` $(function() { $.fn.pmaker = function() { var brs = 0; var nodes = []; function makeP() { // only bother doing this if we have nodes to stick into a P if (nodes.length) { var p = $("<p/>"); p.insertBefore(nodes[0]); // insert a new P before the content p.append(nodes); // add the children nodes = []; } brs=0; } this.contents().each(function() { if (this.nodeType == 3) // text node { // if the text has non whitespace - reset the BR counter if (/\S+/.test(this.data)) { nodes.push(this); brs = 0; } } else if (this.nodeType == 1) { if (/br/i.test(this.tagName)) { if (++brs == 2) { $(this).remove(); // remove this BR from the dom $(nodes.pop()).remove(); // delete the previous BR from the array and the DOM makeP(); } else { nodes.push(this); } } else if (/^(?:p)$/i.test(this.tagName)) { // these tags for the P break but dont scan within makeP(); } else if (/^(?:div)$/i.test(this.tagName)) { // force a P break and scan within makeP(); $(this).pmaker(); } else { brs = 0; // some other tag - reset brs. nodes.push(this); // add the node // specific nodes to not peek inside of - inline tags if (!(/^(?:b|i|strong|em|span|u)$/i.test(this.tagName))) { $(this).pmaker(); // peek inside for P needs } } } }); while ((brs--)>0) { // remove any extra BR's at the end $(nodes.pop()).remove(); } makeP(); return this; }; // run it against something: $(function(){ $("#worker").pmaker(); }); ``` And this was the html portion I tested against: ``` <div id="worker"> bla bla bla long <b>paragraph</b> here <br/> <br/> bla bla bla more paragraph text <br/> <br/> this text should end up in a P <div class='test'> and so should this <br/> <br/> and this<br/>without breaking at the single BR </div> and then we have the a "buggy" clause <p> fear the real P! </p> and a trailing br<br/> </div> ``` And the result: ``` <div id="worker"><p> bla bla bla long <b>paragraph</b> here </p> <p> bla bla bla more paragraph text </p> <p> this text should end up in a P </p><div class="test"><p> and so should this </p> <p> and this<br/>without breaking at the single BR </p></div><p> and then we have the a "buggy" clause </p><p> fear the real P! </p><p> and a trailing br</p> </div> ```
Scan each of the child elements + text of the enclosing element. Each time you encounter a "br" element, create a "p" element, and append all pending stuff to it. Lather, rinse, repeat. Don't forget to remove the stuff which you are relocating to a new "p" element. I have found [this library (prototype.js)](http://www.prototypejs.org/api/element) to be useful for this sort of thing.
Is there an easy way to convert HTML with multiple <br/> tags into proper surrounding <p> tags in Javascript?
[ "", "javascript", "html", "semantics", "semantic-markup", "" ]
I know this is not exactly reflection, but kind of. I want to make a debug function that gets a variable and prints a var\_dump and the variable name. Of course, when the programmer writes a call to the function, they *already know* the variable's name, so they could write something like: ``` debug( $myvar, 'myvar' ); ``` But I want it to be quick and easy to write, just the function name, the variable, and voilà ! ``` debug( $myvar ); // quicker and easier :) ```
You can do it by converting the variable to a key/value set before passing it to the function. ``` function varName($theVar) { $variableName = key($theVar); $variableValue = $theVar[$variableName]; echo ('The name of the variable used in the function call was '.$variableName.'<br />'); echo ('The value of the variable used in the function call was '.$variableValue.'<br />'); } $myVar = 'abc'; varName(compact('myVar')); ``` Though I don't recommend creating a reference to a nameless variable, `function varName(&$theVar)` works too. Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy. As to why you would want to do this -- don't ask me but it seems like a lot of people ask the question so here's my solution.
I know I'm answering a 4 year old question but what the hell... [compact()](http://php.net/manual/en/function.compact.php) might help you is your friend here! I made a similar function to quickly dump out info on a few chosen variables into a log for debugging errors and it goes something like this: ``` function vlog() { $args = func_get_args(); foreach ($args as $arg) { global ${$arg}; } return json_encode(compact($args)); } ``` I found JSON to be the cleanest and most readable form for these dumps for my logs but you could also use something like [print\_r()](http://php.net/manual/en/function.print-r.php) or var\_export(). This is how I use it: ``` $foo = 'Elvis'; $bar = 42; $obj = new SomeFancyObject(); log('Something went wrong! vars='.vlog('foo', 'bar', 'obj')); ``` And this would print out like this to the logs: > Something went wrong! vars={"foo":"Elvis","bar":42,"obj":{"nestedProperty1":1, "nestedProperty2":"etc."}} Word of warning though: This will only work for variables declared in the global scope (so not inside functions or classes. In there you need to evoke compact() directly so it has access to that scope, but that's not really that big of a deal since this vlog() is basically just a shortcut for json\_encode(compact('foo', 'bar', 'obj')), saving me 16 keystrokes each time I need it.
Is there a way to get the name of a variable? PHP - Reflection
[ "", "php", "reflection", "" ]
I made a plugin for email entity and registered it on Pre Create event (child pipeline). Plugin is as simple as possible: ``` public class AddDescription : IPlugin { public void Execute(IPluginExecutionContext context) { DynamicEntity di = (DynamicEntity)context.InputParameters["Target"]; di.Properties["description"] = "blabla"; } } ``` But description (=email body) stays the same. No exceptions are thrown. I debuged and it looks like Properties collection is changed ('blabla' description added) but it is not saved. If I register the same plugin on account entity (Pre Create, child pipeline) it works fine. Does email entity have any restrictions about changing properties on create?!!? **EDIT (MORE INFO):** I tried to change description, subject, category and subcategory and to my surprise category and subcategory changed while description and subject didn't. tnx for help bye
Why are you in the child pipeline? My guess is the base activity is created in the main pipeline and the child activity (as Matt points out - only contains non-shared attributes) then goes through the child pipeline. Does this work as you expect in the parent pipeline? Maybe there's a scenario you have to catch in the child pipeline?
My guess would be that it's because subject and description are attributes shared across all activities (on the activitypointer entity), while category and subcategory are on the email entity. When you debug, see if there's a property that is another DynamicEntity... this might be where the properties that go to the activity are stored.
MS CRM - Pre Create plugin doesn't change property value
[ "", "c#", "plugins", "dynamics-crm", "" ]
I have a user control defined on an page as follows: ``` <uc:MyUserControl ID="MyUserControl" runat="server" Visible="true" /> ``` I am wanting to reuse the same control on a different page with a custom property as follows: ``` <uc:MyUserControl ID="MyUserControl" runat="server" Visible="true" MyCustomProperty="MyCustomText" /> ``` The purpose of MyCustomProperty is to control some text in MyUserControl to be whatever I specify it to be. For the first case I want the text to be "View" and for the second case I want it to be "MyCustomText". In my user control I have the following code to define the property: ``` [DefaultValue("View")] public string MyCustomProperty { get; set; } ``` I also have the following code to update the text based on the property: ``` LinkButton buttonSelect = e.Item.FindControl("ButtonSelect") as LinkButton; if(buttonSelect != null) buttonSelect.Text = MyCustomProperty; ``` What actually happens is that when the custom property isn't supplied in the first case then MyCustomProperty == null. I've tried to specify that the default should be "View" by adding the DefaultValue attribute but it hasn't had the affect that I intended. Can anyone spot what I'm doing wrong?
The `DefaultValueAttribute` is used by visual designers and code generators to identify the default value, so they can more intelligently generate code. In Visual Studio, this attribute will cause a property to be shown in bold when the property returns a value that differs from the value declared in the attribute. `DefaultValueAttribute` does not actually set the default value of the property for you. To do this, simply specify a suitable default value in your constructor. In your case: ``` public partial class MyUserControl { public MyUserControl() { MyCustomProperty = "View"; } ... } ``` Also, be aware that the property as you have coded it will not survive Postbacks. If this is important behaviour between round trips, be sure to add it to view state!
How about setting the property value explicitly rather than using the DefaultValue attribute? ``` private string _MyCustomProperty = "View"; public string MyCustomProperty { get { return _MyCustomProperty; } set { _MyCustomProperty = value; } } ```
How do I set a default value for a ASPX UserControl property?
[ "", "c#", "user-controls", "default-value", "custom-properties", "" ]
I am trying to decode some UTF-8 strings in Java. These strings contain some combining unicode characters, such as CC 88 (combining diaresis). The character sequence seems ok, according to <http://www.fileformat.info/info/unicode/char/0308/index.htm> But the output after conversion to String is invalid. Any idea ? ``` byte[] utf8 = { 105, -52, -120 }; System.out.print("{{"); for(int i = 0; i < utf8.length; ++i) { int value = utf8[i] & 0xFF; System.out.print(Integer.toHexString(value)); } System.out.println("}}"); System.out.println(">" + new String(utf8, "UTF-8")); ``` Output: ``` {{69cc88}} >i? ```
The console which you're outputting to (e.g. windows) may not support unicode, and may mangle the characters. The console output is not a good representation of the data. Try writing the output to a file instead, making sure the encoding is correct on the FileWriter, then open the file in a unicode-friendly editor. Alternatively, use a debugger to make sure the characters are what you expect. Just don't trust the console.
Here how I finally solved the problem, in Eclipse on Windows: 1. Click **Run Configuration**. 2. Click **Arguments** tab. 3. Add `-Dfile.encoding=UTF-8` 4. Click **Common** tab. 5. Set **Console Encoding** to `UTF-8`. Modify the code: ``` byte[] utf8 = { 105, -52, -120 }; System.out.print("{{"); for(int i = 0; i < utf8.length; ++i) { int value = utf8[i] & 0xFF; System.out.print(Integer.toHexString(value)); } System.out.println("}}"); PrintStream sysout = new PrintStream(System.out, true, "UTF-8"); sysout.print(">" + new String(utf8, "UTF-8")); ``` Output: ``` {{69cc88}} > ï ```
Java UTF-8 strange behaviour
[ "", "java", "utf-8", "" ]
I want to talk to the application that was used just before my application, how can I find out which application had focus last?
Before creating your own application window, call GetForegroundWindow. Otherwise call GetWindow(your\_hwnd,GW\_HWNDNEXT) to find the next window, below the specified.
I am looking for the same - I have an application that stays open on the screen and the user can invoke a button on my app once they have made an entry into one of three 3rd party applications. When they click the button on my app, I need to determine which of the three applications they last used in order to know which database to talk to. I have gone down the route of looking at GetForeGroundWindow and GetWindow however the Window handle I get from GetWindow always refers to a window with title M. I have used the Winternal Explorer tool from the Managed Windows API tools and I can locate the M handle being returned and it is a 'child' of the process that I am after - but from this handle I cant get the process name. I have done up a small example app using simple windows forms - and I lauch it and then make Notepad the focus and then click on my button and I get the handle - but when looking at the MainWindowHandle of all the processes, it is not listed, but using Winternal Explorer I can see that is a sub process of the notepad process. Any suggestions on why I am only getting this subprocess handle returned instead of the actual process handle?? Sample code is below - being run on a Windows XP sp 3 machine ``` using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace TestWindowsAPI { public partial class Form1 : Form { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { IntPtr thisWindow = GetForegroundWindow(); IntPtr lastWindow = GetWindow(thisWindow, 2); tbThisWindow.Text = thisWindow.ToString(); tbLastWindow.Text = lastWindow.ToString(); } } } ```
How do I track the application z-order/focus?
[ "", "c#", "windows", "" ]
Are there any Java APIs to find out the JDK version a class file is compiled for? Of course there is the javap tool to find out the major version as mentioned in [here](https://stackoverflow.com/questions/1096148/how-to-check-the-jdk-version-used-to-compile-a-class-file). However I want to do it programmatically so that that I could warn the user to compile it for the appropriate JDK
``` import java.io.*; public class ClassVersionChecker { public static void main(String[] args) throws IOException { for (int i = 0; i < args.length; i++) checkClassVersion(args[i]); } private static void checkClassVersion(String filename) throws IOException { DataInputStream in = new DataInputStream (new FileInputStream(filename)); int magic = in.readInt(); if(magic != 0xcafebabe) { System.out.println(filename + " is not a valid class!");; } int minor = in.readUnsignedShort(); int major = in.readUnsignedShort(); System.out.println(filename + ": " + major + " . " + minor); in.close(); } } ``` The possible values are : ``` major minor Java platform version 45 3 1.0 45 3 1.1 46 0 1.2 47 0 1.3 48 0 1.4 49 0 5 50 0 6 51 0 7 52 0 8 53 0 9 54 0 10 55 0 11 56 0 12 57 0 13 58 0 14 59 0 15 60 0 16 61 0 17 62 0 18 63 0 19 ``` ref : [The Java Virtual Machine Specification, Java SE 19 Edition](https://docs.oracle.com/javase/specs/jvms/se19/html/jvms-4.html#jvms-4.1)
basszero's approach can be done via the UNIX command line, and the "od(1)" command: ``` % od -x HelloWorldJava.class |head -2 0000000 feca beba 0000 3100 dc00 0007 0102 2a00 0000020 6f63 2f6d 6e65 6564 6163 642f 6d65 2f6f ``` "feca beba" is the [magic number](http://www.artima.com/insidejvm/whyCAFEBABE.html). The "0000 3100" is 0x31, which represents J2SE 5.0.
Java API to find out the JDK version a class file is compiled for?
[ "", "version", "java", "" ]
How to run database scripts(MySql db scripts) in c#. Thanks, sirni.
Fork a child process and execute the `mysql` command-line client, using the script as input. It's tempting to try to read the script as a file and execute the SQL commands within it one by one, but there are numerous statements in an SQL script that can't be executed that way. So you'd have to duplicate the code of the mysql client anyway in order to run an SQL script. Do yourself a favor and use the program that is already designed for that purpose.
You need to open a connection to the database then create a command object and use the ExecuteNonQuery method (if you don't expect any result) or one of the other Execute... commands. Set the CommandText of the command object to the content of the script to execute. One example here: <http://database-programming.suite101.com/article.cfm/how_to_add_records_to_mysql_with_c>
Running Database scripts in C#
[ "", "c#", "database", "scripting", "" ]
Say I have three classes A, B and C and they are nested in such a manner that I can access C through B through A (ie. A.B.C). If I'm trying to access a simple property of C, say Id type int, and I haven't instanciated a new instace of B in A (or C in B) I would get an 'Object reference not set to an instance of an object.' error. What I'd like to know is if there is a simple way of saying get me A.B.C.Id and if you can't becuase something is null along the way give me a default value. ``` var myId = A.B.C.Id <some operator> -1; ``` At the moment I'm doing something like this and it just feels horrible. ``` var myId = A == null ? -1 : A.B == null ? -1 : A.B.C == null ? -1 : A.B.C.Id; ```
In C# is no special syntax which can do what you want to do. But there is some architectonic ways, how to do it. You can use a [Null Object Design Pattern](http://www.google.cz/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FNull_Object_pattern&ei=S3SBSpW1BJTFsgby9JHMCQ&usg=AFQjCNEksAKL-3RfMRJIDnCX3QVzj-xvng&sig2=coIQblzH-ah8iinAm2lKKg) or you can extend the A, B, C classes with extension methods which allows null: ``` var myId = A.BOrNull().COrNull().IdOrNull(); public class A { public B B { get; set; } } public static class AExtensionMethods { public static B BOrNull( this A a ) { return null != a ? a.B : null; } } public class B { public C C { get; set; } } public static class BExtensionMethods { public static C COrNull( this B b ) { return null != b ? b.C : null; } } public class C { public int Id { get; set; } } public static class CExtensionMethods { public static int? IdOrNull( this C c ) { return null != c ? (int?)c.Id : null; } } ```
references C by going through A or B or both breaks the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter) which is bad practise. If something is needs to be referenced that way have a empty constructor that builds the connections that way.
Object reference not set to an instance of an object. - DefaultValue
[ "", "c#", "" ]
I'm writing a system that has a set of protocol buffers (using protobuf-net), I want to define something like this in an abstract class they all inherit off: ``` public byte[] GetBytes() ``` however, the protocol buffer serealiser requires a type argument, is there some efficient way to get the type of the inheriting class? Example: ``` public byte[] GetBytes() { using (MemoryStream stream = new MemoryStream()) { Serializer.Serialize<T /* what goes here? */>(stream, this); return stream.ToArray(); } } ```
Just write "T" right? and then in your class declaration: ``` public class M<T> ``` ? -- Edit And then when you inherit it: ``` public class Foo : M<Apple> ```
Define your base class as `BaseClass<T>` and then your derived classes replace T with the serializer type `DerivedClass<SerializerType>`. You can also specify constraints on the type argument e.g. ``` BaseClass<T> where T : SerializerBase ``` [Here](http://msdn.microsoft.com/en-us/library/d5x73970%28VS.80%29.aspx) is a description of the types of constraints you can apply.
C# generic type in a base class
[ "", "c#", "generics", "protocol-buffers", "protobuf-net", "" ]
Is there a preferred approach to isolating functions in a .js file from potential conflicts with other .js files on a page due to similar names? For example if you have a function ``` function AddTag(){} ``` in Core.js and then there is a ``` function AddTag(){} ``` in Orders.js they would conflict. How would you best structure your .js files and what naming conventions would you use to isolate them? Thanks
I limit the scope of the function to that file. ``` (function () { var AddTag = function AddTag () { }; }()); ``` … and sometimes make some functions in it available to the global scope: ``` var thisNamespace = function () { var AddTag = function AddTag () { … }; var foo = function foo() { AddTag(); … }; var bar = function bar() { … }; return { foo: foo, bar: bar } }(); ```
You can use 'namespacing'. Like this ``` File1.js: var Orders = {} (function(o) { o.function1 = function() {} o.function2 = function() {} })(Orders); File2.js var Sales = {} (function(o) { o.function1 = function() {} o.function2 = function() {} })(Sales); ``` You can invoke them like this: ``` Sales.function1(); Orders.function1(); ``` In general do not use global functions/variables. Read about javascript module pattern here <http://yuiblog.com/blog/2007/06/12/module-pattern/>
Best approach avoid naming conflicts for javascript functions in separate .js files?
[ "", "javascript", "" ]
I have had this problem for the last day. I have created a SOAP Extension following the MSDN articles and a load of blog posts but I just can't get it to work. Ok Some code: ``` public class EncryptionExtension : SoapExtension { Stream _stream; public override object GetInitializer(Type serviceType) { return typeof(EncryptionExtension); } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return attribute; } public override void Initialize(object initializer) { } public override void ProcessMessage(SoapMessage message) { switch (message.Stage) { case SoapMessageStage.BeforeSerialize: break; case SoapMessageStage.AfterSerialize: break; case SoapMessageStage.BeforeDeserialize: break; case SoapMessageStage.AfterDeserialize: break; default: throw new Exception("invalid stage"); } } public override Stream ChainStream(Stream stream) { _stream = stream; return stream; } } ``` There is also an attribute class: ``` [AttributeUsage(AttributeTargets.Method)] public class EncryptionExtensionAttribute : SoapExtensionAttribute { public override Type ExtensionType { get { return typeof(EncryptionExtension); } } public override int Priority { get; set; } } ``` So when the message comes in I can see the inbound SOAP request when I debug at the BeforeDeserialization and AfterDeserialization, which is great. My web service method is then called. Which is simply: ``` [WebMethod()] [EncryptionExtension] public string HelloWorld() { return "Hello world"; } ``` The process then hops back into my SoapExtension. Putting break points at BeforeSerialization and AfterSerialization I see that the outbound stream contains nothing. I am not surprised that it is empty on the BeforeSerialization but i am surprised that it is empty at AfterSerialization. This creates a problem because I need to get hold of the outbound stream so I can encrypt it. Can someone tell me why the outbound stream is empty? I have followed this MSDN article which indiciates it shouldn't be <http://msdn.microsoft.com/en-us/library/ms972410.aspx>. Am I missing some configuration or something else?
I found this question among the top hits for a google search on "SoapExtension MSDN" (which also finds the doc with example code as the top hit), so here are some helpful suggestions to anyone else trying to make sense of the sometimes confusing or contradictory docs on coding Soap extensions. If you are modifying the serialized message (as a stream) you need to create and return a different stream from the ChainStream override. Otherwise, you're saying that your extension doesn't modify the stream and just lets it pass through. The example uses a MemoryStream, and that's probably what you have to use because of the weird design: When ChainStream is called you don't know if you are sending or receiving, so you have to be prepared to handle it either way. I think even if you only process it in one direction you still have to handle the other direction and copy the data from one stream to the other anyway because you are inserting yourself in the chain without knowing which way it is. ``` private Stream _transportStream; // The stream closer to the network transport. private MemoryStream _accessStream; // The stream closer to the message access. public override Stream ChainStream(Stream stream) { // You have to save these streams for later. _transportStream = stream; _accessStream = new MemoryStream(); return _accessStream; } ``` Then you have to handle the AfterSerialize and BeforeDeserialize cases in ProcessMessage. I have them calling ProcessTransmitStream(message) and ProcessReceivedStream(message) respectively to help keep the process clear. ProcessTransmitStream takes its input from \_accessStream (after first resetting the Postion of this MemoryStream to 0) and writes its output to \_transportStream--which may allow very limited access (no seek, etc), so I suggest processing first into a local MemoryStream buffer and then copying that (after resetting its Postion to 0) into the \_transportStream. (Or if you process it into a byte array or string you can just write from that directly into the \_transportStream. My use case was compression/decompression so I'm biased towards handling it all as streams.) ProcessReceivedStream takes its input from \_transportStream and writes its output to \_accessStream. In this case you should probably first copy the \_transportStream into a local MemoryStream buffer (and then reset the buffer's Position to 0) which you can access more conveniently. (Or you can just read the entire \_transportStream directly into a byte array or other form if that's how you need it.) Make sure you reset the \_accessStream.Position = 0 before returning so that it is ready for the next link in the chain to read from it. That's for changing the serialized stream. If you aren't changing the stream then you should not override ChainStream (thus taking your extension out of the chain of stream processing). Instead you would do your processing in the BeforeSerialize and/or AfterDeserialize stages. In those stages you don't modify or access the streams but instead work on the message object itself such as adding a custom SoapHeader to the message.Headers collection in the BeforeSerialize stage. The SoapMessage class itself is abstract, so what you really get is either a SoapClientMessage or a SoapServerMessage. The docs say you get a SoapClientMessage on the client side and a SoapServerMessage on the server side (experimenting in the debugger should be able to confirm or correct that). They seem pretty similar in terms of what you can access, but you have to cast to the right one to access it properly; using the wrong one would fail, and the base SoapMessage type declared for the parameter to ProcessMessage doesn't give you access to everything. I haven't looked at the attribute stuff yet (it won't be a part of what I'm coding), so I can't help with how to use that part.
I ran into this post while trying to write a SoapExtension that would log my web service activity at the soap level. This script is tested and works to log activity to a text file when used on the server side. The client side is not supported. To use just replace 'C:\Your Destination Directory' with the actual directory you want to use for log file writes. This work cost me an entire day so I am posting it in hopes that others won't have to do the same. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Services; using System.Web.Services.Protocols; using System.IO; using System.Net; using System.Reflection; public class WebServiceActivityLogger : SoapExtension { string fileName = null; public override object GetInitializer(Type serviceType) { return Path.Combine(@"C:\Your Destination Directory", serviceType.Name + " - " + DateTime.Now.ToString("yyyy-MM-dd HH.mm") + ".txt"); } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return Path.Combine(@"C:\Your Destination Directory", methodInfo.DeclaringType.Name + " - " + DateTime.Now.ToString("yyyy-MM-dd HH.mm") + ".txt"); } public override void Initialize(object initializer) { fileName = initializer as string; } Dictionary<int, ActivityLogData> logDataDictionary = new Dictionary<int, ActivityLogData>(); private ActivityLogData LogData { get { ActivityLogData rtn; if (!logDataDictionary.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out rtn)) return null; else return rtn; } set { int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId; if(logDataDictionary.ContainsKey(threadId)) { if (value != null) logDataDictionary[threadId] = value; else logDataDictionary.Remove(threadId); } else if(value != null) logDataDictionary.Add(threadId, value); } } private class ActivityLogData { public string methodName; public DateTime startTime; public DateTime endTime; public Stream transportStream; public Stream accessStream; public string inputSoap; public string outputSoap; public bool endedInError; } public override Stream ChainStream(Stream stream) { if (LogData == null) LogData = new ActivityLogData(); var logData = LogData; logData.transportStream = stream; logData.accessStream = new MemoryStream(); return logData.accessStream; } public override void ProcessMessage(SoapMessage message) { if (LogData == null) LogData = new ActivityLogData(); var logData = LogData; if (message is SoapServerMessage) { switch (message.Stage) { case SoapMessageStage.BeforeDeserialize: //Take the data from the transport stream coming in from the client //and copy it into inputSoap log. Then reset the transport to the beginning //copy it to the access stream that the server will use to read the incoming message. logData.startTime = DateTime.Now; logData.inputSoap = GetSoapMessage(logData.transportStream); Copy(logData.transportStream, logData.accessStream); logData.accessStream.Position = 0; break; case SoapMessageStage.AfterDeserialize: //Capture the method name after deserialization and it is now known. (was buried in the incoming soap) logData.methodName = GetMethodName(message); break; case SoapMessageStage.BeforeSerialize: //Do nothing here because we are not modifying the soap break; case SoapMessageStage.AfterSerialize: //Take the serialized soap data captured by the access stream and //write it into the log file. But if an error has occurred write the exception details. logData.endTime = DateTime.Now; logData.accessStream.Position = 0; if (message.Exception != null) { logData.endedInError = true; if (message.Exception.InnerException != null && message.Exception is System.Web.Services.Protocols.SoapException) logData.outputSoap = GetFullExceptionMessage(message.Exception.InnerException); else logData.outputSoap = GetFullExceptionMessage(message.Exception); } else logData.outputSoap = GetSoapMessage(logData.accessStream); //Transfer the soap data as it was created by the service //to the transport stream so it is received the client unmodified. Copy(logData.accessStream, logData.transportStream); LogRequest(logData); break; } } else if (message is SoapClientMessage) { throw new NotSupportedException("This extension must be ran on the server side"); } } private void LogRequest(ActivityLogData logData) { try { //Create the directory if it doesn't exist var directoryName = Path.GetDirectoryName(fileName); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write)) { var sw = new StreamWriter(fs); sw.WriteLine("--------------------------------------------------------------"); sw.WriteLine("- " + logData.methodName + " executed in " + (logData.endTime - logData.startTime).TotalMilliseconds.ToString("#,###,##0") + " ms"); sw.WriteLine("--------------------------------------------------------------"); sw.WriteLine("* Input received at " + logData.startTime.ToString("HH:mm:ss.fff")); sw.WriteLine(); sw.WriteLine("\t" + logData.inputSoap.Replace("\r\n", "\r\n\t")); sw.WriteLine(); if (!logData.endedInError) sw.WriteLine("* Output sent at " + logData.endTime.ToString("HH:mm:ss.fff")); else sw.WriteLine("* Output ended in Error at " + logData.endTime.ToString("HH:mm:ss.fff")); sw.WriteLine(); sw.WriteLine("\t" + logData.outputSoap.Replace("\r\n", "\r\n\t")); sw.WriteLine(); sw.Flush(); sw.Close(); } } finally { LogData = null; } } private void Copy(Stream from, Stream to) { TextReader reader = new StreamReader(from); TextWriter writer = new StreamWriter(to); writer.WriteLine(reader.ReadToEnd()); writer.Flush(); } private string GetMethodName(SoapMessage message) { try { return message.MethodInfo.Name; } catch { return "[Method Name Unavilable]"; } } private string GetSoapMessage(Stream message) { if(message == null || message.CanRead == false) return "[Message Soap was Unreadable]"; var rtn = new StreamReader(message).ReadToEnd(); message.Position = 0; return rtn; } private string GetFullExceptionMessage(System.Exception ex) { Assembly entryAssembly = System.Reflection.Assembly.GetEntryAssembly(); string Rtn = ex.Message.Trim() + "\r\n\r\n" + "Exception Type: " + ex.GetType().ToString().Trim() + "\r\n\r\n" + ex.StackTrace.TrimEnd() + "\r\n\r\n"; if (ex.InnerException != null) Rtn += "Inner Exception\r\n\r\n" + GetFullExceptionMessage(ex.InnerException); return Rtn.Trim(); } } ``` Add this to the web.config of your server. ``` <system.web> <webServices> <soapExtensionTypes> <add type="[Your Namespace].WebServiceActivityLogger, [Assembly Namespace], Version=1.0.0.0, Culture=neutral" priority="1" group="0" /> </soapExtensionTypes> </webServices> </system.web> ```
SOAP Extension Stream Empty After Serialization
[ "", "c#", ".net", "asp.net", "web-services", "soap", "" ]
I'm new to .NET and am having trouble understanding the concept of an Assembly - what is an Assembly? What do people mean when they say 'copy the assembly...'? What is the purpose of AssemblyInfo.cs?
> what is an Assembly? A physical unit of deployment. > What do people mean when they say 'copy the assembly...'? Most assemblies are XCopy deployable - meaning you can just file copy them to their destination. > What is the purpose of AssemblyInfo.cs? It sets Assembly level metadata. Things like version number, copyright notices, COM interop rules, etc.
Its roughly analogous to a [DLL](http://en.wikipedia.org/wiki/Dynamic_link_library) or an [EXE](http://en.wikipedia.org/wiki/Executable). Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. <http://msdn.microsoft.com/en-us/library/hk5f40ct%28VS.71%29.aspx>
What is the concept of an Assembly in .NET?
[ "", "c#", ".net", "" ]
I'm currently using str\_replace to remove a usrID and the 'comma' immediately after it: For example: ``` $usrID = 23; $string = "22,23,24,25"; $receivers = str_replace($usrID.",", '', $string); //Would output: "22,24,25" ``` However, I've noticed that if: ``` $usrID = 25; //or the Last Number in the $string ``` It does not work, because there is not a trailing 'comma' after the '25' Is there a better way I can be removing a specific number from the string? Thanks.
YOu could explode the string into an array : ``` $list = explode(',', $string); var_dump($list); ``` Which will give you : ``` array 0 => string '22' (length=2) 1 => string '23' (length=2) 2 => string '24' (length=2) 3 => string '25' (length=2) ``` Then, do whatever you want on that array ; like remove the entry you don't want anymore : ``` foreach ($list as $key => $value) { if ($value == $usrID) { unset($list[$key]); } } var_dump($list); ``` Which gives you : ``` array 0 => string '22' (length=2) 2 => string '24' (length=2) 3 => string '25' (length=2) ``` And, finally, put the pieces back together : ``` $new_string = implode(',', $list); var_dump($new_string); ``` And you get what you wanted : ``` string '22,24,25' (length=8) ``` Maybe not as "simple" as a regex ; but the day you'll need to do more with your elements (or the day your elements are more complicated than just plain numbers), that'll still work :-) --- EDIT : and if you want to remove "empty" values, like when there are two comma, you just have to modifiy the condition, a bit like this : ``` foreach ($list as $key => $value) { if ($value == $usrID || trim($value)==='') { unset($list[$key]); } } ``` ie, exclude the `$values` that are empty. The "`trim`" is used so `$string = "22,23, ,24,25";` can also be dealt with, btw.
Another issue is if you have a user 5 and try to remove them, you'd turn 15 into 1, 25 into 2, etc. So you'd have to check for a comma on both sides. If you want to have a delimited string like that, I'd put a comma on both ends of both the search and the list, though it'd be inefficient if it gets very long. An example would be: ``` $receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1); ```
PHP str_replace
[ "", "php", "mysql", "substr", "" ]
We have a Netezza table that contains dates stored in a numeric YYYYMMDD format (eg 20090731). What is the best Netezza syntax to use to convert this into date format? eg ``` SELECT somefunction(20090731) as NZDATE ``` ?
Easiest way to convert number to date would be ``` select date(to_char(20090731,'99999999')) as Number_As_DATE; ```
You can use this one as it's the best one. ``` SELECT TO_DATE('20090731','YYYYMMDD') as NZDATE ```
Netezza SQL syntax to convert numeric YYYYMMDD format into date
[ "", "sql", "netezza", "" ]
Can anyone LINQ the following SQL? I've been on this for two hours now and am no closer to getting this than I was when I started. ``` SELECT ArticleId, sum(Amount) AS VoteCount FROM ArticleVotes INNER JOIN Votes ON ArticleVotes.voteId = Votes.id GROUP BY ArticleVotes.articleId ORDER BY VoteCount DESC ``` Tables as follows; ArticleVotes: ArticleId, VoteId Votes: id, amount
``` from articleVote in ArticleVotes join vote in Votes on art.voteId equals vote.id group articleVote by artarticleVote.articleId select new { ArticleId = art.ArticleID, VoteCount = Votes.Sum(vote.amount) } orderby VoteCount ``` I'm not entirely sure about the orderby part, for the matter, I'm not sure about the rest either, as I'm not in the position to test it. If it doesn't work, don't blame me please :) **Update:** Using the OP's work: ``` from artVotes in ArticleVotes join vote in Votes on artVotes.VoteId equals vote.Id group artVotes by artVotes.ArticleId into g let totalAmount = g.Sum(p => p.Vote.Amount) orderby totalAmount descending select new { ArticleId = g.Key, total = totalAmount} ``` --- **Edit** fixed the orderby to use descending ordering. Thanks to the op giving me reason to use the let operator, and finally realizing its beauty. You helped me immensely with your question, just by asking it. +1 for that.
This is what i have now but it's missing the order by the total. ``` from artVotes in ArticleVotes join vote in Votes on artVotes.VoteId equals vote.Id group artVotes by artVotes.ArticleId into g select new { ArticleId = g.Key, total = g.Sum(p => p.Vote.Amount)} ```
LINQ to SQL Join and Sum
[ "", "c#", "linq-to-sql", "" ]
I have been using the PHP mcrypt module for encrypting sensitive data at my company. This has been working well. However, I have been requested to create a new master password which should be able to decrypt any data. The problem is that this master password would have to be hardcoded in a script file. Please correct me if I am wrong but the only secure way seems to be to hardcode a public key in the script and use it to encrypt data while keep the private key secure and use it to decrypt only when needed. mcrypt does not seem to have an implementation for such a scheme. Does anybody know of a library (PHP module or pure PHP) which would do this?
I suggest taking a look at the PHP OpenSSL bindings, and in particular the [openssl\_public\_encrypt()](http://php.net/openssl_public_encrypt) function. You could indeed embed a master public key into the script, and have the script encrypt each user's AES key with this public key. Keep the corresponding master private key in the company safe. Should you need the master decrypt function, you would pull the encrypted user key, decrypt it with the master private key and then decrypt the original data.
There's a PECL extension for that. <https://www.php.net/manual/en/book.gnupg.php> You can also use gnupg command line tool from php, if it doesn't have to be very fast: <http://devzone.zend.com/article/1265> I haven't tried either method.
public key cryptography implementation
[ "", "php", "encryption", "public-key", "mcrypt", "" ]
I need my application to ask the user to browse to a particular file, save that files location and subsequently write a string from a TextBox to it. However, I only need my end-user to browse to the file the **first time** the application launches. Only once. Here lies my dilemma, how can I have my application *remember* if it was the first time it launched?
I think you want a folder, not a file, but that is besides the point. You can use a UserSetting (See Project properties, Settings) and deploy it with an empty or invalid value. Only when you read the invalid value from settings do you start the Dialog. This is on a per-user basis. You can use the Registry in .NET but you really want to stay away from that as much as possible. The fact that the library is not in a System namespace is an indicator.
Save the file chosen in the registry, or in a configuration file in the user's Documents and Settings folder. To get to your local program's path, use: ``` string path = Environment.GetFolderPath(Environment.LocalApplicationData); ```
Saving the filepath of a .txt file
[ "", "c#", "openfiledialog", "" ]
I would like to get ahold of a lightweight, portable fiber lib with MIT license (or looser). Boost.Coroutine does not qualify (not lightweight), neither do Portable Coroutine Library nor Kent C++CSP (both GPL). Edit: could you help me find one? :)
If Boost seems to heavy, helpful people have extracted the relevant parts of Boost (`fcontext`) as a standalone library, e.g. [deboost.context](https://github.com/septag/deboost.context).
1. [Libtask](http://swtch.com/libtask/): MIT License 2. [Libconcurrency](http://code.google.com/p/libconcurrency/): LGPL (a little tighter than MIT, but it's a *functional* library!) Both are written for C.
Lightweight, portable C++ fibers, MIT license
[ "", "c++", "licensing", "portability", "fiber", "" ]
For a networked application, the way we have been transmitting dynamic data is through memcpying a struct into a (void\*). This poses some problems, like when this is done to an std::string. Strings can be dynamic length, so how will the other side know when the string ends? An idea I had was to use something similiar to Java's DataOuputStream, where I could just pass whatever variables to it and it could then be put into a (void\*). If this can't be done, then its cool. I just don't really like memcpying a struct. Something about it doesn't seem quite right. Thanks, Robbie
nothing wrong with memcpy on a struct - as lng as the struct is filled with fixed-size buffers. Put a dynamic variable in there and you have to serialise it differently. If you have a struct with std::strings in there, create a stream operator and use it to format a buffer. You can then memcpy that buffer to the data transport. If you have boost, use [Boost::serialize](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/index.html) which does all this for you (that link also has links to alternative serialization libs) Notes: the usual way to pass a variable-size buffer is to begin by sending the length, then that many bytes of data. Occasionally you see data transferred until a delimiter is received (and fields within that data are delimited themselves by another character, eg a comma).
I see two parts of this question: - serialization of data over a network - how to pass structures into a network stack To serialize data over a network, you'll need a protocol. Doesn't have to be difficult; for ASCII even a cr/lf as packet end may do. If you use a framework (like MFC), it may provide serialization functions for you; in that case you need to worry about how to send this in packets. A packetization which often works well for me is : ``` <length><data_type>[data....][checksum] ``` In this case the checksum is optional, and also zero-data is possible, for instance if the signal is carried in the data\_type (i.e. Ack for acklnowedgement) If you're working on the memcpy with structures, you'll need to consider that memcpy only makes a shallow copy. A pointer is worthless once transmitted over a network; instand you should transmit the data from that pointer (i.e. the contents of your string example)
C++ byte stream
[ "", "c++", "struct", "byte", "memcpy", "" ]
I would like an automated web tests suite based on Selenium RC to take screenshots of pages when some errors are encountered. The test suite is a part of the continuous integration process and technically is executed by CruiseControl running as a **Windows service**. The `selenium.captureScreenshot()` method is called to trigger the actual screenshot. I've registered a JUnit `RunListener` to call it on any test failure. The problem is the screenshots are just **blank files** - PNG files totally black. The dimensions are 1440x900. When manually running the same tests from Eclipse the screenshots are OK (althought they are screenshots of the whole desktop not the browser window, but that's a different story and a minor issue). So I guess the cause of the problem is the Selenium being run as a Windows service. How can I have the screenshots of pages taken when exceptions in Selenium tests happen? The software used: * Windows 2003 Server * Selenium 1.0.1
Looks like there's a completely different answer. The Windows service (managed by [TanukiSoftware Java Service Wrapper](http://wrapper.tanukisoftware.org)) was started with `wrapper.ntservice.interactive` set to `false`. Setting it to `true` has helped. Eventually the screenshots contain real screen content. Consult the [`wrapper.ntservice.interactive`](http://wrapper.tanukisoftware.org/doc/english/prop-ntservice-interactive.html) for details. The analysis of the wrapper code leads to [`SERVICE_INTERACTIVE_PROCESS`](<http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx)> flag being set when starting the Windows service.
What browser are you running these tests in? If it's Firefox I'd recommend the captureEntirePageScreenshot to capture the entire canvas - not just what's in view (rather than the screen) and captureEntirePageScreenshotToString if you're working remotely and want to save the files locally. Not sure if it will help with your issue, but as it uses an add-on to Firefox it might be worth a try.
Selenium run as a Windows service to take screenshots on errors
[ "", "java", "windows", "continuous-integration", "selenium", "" ]
I would like to know what is the best to start with, pyglet or pygame? Which one is faster and which one is more active? I would also like to know if pyglet will get python 3 support, because I have read [here](http://groups.google.com/group/pyglet-users/browse_thread/thread/4afea8197a8fd243) that it might not be possible or it would take a long time. Thanks.
pygame is richly active, witness the Aug release of 1.9 with nokia s60 support, enhanced py2app/py2exe support, and a bevvy of experimental features (support for Python 3.1, webcams, gfx, ...). Books like [Hello World](http://www.manning.com/sande/) and periodic, fun competitions like [ludumdare](http://www.ludumdare.com/) and [pyweek](http://www.pyweek.org) bear witness to the vitality of its community and ecosystem. pyglet has a neat, newer API, and is convenient (pure Python, BSD license instead of LGPL). As for speed, I've run no benchmarks but I gather that out of the box pyglet is better at exploiting advanced HW acceleration for 3D work, while pygame is better at 2D work and on HW that's nowhere as advanced (smart phones, netbooks, etc, don't have shiny 3D HW accelerators). You can enhance both frameworks' speed with add-ons, though that does lose convenience. In terms of Py3 support etc, I believe the issue is simply that pygame, much more mature and popular, has a vastly larger core development group, so of course it can get new things like Py3 support out of the gate earlier. If none of the above issues is decisive for you (you're fine with LGPL vs BSD, don't care much about smartphones, need no books, etc, etc), the only sensible approach is really to download both and try the same elementary tasks of your interest on machines of your interest -- that will tell you how well each "fits your brain", your need for speed, convenience, and so forth.
I cannot comment other answers, so I have to make this new one, sorry. Speed-wise, [Pyglet](http://www.pyglet.org/) is definitely faster than [pygame](http://www.pygame.org/news.html) out-of-the-box, and speed is always a concern when developing with pygame (you have to update the smallest parts of screen, and remembering what has changed can be tedious). There is no such issue with pyglet. If you use [cocos2d](http://cocos2d.org/) (a layer above pyglet) speeding-up things is even easier, just attach sprites to a BatchNode, and watch the FPS rise. As said in a comment pyglet as python3 support. It's just my personal preference, but I like Pyglet much more, and with cocos2d on top, it's really easy to learn. The downside is the much smaller community.
cons/pros of pygame and pyglet
[ "", "python", "pygame", "pyglet", "" ]
The title tells it all, I need to see how others solve this to get a grasp around it. WebForm applications won't help me, as I don't understand WebForms and it would really confuse me (if possible) even more. If such a example or framework would fit together with Entity framework it would rock my world. Edit - Added some info: WinForms I know well, and that's why I'm hoping for an example that I can relate to. I have trouble understanding how to get the different structures from my model to my user. Getting plain data from the model is piece of cake, and passing events from Form back to my 'controller' is also easy, so the model gets it's data. For one model of data I've ended up with 5 different DTO objects as they need different additional data. If this is representing for my solution, I'll end up with about 40 different view interfaces, and then it's becoming difficult to even name them. So by seeing how others have solved my issues I hope to nail out my own solution on the problem, because right now I'm uncertain if I've missed something and is doing it all wrong.
There are some who will disagree that this is multi-tier, but it *will* show you separation of concerns and techniques for decoupling the layers. **koossery.MVCwin: an MVC open source framework for winform .NET applications** <http://koosserymvcwin.codeplex.com/Wiki/View.aspx?title=koossery.MVCwin%20Overview&referringTitle=Home> There is also this article, with examples in Winforms: **The Entity Framework In Layered Architectures** <http://msdn.microsoft.com/en-us/magazine/cc700340.aspx>
A good easy place to start would be writing a WinForms (not WebForms) client that communicates with a .NET web service passing some basic data back and forth. Try figuring out caching strategies both on the client and server. Get familiar with the referencing web services and proxy classes. Think about validation and error handling. Once you are comfortable with how a basic web service works, take it to the next level and read this book [Expert Business Objects by Rockford Lhockta](https://rads.stackoverflow.com/amzn/click/com/1430210192). The book takes you through creating n-tier business objects and all the issues you will face when developing them. He develops an n-tier framework that serves objects to client, web and service applications. Believe me, it's no small feat. Good Luck!
Is there any good examples or frameworks that can teach me n-tier development?
[ "", "c#", ".net", "winforms", "design-patterns", "entity-framework", "" ]
I am building a drag'n'drop gui builder in Javascript. So far so good. As I add items to the GUI and configure them; I have two mechanisms for addressing them: * the 'class' - which I use for doing things to ***all instances*** of an item (eg CSS, generic functionality and so on and so forth) and which I can bind javascript libraries to... and I can make full use of polymorphic class names (ie class="name1 name2 name3 name4" with different things bound to each class name...) * the 'id' - which refers to ***this particular instance*** of a text box or a paragraph and which I can bind javascript libraries to My problem is this: the 'id' must be unique across all html items on the page (by definition) so how do I ensure this? I need to get all the id's of all the items and then maintain some sort of state table. Starting from a blank bit of html this is pretty reasonable - but I need to start from a partly created bit of html with a mixture of existing 'id's - some of which will be in my unique scheme and some of which wont be... The way to do this best ***ought*** to be a solved problem. Suggestions, tips, examples?
**The best way to do this will depend entirely upon the structure and organization of your javascript.** Assuming that you are using objects to represent each of your GUI elements you could use a static counter to increment your ids: ``` // Your element constructor function GuiElement() { this.id = GuiElement.getID(); } GuiElement.counter = 0; GuiElement.getID = function() { return 'element_' + GuiElement.counter++; }; ``` Of course you probably have more than one type of element, so you could either set each of them up so that they have their own counter (e.g. form\_1, form\_2, label\_1, label\_2) or so that they all share a counter (e.g. element\_1, element\_2, element\_3), but either way you will probably want them to inherit from some base object: ``` // Your base element constructor function GuiElement(tagName, className) { this.tagName = tagName; this.className = className; } GuiElement.counter = 0; GuiElement.getID = function() { return 'element_' + GuiElement.counter++; }; GuiElement.prototype.init = function() { this.node = document.createElement(this.tagName); this.node.id = this.id = GuiElement.getID(); this.node.className = this.className; } // An element constructor function Form() { this.init(); } Form.prototype = new GuiElement('form', 'form gui-element'); // Another element constructor function Paragraph() { this.init(); } Paragraph.prototype = new GuiElement('p', 'paragraph gui-element'); ``` You could also go this route if you would rather keep some variables "private": ``` // Your element constructor constructor var GuiElement = (function() { var counter = 0; function getID() { return 'element_' + counter++; } return function GuiElement(tagName, className) { return function() { this.node = document.createElement(tagName); this.node.id = this.id = getID(); this.node.className = className + ' gui-element'; this.className = className; }; } })(); // Create your element constructors var Form = GuiElement('form', 'form'), Paragraph = GuiElement('p', 'paragraph'); // Instantiate elements var f1 = new Form(), f2 = new Form(), p1 = new Paragraph(); ``` **Update:** If you need to verify that an id is not already in use then you could add the check you and of the getID methods: ``` var counter = 0; function getID() { var id = 'element_' + counter++; while(document.getElementById(id)) id = 'element_' + counter++; return id; } ```
``` function uniqueId() { return 'id_' + new Date().getTime(); } ```
Unique html item ID in Javascript
[ "", "javascript", "html", "uniqueidentifier", "" ]
I have current have two UI components used to specify a date and a time. Both components return `java.util.Date` instances representing the calendar date and time respectively. My question is: What is the best way to combine these values to create a `java.util.Date` instance representing the date and time? **I would like to avoid dependencies on Joda or other 3rd party libraries.** My current solution looks like this (but is there a better way?): ``` Date date = ... // Calendar date Date time = ... // Time Calendar calendarA = Calendar.getInstance(); calendarA.setTime(date); Calendar calendarB = Calendar.getInstance(); calendarB.setTime(time); calendarA.set(Calendar.HOUR_OF_DAY, calendarB.get(Calendar.HOUR_OF_DAY)); calendarA.set(Calendar.MINUTE, calendarB.get(Calendar.MINUTE)); calendarA.set(Calendar.SECOND, calendarB.get(Calendar.SECOND)); calendarA.set(Calendar.MILLISECOND, calendarB.get(Calendar.MILLISECOND)); Date result = calendarA.getTime(); ```
``` public Date dateTime(Date date, Date time) { return new Date( date.getYear(), date.getMonth(), date.getDay(), time.getHours(), time.getMinutes(), time.getSeconds() ); } ``` you can corvert this deprecated code to Calendar obtaining your solution. Then my answer is: *no, you cannot do better without using joda* **NB** jodatime soon will be standardized with [JSR 310](http://jcp.org/en/jsr/detail?id=310)
I think you're approach is the best you're likely to get without using Joda time. A solution using SimpleDateFormats might use fewer lines, but is not really giving you any benefit.
Combining java.util.Dates to create a date-time
[ "", "java", "datetime", "" ]
I'm trying to find an appropriate way to read the contents of an Excel file on an NT server operating system. I have numerous problems using the Excel API and then came across the official [Microsoft on Office Automation](http://support.microsoft.com/default.aspx/kb/257757) which states that the Excel API is not suitable for Excel automation. The sorts issues that I saw were similar to those described in the article. Is there another way that I can read an Excel file (xls, xlsx, xlsm) on a server (no UI) in such a way that doesn't suffer the same sort of threading/security/license issues imposed within the Excel API?
There were a number of libraries that were highlighted by different users that would allow the sort of functionality required. I've listed them here and some of these were evaluated so where appropriate I've tried to put down interesting comments for comparing them. The details I've included are completely opinion based, however any of these libraries would probably achieve the required goal. [SpreadsheetGear.Net](http://www.spreadsheetgear.com/) (Didn't evaluate due to high purchase cost) [Aspose.Cells](http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx) (Evaluated by a collegue. Appeared to be fairly simple to implement, performance comparable to Excel Interop). [GemBox](http://www.gemboxsoftware.com/GBSpreadsheet.htm) (Didn't evaluate) [Excel Services](http://blogs.msdn.com/excel/archive/2005/11/08/490502.aspx) (Seems only to be included in SharePoint 2007) [Excel Mapper](http://shashankshetty.wordpress.com/2009/05/09/using-excelmapper/) (Didn't evaluate because it requires strongly typed objects to import into which didn't fit my requirement). [SmartXls](http://www.smartxls.com/) (Didn't evaluate because it requires strongly typed objects to import into which didn't fit my requirement). [ActiveXls](http://www.activexls.com/products/dotnet_reader.aspx) (Fairly easy to use, lack of Properties raises questions, they have a preference of Methods for trivial actions. Despite it's claim of 1M records a second was out performed by cheaper FlexCel. Have decided that the help/API manual is almost useless.) [Koogra](http://koogra.sourceforge.net/) (Didn't evaluate due to finding no documentations/information) [FileHelpers](http://filehelpers.sourceforge.net/example_exceldatalink.html) (Didn't evaluate) [**Flexcel**](http://www.tmssoftware.com/site/flexcelnet.asp) **(Lowest cost solution found, good performance and was simple to implement with a close proximity to Excel Interop structure. Also received quick response to technical question from support. Probably my pick of the bunch.)** [SyncFusion BackOffice](http://www.syncfusion.com/products/back-office/xlsio) (Medium cost and had a reasonable structure. Unfortunately had more difficulty implementing and inconsistent results when running unit tests. Also received a number of 'Attempted to read protected memory' errors, which didn't encourage me with purely managed library.)
I have used ADO.NET get data out of an xls before. I'm not sure all the Excel Doc types this would support but check out [Reading and Writing Excel Spreadsheets Using ADO.NET C# DbProviderFactory](http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx) [Here is some code](https://stackoverflow.com/questions/280058) from a SO question as well. I was able to read and write to excel without having to install Office or any 3rd party tools.
Reading Excel Files as a Server Process
[ "", "c#", "excel", "windows-services", "" ]