Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example): ``` void someMethod(SomeClass x) { if...
I prefer the `ArgumentNullException` over the `NullReferenceException` that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object. If the method is a constructor, then it would depend on a couple of different fact...
I always follow the practice of **fail fast**. If your method is dependent on X and you understand X might be passed in null, null check it and raise the exception immediately instead of prolonging the point of failure. **2016 update:** Real world example. I strongly recommend the usage of [JetBrains Annotations](htt...
Throwing ArgumentNullException
[ "", "c#", ".net", "exception", ".net-6.0", "" ]
I'm currently using msbuild for a solution of over 600 projects. Imagine I change the code for 1 library that is used by 10 projects. Instead of providing all 600 projects to msbuild and let it compile all of them and figure out the dependencys. I was wondering if there was a program or library I could use that would ...
Have you tried [.NET assembly dependency analyser](http://www.drewnoakes.com/code/dependancyanalyser/)?. It is open source, and the graph output in [dot script](http://www.graphviz.org/doc/info/lang.html) might be what you need. An example from the site: ``` digraph G { size="100,69" center="" rati...
I have some code that does exactly this; I use it in our bespoke build process to a: figure out the build order (without having to maintain it), and b: cascade changes upwards through a tree of random projects. Unfortunately I'm not in my usual office at the moment, and the code is too complex to reproduce "off the cuf...
Build dependency tree from csproj files
[ "", "c#", "optimization", "msbuild", "" ]
In through `php_info()` where the WSDL cache is held (`/tmp`), but I don't necessarily know if it is safe to delete all files starting with WSDL. Yes, I *should* be able to just delete everything from `/tmp`, but I don't know what else this could effect if I delete any all WSDL files.
You can safely delete the WSDL cache files. If you wish to prevent future caching, use: ``` ini_set("soap.wsdl_cache_enabled", 0); ``` or dynamically: ``` $client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) ); ```
Remove all `wsdl*` files in your `/tmp` folder on the server. WSDL files are cached in your default location for all cache files defined in php.ini. Same location as your session files.
In PHP how can you clear a WSDL cache?
[ "", "php", "soap", "caching", "wsdl", "" ]
basically, I've got my Huffman table as ``` std::map<std::string, char> ciMap; ``` Where string is the bit pattern and char is the value represented by said pattern. The problem is how do I store that as a header of my compressed file so I can build again the same map when I want to decode it? Trying to store it as ...
You can do it yourself, or you can do it with boost: <http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/index.html>. What you currently try is just view the map as a plain old datatype, which essentially means it's a C datatype. But it isn't, so it fails to save/load. boost serialization does it correctly. Ha...
You can't just serialize the binary values to disk in this way. The in memory representation is not simply a contiguous block of memory, and even if it was it will likely contain pointers which are relative to the address of the block. You need to iterate over the map and serialize out each item individually. Then to ...
C++ Huffman Code Header
[ "", "c++", "tree", "header", "binaryfiles", "" ]
What are the best practices for naming ant targets? For example, what would you expect the target "test" to run? All unit tests? All functional tests? Both? What are the standard names used for running different types of tests (unit/functional/all)? Are there standards for target names to deploy software in J2SE? in ...
See the [**"Naming Conventions"** section](http://wiki.apache.org/ant/TheElementsOfAntStyle#Naming_conventions) on this page : [The Elements of Ant Style](http://wiki.apache.org/ant/TheElementsOfAntStyle) > The following targets are common to many builds. Always avoid changing > the behavior of a well-known target nam...
For my java projects I use the names defined in the [maven default lifecycle](http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference) as basis. For other projects I also have used the [GNU autoconf standard targets](http://www.gnu.org/software/autoconf/manual/make/Standard-Ta...
What are the best practices for naming ant targets?
[ "", "java", "ant", "naming-conventions", "" ]
I have a requirement to send some 100 bytes data over internet .My machine is connected to internet. I can do this with HTTP by sending requests and receiving responses. But my requirement is just to send data not receive response. I am thinking of doing this using UDP Client server program. But to do that I need to ho...
Cheap answer to send 100 bytes of data on the internet. ``` C:\Windows\system32>ping -n 1 -l 100 -4 google.com Pinging google.com [209.85.171.99] with 100 bytes of data: Reply from 209.85.171.99: bytes=56 (sent 100) time=174ms TTL=233 Ping statistics for 209.85.171.99: Packets: Sent = 1, Received = 1, Lost = 0 (...
Anything that happens on the internet requires a client and a server. One box is in the role of client, the other is in the role of server for your specific transaction. Usually (but not always) your local box is a client and some other box is the server. Software MUST be running on both to implement some protocol f...
Send data over Internet
[ "", "c++", "networking", "" ]
I'm writing an application where the user will create an appointment, and instantly get an email confirming their appointment. I'd also like to send an email the day of their appointment, to remind them to actually show up. I'm in ASP.NET (2.0) on MS SQL . The immediate email is no problem, but I'm not sure about the ...
Choice #1 would be the best option, create a table of emails to send, and update the table as you send each email. It's also best not to delete the entry but mark it as sent, you never know when you'll have a problem oneday and want to resend out emails, I've seen this happen many times in similar setups.
One caution - tightly coupling the transmission of the initial email in the web application can result in a brittle architecture (e.g. SMTP server not available) - and lost messages. You can introduce an abstraction layer via an MSMQ for both the initial and the reminder email - and have a service sweeping the queue o...
sending an email, but not now
[ "", "asp.net", "sql", "smtp", "" ]
Here's an interesting question. I have a system that attempts to run some initialization code. If it fails, we call the deinitializer to clean everything up. Because we call the deinitializer in exception handling, we run the risk that both initialize and deinitialize will fail, and hypothetically, it now seems that w...
If your clean up code is failing and you cannot leave the application in a clean and known state I would let the exception go unhandled (or catch it with the UnhandledException event to log it) then close the application. Because if you can't handle the first exception, what point is there in catching the second excep...
You shouldn't throw in the Finally block. Instead, use the InnerException to add information in the throw. ## Update What you have to do is to catch and rethrow with the "history" of exception, this is done with InnerException. You can edit it when bulding a new exception. This is a code snippet I just wrote to illus...
The mystery of the twin exceptions
[ "", "c#", ".net", "" ]
I have a simple php script on a server that's using fsockopen to connect to a server. ``` <?php $fp = fsockopen("smtp.gmail.com", 25, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { echo fgets($fp, 1024); fclose($fp); } ?> ``` The problem is the the script times out and fails t...
Interesting... Some firewalls can block specific program's connections to specific ports. Please check it again, try to stop firewall completely. Also try to stop any anti-spyware.
Like *maxnk* mentioned firewalling is the most likely issue, either on the server, or by your ISP. Port 25 is frequently firewalled as a method to prevent spam. Just as a quick test, since you mentioned gmail, you might want to try connecting to port 587 instead. Gmail listens for smpt on this alternate port in additi...
php fsockopen
[ "", "php", "sockets", "" ]
In `C#/VB.NET/.NET,` which loop runs faster, `for` or `foreach`? Ever since I read that a `for` loop works faster than a `foreach` loop a [long time ago](https://learn.microsoft.com/previous-versions/dotnet/articles/ms973839(v=msdn.10)) I assumed it stood true for all collections, `generic collections`, all `arrays`, ...
Patrick Smacchia [blogged about this](http://codebetter.com/blogs/patricksmacchia/archive/2008/11/19/an-easy-and-efficient-way-to-improve-net-code-performances.aspx) last month, with the following conclusions: > * for loops on List are a bit more than 2 times cheaper than foreach > loops on List. > * Looping on arra...
First, a counter-claim to [Dmitry's (now deleted) answer](https://stackoverflow.com/a/472200). For arrays, the C# compiler emits largely the same code for `foreach` as it would for an equivalent `for` loop. That explains why for this benchmark, the results are basically the same: ``` using System; using System.Diagnos...
In .NET, which loop runs faster, 'for' or 'foreach'?
[ "", "c#", ".net", "performance", "for-loop", "" ]
I have a generic list of objects in C#, for example sake, here's what the object might be. ``` public class Thing { public string Name { get; set; } public DateTime EditDate { get; set; } } var things = new List<Thing>(); ``` Now I want to call: ``` thing.Sort((t1, t2) => t1.EditDate.CompareTo(t2.EditDate))...
You can create a somewhat more complex lambda, such as: ``` things.Sort((t1, t2) => { if (t1 == null) { return (t2 == null) ? 0 : -1; } if (t2 == null) { return 1; } return t1.EditDate.CompareTo(t2.EditDate); }); ``` `EndDate` cannot be `null` as it is a value type. However, if you had a specific value ...
Have Thing implement IComparable such that Things with null editDates have a higher order than those with an edit date. Then modify the sort expression to sort on the objects and not the edit dates.
How do you sort a generic list in C# and allow NULL items to appear first in the list?
[ "", "c#", "generics", "comparison", "" ]
I am Need of Formula to Accurately Calculate Bandwith for 1 Gig Nic Card. What i am doing is send Layer 2 Packets @ 1Gbps but my software is showing 6oo Mbps. The whole experiment is Back to Back. No switch No Router. Here is what i did. ``` // LinkSpeed = 1Gb UINT nBandwidth = LinkSpeed/100;//Mbps nBandwidth =...
In ethernet, you also have to take into account the [interframe gap](http://en.wikipedia.org/wiki/Interframe_gap), which is at minimum, 96 quantum time, that is, the quantum time being the time to send a bit, which is, 1ns in GigaEthernet (1 second / 1,000,000,000). Also, if you get a collision, there will be [backoff...
Just because your card is a 1 Gigabit card that doesn't mean you will get that entire speed. On top of what Mat said you have to worry about signal attenuation and interfearence. If the router or switch gets congested this will also slow down your transfer speed. No formula can give you a completely accurate number for...
Need of Formula for Accurate Bandwith for 1 Gigabit NIC Card
[ "", "c++", "networking", "network-programming", "" ]
Which libraries for Java are there that have a fast implementation for floating point or fixed point operations with a precision of several thousands of digits? How performant are they? A requirement for me is that it implements a multiplication algorithm that is better than the naive multiplication algorithm that tak...
There are three libraries mentioned on the [Arbitrary Precision Arithmetic](http://en.wikipedia.org/wiki/Bignum) page: java.math (containing the mentioned BigDecimal), [Apfloat](http://www.apfloat.org/) and [JScience](http://jscience.org/). I run a little speed check on them which just uses addition and multiplication....
Have you checked the performance of [BigDecimal](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html)? I can't see anything obvious in the JavaDoc, but it would certainly be my first port of call.
Java floating point high precision library
[ "", "java", "floating-point", "" ]
What is a good C/C++ CSS parser? All that I can find is [CSSTidy](http://csstidy.sourceforge.net/), and it seems to be more of an application than a parsing library.
libcss seems also a common google hit and it looks good <http://www.netsurf-browser.org/projects/libcss/>
I googled for: ``` "CSS Parser" C++ ``` The first result is <http://sourceforge.net/projects/htmlcxx>. It's a CSS/HTML API for C++.
What is a good C/C++ CSS parser?
[ "", "c++", "c", "css", "parsing", "" ]
Is there any way to create an array-like object in JavaScript, without using the built-in array? I'm specifically concerned with behavior like this: ``` var sup = new Array(5); //sup.length here is 0 sup[0] = 'z3ero'; //sup.length here is 1 sup[1] = 'o3ne'; //sup.length here is 2 sup[4] = 'f3our'; //sup.length...
Now we have ECMAScript 2015 (ECMA-262 6th Edition; ES6), we have [proxy objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), and they allow us to implement the `Array` behaviour in the language itself, something along the lines of: ``` function FakeArray() { const target ...
[] operator is the native way to access to object properties. It is not available in the language to override in order to change its behaviour. If what you want is return computed values on the [] operator, you cannot do that in JavaScript since the language does not support the concept of computed property. The only ...
Implement Array-like behavior in JavaScript without using Array
[ "", "javascript", "arrays", "overloading", "" ]
I need to convert a list (or a dict) into a comma-separated list for passing to another language. Is there a nicer way of doing this than: ``` result = '' args = ['a', 'b', 'c', 'd'] i = 0 for arg in args: if i != 0: result += arg else: result += arg + ', ' i += 1 result = 'function (...
``` 'function(%s)' % ', '.join(args) ``` produces ``` 'function(a, b, c, d)' ```
`', '.join(args)` will do the trick.
Formatting a data structure into a comma-separated list of arguments
[ "", "python", "refactoring", "list", "" ]
I wonder if there is a less verbose way to do Input Verification in my methods. For example, i commonly write stuff like this: ``` public string SomeFunction(string param1, int param2) { if(string.IsNullOrEmpty(param1)){ throw new ArgumentException("bla", "param1"); } if(param2 < 0 || param2 > 100 ...
Three words: [design by contract](http://en.wikipedia.org/wiki/Design_by_contract) One implementation for C# can be found here: <http://www.codeproject.com/KB/cs/designbycontract.aspx>
Well, you could do something with AOP, look at [PostSharp](http://www.postsharp.org). This could be used to just inject the necessary code, but it adds some overhead, both to the compilation step and to the compiled code. Code Contracts are also slated to be included in .NET 4.0, read more about this [here](http://ms...
Enforcing Input Parameters to a Method without a bunch of if's at the beginning of the method?
[ "", "c#", ".net", "" ]
In my C++ application (developed with Visual Studio 2003) and [Qt4](http://en.wikipedia.org/wiki/Qt_(toolkit)#Current), I'd like to print the stack trace from a specific line of code, either to the console output or into a file. What would it take ? Is Qt of any help to do this ?
[StackWalker](http://www.codeproject.com/KB/threads/StackWalker.aspx) by Jochen Kalmbach [MVP VC++] and available on codeproject is probably the easiest way to do this. It wraps up all of the details of dealing with the underlying StackWalk64 API.
It's not in the public Qt API, but if you look in > $QTDIR/src/corelib/kernel/qcrashhandler.\* you can see the beginnings of a cross-platform implementation of exactly this.
Printing the stack trace in C++ (MSVC)?
[ "", "c++", "qt", "visual-c++", "" ]
My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use. Our security requirements are pretty basic; a user just needs to be able ...
The problem is that Spring Security does not make the Authentication object available as a bean in the container, so there is no way to easily inject or autowire it out of the box. Before we started to use Spring Security, we would create a session-scoped bean in the container to store the Principal, inject this into ...
Just do it the usual way and then insert it using `SecurityContextHolder.setContext()` in your test class, for example: Controller: ``` Authentication a = SecurityContextHolder.getContext().getAuthentication(); ``` Test: ``` Authentication authentication = Mockito.mock(Authentication.class); // Mockito.whens() for ...
Unit testing with Spring Security
[ "", "java", "security", "unit-testing", "spring", "spring-security", "" ]
I've written a simple control which basically displays a few words with an image next to it. I want the containing items to strech when the parent form is resized and as you can see from my commented out code, I don't want to use a loop as it flickers. Any idea on how to get the items to grow and shrink with the form...
Avoid triggering a redraw every time you resize a child control by embedding your `foreach` in `SuspendLayout()` and `ResumeLayout()`: ``` this.SuspendLayout(); foreach (FlowLayoutPanel item in _listItems) { item.Width = this.Width - 10; } this.ResumeLayout(); ```
Anchor right and bottom on the form and maybe dock them.
I need help with scrolling on my control - c#
[ "", "c#", "winforms", "controls", "" ]
I'm trying to find the actual class of a django-model object, when using model-inheritance. Some code to describe the problem: ``` class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass ``` If I create various objects of the two Child classes and...
Django implements model inheritance with a OneToOneField between the parent model's table and the child model's table. When you do `Base.object.all()`, Django is querying just the Base table, and so has no way of knowing what the child table is. Therefore, unfortunately, it's not possible to go directly to the child mo...
Have a look at InheritanceManager in [django-model-utils](https://github.com/carljm/django-model-utils/) – attaching it to a model gives you the concrete child classes (at least at the first level): ``` from model_utils.managers import InheritanceManager class Base(models.Model): objects = InheritanceManager() #...
How do I find the "concrete class" of a django model baseclass
[ "", "python", "django", "inheritance", "django-models", "" ]
What is the best way to password protect folder using php without a database or user name but using. Basically I have a page that will list contacts for organization and need to password protect that folder without having account for every user . Just one password that gets changes every so often and distributed to the...
**Edit: SHA1 is no longer considered secure. Stored password hashes should also be [salted](https://en.wikipedia.org/wiki/Salt_(cryptography)). There are now much better solutions to this problem.** --- You could use something like this: ``` //access.php <?php //put sha1() encrypted password here - example is 'hell...
Assuming you're on Apache: <http://httpd.apache.org/docs/1.3/howto/htaccess.html#auth>
What is the best way to password protect folder/page using php without a db or username
[ "", "php", "passwords", "password-protection", "" ]
Javascript I have code that will hide various sections in a MS CRM form based on the value of a Picklist. The code executes in the onChange event of the Picklist. It hides the section by referencing a field in the section and then navigating up the DOM using the ParentElement syntax, as such: crmForm.all.fieldName.pa...
Take a look at the following post. it uses section position instead of parentElement. <http://mscrm4ever.blogspot.com/2008/08/show-hide-crm-form-section.html>
Sorry, buy can you clean up the question? You say it works with 1 exception when the section has a read-only field. Is that the field you are trying to work with in your example? Or can you work with any field in the section, but if there is one read only in the section it fails? What is the exception (doesn't work, ja...
Hide a section in MS CRM form which contains read only field
[ "", "javascript", "dynamics-crm", "dynamics-crm-4", "" ]
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods. I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine **Update: the caller I have i...
Ok. Here's another try now that I know the client is not Java. Since you want out-of-process access and possibly remote machine access, I don't think JNI is what you want since that's strictly in-process (and a total hassle). Here are some other options: **Raw Sockets** : just set up a listener socket in Java and acce...
Will you be calling from another JVM-based system, or is the client language arbitrary? If you're calling from another JVM, one of the simplest approaches is to expose your object as an MBean through JMX. The canonical Hello World MBean is shown [here](http://java.sun.com/developer/technicalArticles/J2SE/jmx.html). The...
How can I call a method in an object from outside the JVM?
[ "", "java", "jvm", "communication", "" ]
Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing. ``` >>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore') Traceback (most recent call last): File "<interactive input>", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal ...
… There's a reason they're called "encodings" … A little preamble: think of unicode as the norm, or the ideal state. Unicode is just a table of characters. №65 is latin capital A. №937 is greek capital omega. Just that. In order for a computer to store and-or manipulate Unicode, it has to *encode* it into bytes. The ...
encode is available to unicode strings, but the string you have there does not seems unicode (try with u'add \x93Monitoring\x93 to list ') ``` >>> u'add \x93Monitoring\x93 to list '.encode('latin-1','ignore') 'add \x93Monitoring\x93 to list ' ```
Python UnicodeDecodeError - Am I misunderstanding encode?
[ "", "python", "unicode", "ascii", "encode", "" ]
Back in the scripted ASP and ColdFusion days, I used to work on projects that would build code generators for ASP or Coldfusion, typically in C++, in order to be more object oriented in application design and not have developers writing scripted code, which often was called "spaghetti code" for it's size and complexity...
I'm rather sceptical on the merits of code generation in the context of a dynamic language, such as PHP. You can generally use other kinds of abstraction to get the same results. Unlike a statically typed, compiled language, it is rather easy to use dynamic hooks such as \_\_get and \_\_set and reflection, to make gene...
Why not just build a proper app in PHP instead of going through the hassle? Recent PHP is [fully object-oriented](https://www.php.net/manual/en/language.types.object.php) and lets you do some pretty decent stuff. There are even [frameworks](https://stackoverflow.com/questions/20709/which-php-framework-will-get-me-to-a-...
Does a PHP Generator Framework or reference exist?
[ "", "php", "scripting", "code-generation", "" ]
I'm trying to insert a column into an existing DataSet using C#. As an example I have a DataSet defined as follows: ``` DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("column_1", typeof(string)); ds.Tables[0].Columns.Add("column_2", typeof(int)); ds.Tables[0].Columns.Add("column_...
You can use the [DataColumn.SetOrdinal()](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.setordinal.aspx) method for this purpose. ``` DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("column_1", typeof(string)); ds.Tables[0].Columns.Add("column_2", typeof(int)); ds....
I used your suggestion to create an extention method for the DataSet's DataColumnCollection: ``` public static void InsertAfter(this DataColumnCollection columns, DataColumn currentColumn, DataColumn newColumn) { if (!columns.Contains(currentColumn.ColumnName)) throw new Argum...
How does one insert a column into a dataset between two existing columns?
[ "", "c#", "insert", "dataset", "" ]
## **Accuracy Vs. Precision** What I would like to know is whether I should use **System.currentTimeMillis()** or **System.nanoTime()** when updating my object's positions in my game? Their change in movement is directly proportional to the elapsed time since the last call and I want to be as precise as possible. I'v...
If you're just looking for extremely precise measurements of **elapsed time**, use `System.nanoTime()`. `System.currentTimeMillis()` will give you the most accurate possible elapsed time in milliseconds since the epoch, but `System.nanoTime()` gives you a nanosecond-precise time, relative to some arbitrary point. From...
Since no one else has mentioned this… It is not safe to compare the results of `System.nanoTime()` calls between different JVMs, each JVM may have an independent 'origin' time. `System.currentTimeMillis()` will return the (approximate) same value between JVMs, because it is tied to the system wall clock time. If you...
System.currentTimeMillis vs System.nanoTime
[ "", "java", "timer", "time-precision", "" ]
I ran across this and was wondering if someone could explain why this works in VB.NET when I would expect it should fail, just like it does in C# ``` //The C# Version struct Person { public string name; } ... Person someone = null; //Nope! Can't do that!! Person? someoneElse = null; //No problem, just like expect...
If I remember correctly, 'Nothing' in VB means "the default value". For a value type, that's the default value, for a reference type, that would be null. Thus, assigning nothing to a struct, is no problem at all.
`Nothing` is roughly equivalent to `default(T)` for the relevant type. (Just checked, and this is true for strings as well - i.e. `Nothing` is a null reference in the context of strings.)
C# vs VB.NET - Handling of null Structures
[ "", "c#", "vb.net", "" ]
According to HTML specs, the `select` tag in HTML doesn't have a `readonly` attribute, only a `disabled` attribute. So if you want to keep the user from changing the dropdown, you have to use `disabled`. The only problem is that disabled HTML form inputs don't get included in the POST / GET data. What's the best way ...
You should keep the `select` element `disabled` but also add another hidden `input` with the same name and value. If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input. Here is a demo: ``` $('#mainform').submit(function() { $('#f...
We could also disable all except the selected option. This way the dropdown still works (and submits its value) but the user can not select another value. [Demo](http://jsfiddle.net/ret7mhfa/) ``` <select> <option disabled>1</option> <option selected>2</option> <option disabled>3</option> </select> ```
HTML form readonly SELECT tag/input
[ "", "javascript", "html", "" ]
I'm looking for books / articles / papers on Javascript engine internals along the lines of the many reference works about the JVM internals, CLR internals, etc. I could (and likely will) look at the source code for JavaScriptCore and V8/Chromium, but if there's a book out there or some other "guided tour" documentatio...
One of the in-depth documents could be the [ECMA-262 Language Specifications](http://www.ecma-international.org/publications/standards/Ecma-262.htm). A good book on the language's idioms and best practices is [JavaScript The Good Parts](http://oreilly.com/catalog/9780596517748/)
I was curious about this too, and here's what I found: About Chrome's Javascript engine (v8): * [Garbage Collection in V8; For mobile and beyond](http://ajaxian.com/archives/garbage-collection-in-v8-for-mobile-and-beyond) * [V8 Internals: Building a High Performance JavaScript Engine](http://www.scribd.com/doc/169210...
Where can I find information about Javascript engine internals?
[ "", "javascript", "documentation", "internals", "" ]
i would to know how to write a profiler? What books and / or articles recommended? Can anyone help me please? Someone has already done something like this?
I would look at those open-source projects first: * Eclipse TPTP (<http://www.eclipse.org/tptp/>) * VisualVM (<https://visualvm.dev.java.net/>) Then I would look at JVMTI (not JVMPI) * <http://java.sun.com/developer/technicalArticles/Programming/jvmti/>
Encouraging lot, aren't we :) Profilers aren't too hard if you're just trying to get a reasonable idea of where the program's spending most of its time. If you're bothered about high accuracy and minimum disruption, things get difficult. So if you just want the answers a profiler would give you, go for one someone el...
How to write a profiler?
[ "", "java", "profiler", "" ]
I have a PHP script (running on a Linux server) that ouputs the names of some files on the server. It outputs these file names in a simple text-only format. This output is read from a VB.NET program by using HttpWebRequest, HttpWebResponse, and a StreamReader. The problem is that some of the file names being output c...
**Figured it out!!** Like so many things, it's simple in retrospect! Jon Skeet was correct - it was *meant* to be UTF-8, but definitely wasn't. Turns out, in the original script I was using (before I stripped it down to make it simpler to debug), there was some additional text output by the script which was not wrap...
Does PHP give you control over the encoding at all? It's generally not a good idea to just guess at it. When you say you've written out the symbol from .NET, what encoding were you using? What actual Unicode code point is it? There's a section symbol at [unicode U+00A7](http://www.unicode.org/charts/PDF/U0080.pdf) - i...
Character encoding problem - PHP output, read by .NET, via HttpWebRequest
[ "", ".net", "php", "vb.net", "encoding", "character-encoding", "" ]
When I try to build my project I get the following message in the build window : **========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========** I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info ...
Check with the configuration manager like CMS said and make sure that you have the right platform set. A lot of the time when you use something like the MS Application Blocks the default platform is set to Itanium.
Check on your solution properties, then go to "Configuration Properties", and make sure that all the projects that you want to build, have the build flag checked:
Visual Studio skips build
[ "", "c++", "windows", "visual-studio-2005", "build", "" ]
Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithm...
One of the fastest ways to make many with replacement samples from an unchanging list is the alias method. The core intuition is that we can create a set of equal-sized bins for the weighted list that can be indexed very efficiently through bit operations, to avoid a binary search. It will turn out that, done correctly...
A simple approach that hasn't been mentioned here is one proposed in [Efraimidis and Spirakis](http://www.sciencedirect.com/science/article/pii/S002001900500298X). In python you could select m items from n >= m weighted items with strictly positive weights stored in weights, returning the selected indices, with: ``` i...
Weighted random selection with and without replacement
[ "", "python", "algorithm", "random", "" ]
I know I can update a single record like this - but then how to I get access to the id of the record that was updated? (I'm using MSSQL so I can't use Oracles RowId) ``` update myTable set myCol = 'foo' where itemId in (select top 1 itemId from myTable ) ``` If I was peforming an Insert I could use getGeneratedKeys t...
This example works really well in MSSQL 2005... ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO DROP TABLE [dbo].[TEST_TABLE] GO CREATE TABLE [dbo].[TEST_TABLE]( [id] [int] IDENTITY(1,1) NOT NULL, [name] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_TEST_TABLE] PRIMARY K...
I would do the following: ``` Begin Tran update myTable set myCol = 'foo' where itemId in (select top 1 itemId from myTable ) select top 1 itemId from myTable Commit Tran ```
Whats the best way to update a single record via SQL and obtain the id of the record that was updated? (Java/MSSQL)
[ "", "java", "sql-server", "" ]
i wonder if there is a way to generate valid GUIDs/UUIDs where the first (or any part) part is a user-selected prefix. I.e., the GUID has the format AAAAAAAA-BBBB-CCCC-DDDD-DDDDDDDDDDDD, and I want to set any part to a pre-defined value (ideally the AAA's). The goal is to have GUIDs still globally unique, but they do ...
Sorry, you want too much from a GUID. Summarizing from both your question and your own answer/update, you want it to * 1 be a GUID * 2 not collide with any other GUID (be globally unique) * 3 Ignore the standard on the interpretation of the first bits, using a reserved value * 4 Use a personal scheme for the remaining...
Hmmm...so, you'd basically like a 12 byte GUID? Since, once you remove the uniqueness of the first 4 bytes (your AAA's), you've [broken the existing algorithm](http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx) - you'll need to come up with your own algorithm. According to the relevant [RFC](http://www...
Creating GUIDs with a set Prefix
[ "", "c#", "guid", "" ]
Sometimes software installers force you to scroll to the end of the EULA before the “I agree” box is enabled. How can I produce the same effect on a web page?
``` <html> <head> <script type="text/javascript"> function setupPage() { var agreement = document.getElementById("agreetext"); var visibleHeight = agreement.clientHeight; var scrollableHeight = agreement.scrollHeight; if (scrollable...
Excellent bit of code, if you also want to change the color in the label next to the checkbox, just modify the code as follows: ``` function setupPage() { var agreement = document.getElementById("agreetext"); var visibleHeight = agreement.clientHeight; var scrollableHeight = agreement.scrollHeight; if ...
Javascript on scroll to end
[ "", "javascript", "" ]
Looking at the [mozilla documentation](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array), looking at the regular expression example (headed "Creating an array using the result of a match"), we have statements like: > input: A read-only property that reflects the original string again...
**Edit:** Since this answer was written, a new, better way using `Object.defineProperty` has been standardized in EcmaScript 5, with support in newer browsers. See [Aidamina's answer](https://stackoverflow.com/questions/366047/can-read-only-properties-be-implemented-in-pure-javascript/2964881#2964881). If you need to s...
With [any JavaScript interpreter that implements ECMAScript 5](https://compat-table.github.io/compat-table/es5/#Object.defineProperty "show browser support") you can use Object.defineProperty to define readonly properties. In loose mode the interpreter will ignore a write on the property, in strict mode it will throw a...
Can Read-Only Properties be Implemented in Pure JavaScript?
[ "", "javascript", "browser", "" ]
Is there anyone already implement memcached for production use in Windows environment? Because many blogs that I've read, it's not recommended to run memcached in Windows especially for production use, for example [running memcached on windows](http://latebound.blogspot.com/2008/10/running-memcached-on-windows.html). ...
Why do you need to run memcached on windows? It’s an expensive affair in a production environment. If your code needs to run in a Windows environment get a windows memcached client and talk to a \*nix based memcached machine. In a production environment running memcached on Server 2003 or 2008 would mean that you get...
I'm suprised no one here has yet to mention [Redis](http://code.google.com/p/redis/) - it is one of the most feature-rich and fastest (110,000 SET's per second on an entry level linux box) key-value data stores with rich data-structure support for strings, sets, lists, sorted sets and hashes. Although windows is not a...
Memcached with Windows and .NET
[ "", "c#", ".net-3.5", "memcached", "distributed-caching", "" ]
CodeIgniter allows access to POSTed data via: ``` $this->input->post('input_name'); ``` where 'input\_name' is the name of a form field. This works well for a static form where each input name in known ahead of time. In my case, I am loading a collection of key/value pairs from the database. The form contains a text...
According to the documentation, no. I would suggest just using `array_keys($_POST)` to get the keys.
``` foreach($this->input->post() as $key => $val) { echo "<p>Key: ".$key. " Value:" . $val . "</p>\n"; } ``` that can be used to
Get post values when the key is unknown in CodeIgniter
[ "", "php", "forms", "codeigniter", "post", "input", "" ]
I'm curious to know if there is an easy way to mock an IMAP server (a la the `imaplib` module) in Python, *without* doing a lot of work. Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure. Some background ...
I found it quite easy to write an IMAP server in twisted last time I tried. It comes with support for writing IMAP servers and you have a huge amount of flexibility.
As I didn't find something convenient in python 3 for my needs (mail part of twisted is not running in python 3), I did a small mock with asyncio that you can improve if you'd like : I defined an ImapProtocol which extends asyncio.Protocol. Then launch a server like this : ``` factory = loop.create_server(lambda: Ima...
How do I mock an IMAP server in Python, despite extreme laziness?
[ "", "python", "testing", "imap", "mocking", "" ]
I have an application which tries to load some expected registry settings within its constructor. What is the most appropriate .NET Exception from the BCL to throw if these (essential, non-defaultable) registry settings cannot be loaded? For example: ``` RegistryKey registryKey = Registry.LocalMachine.OpenSubkey("H...
I'd go with [ArgumentException](http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx) or [ArgumentOutOfRangeException](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception.aspx).. ``` throw new ArgumentException("Could not find registry key: " + theKey); ``` Quoting MSDN: > The...
Why not create your custom exception? ``` public class KeyNotFoundException : RegistryException { public KeyNotFoundException(string message) : base(message) { } } public class RegistryException : Exception { public RegistryException(string message) : base(message) { } } .... if (registryKey ...
What is the most appropriate .NET exception to throw upon failing to load an expected registry setting?
[ "", "c#", ".net", "" ]
Problem: I have an integer; this integer needs to be converted to a stl::string type. In the past, I've used `stringstream` to do a conversion, and that's just kind of cumbersome. I know the C way is to do a `sprintf`, but I'd much rather do a C++ method that is typesafe(er). Is there a better way to do this? Here i...
Now in c++11 we have ``` #include <string> string s = std::to_string(123); ``` Link to reference: <http://en.cppreference.com/w/cpp/string/basic_string/to_string>
Like mentioned earlier, I'd recommend boost lexical\_cast. Not only does it have a fairly nice syntax: ``` #include <boost/lexical_cast.hpp> std::string s = boost::lexical_cast<std::string>(i); ``` it also provides some safety: ``` try{ std::string s = boost::lexical_cast<std::string>(i); }catch(boost::bad_lexical...
c++ integer->std::string conversion. Simple function?
[ "", "c++", "integer", "stdstring", "" ]
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following [Haskell code](http://www.haskell.org/haskellwiki/List_comprehension): ``` [(i,j) | i <- [1,2], j <- [1..4]] ``` which yields ``` [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] ``` Can I...
Are you asking about this? ``` [ (i,j) for i in range(1,3) for j in range(1,5) ] ```
Cartesian product is in the [itertools module](http://docs.python.org/library/itertools.html#itertools.product) (in 2.6). ``` >>> import itertools >>> list(itertools.product(range(1, 3), range(1, 5))) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)] ```
In Python, is there a concise way to use a list comprehension with multiple iterators?
[ "", "python", "iterator", "list-comprehension", "" ]
I have a field in my form labeled "Name" that will contain both the First & Last name. Our existing dynamic server (to which the form is being POSTed to), expects two separate fields (first name, last name). Can I use Javascript to split the user input into two separate variables before the form is posted to the serv...
I would process this on the server end to make sure the data that is passed is accurate from what was posted. It's relatively easy programmatically to split the name, but the problem is how do you define your separator. Most would agree to split it wherever there is a white-space character, but what if they enter a thr...
You should not rely on client side parsing whenever possible. If you are sending this form to an app you can't modify, use the Javascript method mentioned above because you have no control over it (but then why not just have a first and last name field). But if you are controller the backend app, perform all your massa...
How can I reformat form input before POST using Javascript (or Rails)?
[ "", "javascript", "forms", "post", "" ]
I have a small app that has a Render thread. All this thread does is draw my objects at their current location. I have some code like: ``` public void render() { // ... rendering various objects if (mouseBall != null) mouseBall.draw() } ``` Then I also have some mouse handler that creates and sets mouseBal...
The problem lies in the fact that you are accessing `mouseBall` twice, once to check whether it is not `null` and another to call a function on it. You can avoid this problem by using a temporary like this: ``` public void render() { // ... rendering various objects tmpBall = mouseBall; if (tmpBall != null...
You have to synchronize the if and draw statements so that they are guaranteed to be run as one atomic sequence. In java, this would be done like so: ``` public void render() { // ... rendering various objects synchronized(this) { if (mouseBall != null) mouseBall .draw(); } } ```
Multi-threading: Objects being set to null while using them
[ "", "java", "multithreading", "nullpointerexception", "" ]
I was working with a new C++ developer a while back when he asked the question: "Why can't variable names start with numbers?" I couldn't come up with an answer except that some numbers can have text in them (123456L, 123456U) and that wouldn't be possible if the compilers were thinking everything with some amount of ...
Because then a string of digits would be a valid identifier as well as a valid number. ``` int 17 = 497; int 42 = 6 * 9; String 1111 = "Totally text"; ```
Well think about this: ``` int 2d = 42; double a = 2d; ``` What is a? 2.0? or 42? Hint, if you don't get it, d after a number means the number before it is a double literal
Why can't variable names start with numbers?
[ "", "c++", "variables", "programming-languages", "language-design", "variable-names", "" ]
table data of 2 columns "category" and "subcategory" i want to get a collection of "category", [subcategories] using code below i get duplicates. Puting .Distinct() after outer "from" does not help much. What do i miss? ``` var rootcategories = (from p in sr.products orderby p.catego...
solved with this code ``` var rootcategories2 = (from p in sr.products group p.subcategory by p.category into subcats select subcats); ``` thanks everyone
I think you need 2 "Distinct()" calls, one for the main categories and another for the subcategories. This should work for you: ``` var mainCategories = (from p in products select p.category).Distinct(); var rootCategories = from c in mainCategories select new { category = c, subcategories = ...
nested linq queries, how to get distinct values?
[ "", "c#", "linq", "linq-to-sql", "" ]
Is it possible to create a MySQL select statement that uses an expression as x then checks if the value for x is under a certain amount? ``` SELECT (mytable.field1 + 10) AS x FROM `mytable` WHERE x < 50; ```
no you have to actually do this ``` SELECT (mytable.field1 + 10) AS x FROM `mytable` WHERE (mytable.field1 + 10) < 50; ```
You could also do it like this: ``` SELECT * FROM ( SELECT (mytable.field1 + 10) AS X FROM `MyTable` ) t WHERE X < 50 ``` In most cases it's probably better to use Nick's solution, since it allows the server to apply the where clause earlier in the process. However, occasionally you will want to do it this wa...
Compare result of 'as' expression in 'where' statement
[ "", "sql", "mysql", "" ]
Should the model just be data structures? Where do the services (data access, business logic) sit in MVC? Lets assume I have a view that shows a list of customer orders. I have a controller class that handles the clicks on the view controls (buttons, etc). Should the controller kick off the data access code? Think bu...
Generally I implement MVC as follows: View - Receives data from the controller and generates output. Generally only display logic should appear here. For example, if you wanted to take an existing site and produce a mobile/iPhone version of it, you should be able to do that just by replacing the views (assuming you wa...
I wouldn't put Data Access Code in the Controller. To build on what has already been said, it's important to think of layering WITHIN the layers. For example, you will likely have multiple layers within the Model itself - a Data Access Layer which performs any ORM and Database access and a more abstract layer which re...
MVC: View and Model Interaction Regarding Data Access, etc
[ "", "c#", "model-view-controller", "" ]
I'm trying to get an object element from my webpage using getElementById (ultimately so I can replace it with a dynamically created object element) but it is returning `null` in IE6. In the following code, the `byId()` function returns `null` in IE but an `[object HTMLObjectElement]` in Firefox 3 and the `lengthOfByTa...
This is because of the way IE treats <object> nodes vis-a-vis the DOM. Since you're dynamically replacing anyway I recommend you instead create a <div> where you need it and change the innerHTML to be the HTML for the object you require.
I've just tested on IE 7 and seen the behavior as described Internet Explorer doesn't expect free text in an `<object>` tag. Using Debugbar on you sample prooved that IE doesn't build the right DOM tree. Use this code instead ``` <object type="" id="VideoPlayer"> <param name="allowScriptAcess" value="always" /> ...
IE6 can't find Object element with getElementById()?
[ "", "javascript", "internet-explorer", "internet-explorer-6", "getelementbyid", "" ]
I'm encountering problems with my .NET Framework 3.0 SP1 application. It is a C# winforms application communicating with a COM exe. Randomly either the winforms app or the COM exe crashes without any error message and the event log contains this entry: [1958] .NET Runtime Type: ERROR Computer: CWP-OSL029-01 Time: 11/2...
I had this error, it (luckily) went away by installing 3.5 SP1, which bumps your runtime to version 2.0.50727.3053 ([this](http://blogs.msdn.com/dougste/archive/2007/09/06/version-history-of-the-clr-2-0.aspx) is a nice version summary). While hunting for solutions I found a wild range of suspects for this error. Some ...
Microsoft released a hotfix <https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&wa=wsignin1.0>
Fatal Execution Engine Error (79FFEE24) (80131506)
[ "", "c#", "com", "clr", "" ]
*Let's say I have download links for files on my site.* When clicked these links send an AJAX request to the server which returns the URL with the location of the file. What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
Try this lib <https://github.com/PixelsCommander/Download-File-JS> it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience. Explained here - <http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-t...
We do it that way: First add this script. ``` <script type="text/javascript"> function populateIframe(id,path) { var ifrm = document.getElementById(id); ifrm.src = "download.php?path="+path; } </script> ``` Place this where you want the download button(here we use just a link): ``` <iframe id="frame1" style...
starting file download with JavaScript
[ "", "javascript", "ajax", "download", "" ]
I am trying to use some AOP in my Python programming, but I do not have any experience of the various libraries that exist. So my question are: > What AOP support exists for Python? And what are the advantages of the differents libraries between them? --- ### Edit I've found some, but I don't know how they compare...
Edit: I no longer maintain pytilities and it has been unmaintained for years. You may want to consider one of the other answers instead or this [list on Wikipedia](https://en.wikipedia.org/wiki/Aspect-oriented_programming#cite_note-41). Another AOP library for python would be [`pytilities`](https://pypi.org/project/py...
See S.Lott's link about Python decorators for some great examples, and see the [defining PEP for decorators](http://www.python.org/dev/peps/pep-0318/). Python had AOP since the beginning, it just didn't have an impressive name. In Python 2.4 the decorator syntax was added, which makes applying decorators very nice syn...
Any AOP support library for Python?
[ "", "python", "aop", "" ]
Curious to get people's thoughts. I conduct frequent interviews, and have had enough in my career to reflect on them, and I've noticed a broad array of questions. I made this c++ specific, but it's worth noting that I have had people ask me algorithmic complexity questions over the phone, and I don't even mean what is ...
I'd ask about resource/memory management, because it's an important subject in C++, and it doesn't require concrete code. Just sketch a simple hypothetical scenario, and ask how they'd ensure some vital resource gets freed even in the face of errors/exceptions. Say they're developing a network app, how do they ensure t...
I like to find out if people actually know anything about the tools they're using. And I also find that "senior" developers can have serious gaps in their knowledge. You could consider asking * What a vtable is. * How templates work * What the difference between the heap and the stack is. The depth of the reply to th...
What kinds of interview questions are appropriate for a c++ phone screen?
[ "", "c++", "" ]
I am looking for a regex statement that will let me extract the HTML content from just between the body tags from a XHTML document. The XHTML that I need to parse will be very simple files, I do not have to worry about JavaScript content or `<![CDATA[` tags, for example. Below is the expected structure of the HTML fi...
Would this work ? ``` ((?:.(?!<body[^>]*>))+.<body[^>]*>)|(</body\>.+) ``` Of course, you need to add the necessary `\s` in order to take into account `< body ...>` (element with spaces), as in: ``` ((?:.(?!<\s*body[^>]*>))+.<\s*body[^>]*>)|(<\s*/\s*body\s*\>.+) ``` On second thought, I am not sure why I needed a n...
XHTML would be more easily parsed with an XML parser, than with a regex. I know it's not what youre asking, but an XML parser would be able to quickly navigate to the body node and give you back its content without any tag mapping problems that the regex is giving you. EDIT: In response to a comment here; that an XML ...
Regular Expression to Extract HTML Body Content
[ "", "c#", "html", "regex", "xhtml", "" ]
My application is receiving email through SMTP server. There are one or more attachments in the email and email attachment return as byte[] (using sun javamail api). I am trying to zip the attachment files on the fly without writing them to disk first. What is/are possible way to achieve this outcome?
You can use Java's java.util.zip.ZipOutputStream to create a zip file in memory. For example: ``` public static byte[] zipBytes(String filename, byte[] input) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); ZipEntry entry = new...
I have the same problem but i needed a many files in a zip. ``` protected byte[] listBytesToZip(Map<String, byte[]> mapReporte) throws IOException { String extension = ".pdf"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); for (Entry<String, ...
In Java: How to zip file from byte[] array?
[ "", "java", "zip", "" ]
"Fatal error: Allowed memory size of 31457280 bytes exhausted (tried to allocate 9828 bytes)". This is the error i get but I am only trying to upload a 1mb image. I have increased the memory limit in php.ini and the execution time. I am trying this on a local MAMP server, on a Mac using firefox. This going to be for a...
You're likely loading the image to do some manipulation of it. That causes the image data to be decompressed, which requires a lot of memory for big images (I think it's about 4 bytes per pixel). You can choose to either not process the image, or do your processing outside of PHP - for example by invoking ImageMagick ...
It's nothing to do with the (file)size of the image you're uploading, the call that's breaking your memory limit is imagecreatetruecolor(). imagecreatetruecolor() will allocate an area of memory to store a true colour image in with *no* compression, and use 32 bits (4 bytes) per pixel. So for a 1024x768 pixel image, ...
Trying to upload a 1M file locally and i get a Fatal Error
[ "", "php", "" ]
I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles. Here's what I need to do: 1. Do a POST with a few parameters and headers. 2. Follow a redirect 3. Retrieve the HTML body. Now, I'm relatively new to python, but the two things I've tested so far h...
Focus on `urllib2` for this, it works quite well. Don't mess with `httplib`, it's not the top-level API. What you're noting is that `urllib2` doesn't follow the redirect. You need to fold in an instance of `HTTPRedirectHandler` that will catch and follow the redirects. Further, you may want to subclass the default `...
Here's my take on this issue. ``` #!/usr/bin/env python import urllib import urllib2 class HttpBot: """an HttpBot represents one browser session, with cookies.""" def __init__(self): cookie_handler= urllib2.HTTPCookieProcessor() redirect_handler= urllib2.HTTPRedirectHandler() self._o...
Python: urllib/urllib2/httplib confusion
[ "", "python", "http", "urllib2", "" ]
As the question says, it just escaped my memory how to display xml in javascript, I want to display some source xml within an div on a page, that sits next to the processed result of the xml in another div. Can't remember if there was an equivalent to javascript's escape to convert entities on the client **Note**: th...
If you want the *browser to render* your `XML` as `XML`, it must be in it's own document, like an `iframe`, or a `frame`. `DIV` won't do the job! Besides, in the `HTTP` header of the request that serves the `iframe` you should send `Content-Type: text/xml`, so the Browser can understand that this content is an `XML`. ...
Fetch your XML using Ajax and simply put the result in a `textarea`. Style the textarea any way you want.
how to display xml in javascript?
[ "", "javascript", "xml", "" ]
I need to get a count of the number of files in a directory. I could get the names of all the files in the directory using `System.IO.Directory.GetFiles()` and take the length of that array but that takes too long on large directories. Is there a way to get just the count without having to get the names?
I don't believe so, no - at least not in vanilla .NET. I suspect it's not the actual fetching of the names that takes the time - it's the OS walking through the directory internals. There *may* be a Win32 call you could make via P/Invoke. How large is the directory you're looking at? In general it's at least *traditio...
I did a little test - wrote the same task in C++/Qt and C++/CLI: ``` LARGE_INTEGER i1, i2; QueryPerformanceCounter(&i1); int count = IO::Directory::GetFiles(L"c:\\windows\\system32")->Length; QueryPerformanceCounter(&i2); __int64 result = i2.QuadPart - i1.QuadPart; ``` Result is about 16.500.000 an...
How do I find out how many files are in a directory?
[ "", "c#", ".net", "file-io", "" ]
I think there must be something subtle going on here that I don't know about. Consider the following: ``` public class Foo<T> { private T[] a = (T[]) new Object[5]; public Foo() { // Add some elements to a } public T[] getA() { return a; } } ``` Suppose that your main method contains the following...
``` Foo<Double> f = new Foo<Double>(); ``` When you use this version of the generic class Foo, then for the member variable `a`, the compiler is essentially taking this line: ``` private T[] a = (T[]) new Object[5]; ``` and replacing `T` with `Double` to get this: ``` private Double[] a = (Double[]) new Object[5]; ...
There may be some small errors in @mattb's explanation. The error is *not* > java.lang.Object cannot be cast to java.lang.Double. It is: > [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double The [L means an array. That is, the error is that an *array* of Objects cannot be cast to an array of Double. This is t...
Generics, arrays, and the ClassCastException
[ "", "java", "arrays", "generics", "classcastexception", "" ]
I'm trying to learn how to do passphrase-based encryption with Java. I'm finding several examples online, but none (yet) on Stack Overflow. The examples are a little light on explanation for me, particularly regarding algorithm selection. There seems to be a lot of passing strings around to say what algorithms to use, ...
I'll be cautious about giving or taking security-related advice from a forum... the specifics are quite intricate, and often become outdated quickly. Having said that, I think Sun's [Java Cryptography Architecture (JCA) Reference Guide](http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html...
Use [RFC2898](http://www.ietf.org/rfc/rfc2898.txt) to generate keys from passwords. This isn't included in the JRE or JCE, as far as I know, but it is included in J2EE Servers like [JBoss](http://docs.jboss.com/seam/latest/api/org/jboss/seam/security/crypto/PBKDF2.html), Oracle, and [WebSphere](http://download.oracle.c...
Java passphrase encryption
[ "", "java", "encryption", "passphrase", "" ]
Is it good practice to have more than one `try{} catch{}` statement per method?
In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it. As Lisa pointed out you should catch specific exceptions and *only* catch the exceptions the method can ...
If you know the type of Exceptions that could occur beforehand, you can have a single try and catch each of those exceptions, should you want to handle them differently. For example: ``` try { // a bunch of risky code } catch (SpecificException1 ex1) { // handle Specific Exception 1 } catch (SpecificException...
Exception Handling in C#: Multple Try/Catches vs. One
[ "", "c#", "exception", "" ]
Is there a way to get notification of date change in c#? I have a requirement where I have to do something when the system date is changed. I found that SystemsEvent.TimeChanged is an event you can hook into, however it is only fired only when user has changed the time.
Would this be better handled by having a scheduled task/cron job that runs at midnight?
You could implement this (admittedly poorly) as follows: Write a very lightweight class which simply stores the current date. Start it in a separate thread and make it periodically check the date, then sleep for a large amount of time (in fact, you could make it sleep for just longer than the time left until midnight)...
Is there a way to get notification of date change in c#?
[ "", "c#", "date", "" ]
I have a MFC dialog with 32 CComboBoxes on it that all have the same data in the listbox. Its taking a while to come up, and it looks like part of the delay is the time I need to spend using InsertString() to add all the data to the 32 controls. How can I subclass CComboBox so that the 32 instances share the same data?
Turn off window redrawing when filling the combos. e.g.: ``` m_wndCombo.SetRedraw(FALSE); // Fill combo here ... m_wndCombo.SetRedraw(TRUE); m_wndCombo.Invalidate(); ``` This might help.
One way along the lines of your request would be to go owner drawn - you will be writing a fair chunk of code, but you won't have to add the data to all of them. "[CComboBox::DrawItem](http://msdn.microsoft.com/en-us/library/y5hb5f9t.aspx)" Support.microsoft have this article on subclassing a Combo box which might als...
multiple CComboBox sharing the same data
[ "", "c++", "mfc", "" ]
I am working on an application that involves some gis stuff. There would be some .shp files to be read and plotted onto an opengl screen. The current opengl screen is using the orthographic projection as set from `glOrtho()` and is already displaying a map using coordinates from a simple text file.. Now the map to be ...
1. Shapefile rendering is quite straight forward in OpenGL. You may require "shapelib",a free shapefile parsing library in C(Google it). Use GL\_POINTS for point shapefile, GL\_LINES for line shapefile and GL\_LINE\_LOOP for polygon shapefile. Set your bounding box coords to the Ortho. 2. What you read from the .prj...
Please, read the [OGR API Tutorial](http://gdal.org/ogr/ogr_apitut.html) where you can learn how to read vector data from sources like Shapefile. Next, check the [OGR Projections Tutorial](http://gdal.org/ogr/osr_tutorial.html) where you can learn about how to use information about projection and spatial reference syst...
using GDAL/OGR api to read vector data (shapefile)--How?
[ "", "c++", "linux", "opengl", "gdal", "" ]
I generally try and keep all related entities in the same repository. The following are entities that have a relationship between the two (marked with indentation): * User + UserPreference So they make sense to go into a user repository. However users are often linked to many different entities, what would you do i...
In the Eric Evan's Domain Driven Design ( <http://domaindrivendesign.org/index.htm> ) sense of things you should first think about what about your Aggregates. You then build you repositories around those. There are many techniques for handling Aggregates that relate to each other. The one that I use most often is to o...
By repository you mean class? Depending on the use of the objects (repositories) you could make a view that combines the data on the database and create a class (repository) with your ORM to represent that view. This design would work when you want to display lighter weight objects with only a couple columns from each...
When to separate certain entities into different repositories?
[ "", "c#", ".net", "design-patterns", "domain-driven-design", "repository-design", "" ]
I need to cut out and save/use part of a string in C#. I figure the best way to do this is by using Regex. My string looks like this: `"changed from 1 to 10"`. I need a way to cut out the two numbers and use them elsewhere. What's a good way to do this?
Error checking left as an exercise... ``` Regex regex = new Regex( @"\d+" ); MatchCollection matches = regex.Matches( "changed from 1 to 10" ); int num1 = int.Parse( matches[0].Value ); int num2 = int.Parse( matches[1].Value ); ```
Matching only exactly the string "changed from x to y": ``` string pattern = @"^changed from ([0-9]+) to ([0-9]+)$"; Regex r = new Regex(pattern); Match m = r.match(text); if (m.Success) { Group g = m.Groups[0]; CaptureCollection cc = g.Captures; int from = Convert.ToInt32(cc[0]); int to = Convert.ToInt32...
How do I "cut" out part of a string with a regex?
[ "", "c#", "regex", "" ]
Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code: ``` <html> <head> <style> <!-- .some_class { padding-left: 2px; border: 2px solid green; } --> </style> ...
It's possible, but of course, every browser has its own implementation. Luckily, PPK has done all the hard work for us: <http://www.quirksmode.org/dom/getstyles.html>
the `style` property can get the styles that are assigned inline like `<div id="target" style="color:#ddd;margin:10px">test</div>` if you want to get the styles assigned in outer css file or `<style/>` element, try this: ``` var div = document.getElementById("target"); var style = div.currentStyle || window.getComput...
detecting true border, padding and margin from Javascript
[ "", "javascript", "css", "border", "padding", "margin", "" ]
I there a PHP based source control 'server' that is compatible with SVN clients? I'd like to host my SVN on my hosting servers, however the current host will not allow me to start any process or install any software
You can have a PHP front end but you will still need to have the SVN server running somewhere.
You could try: <http://sourceforge.net/projects/deltaweb>
PHP Source Control Server
[ "", "php", "svn", "version-control", "" ]
I'm trying to do query result pagination with hibernate and displaytag, and Hibernate `DetachedCriteria` objects are doing their best to stand in the way. Let me explain... The easiest way to do pagination with displaytag seems to be implementing the `PaginatedList` interface that has, among others, the following meth...
well, DetachedCriteria are Serializable, so you have built-in (if inelegant) deep clone support. You could serialize the initial criteria to a byte[] once on construction, then deserialize it each time you want to use it.
``` Criteria.setProjection(null); Criteria.setResultTransformer(Criteria.ROOT_ENTITY); ``` Will effectively "reset" the criteria between the rowCount projection and execution of the criteria itself. I would make sure your Order hasn't been added before doing the rowCount, it'll slow things down. My implementation of ...
How to reuse a Criteria object with hibernate?
[ "", "java", "hibernate", "spring-mvc", "pagination", "displaytag", "" ]
I have 3 tables, foo, foo2bar, and bar. foo2bar is a many to many map between foo and bar. Here are the contents. ``` select * from foo +------+ | fid | +------+ | 1 | | 2 | | 3 | | 4 | +------+ select * from foo2bar +------+------+ | fid | bid | +------+------+ | 1 | 1 | | 1 | 2 | | 2 |...
``` SELECT * FROM foo LEFT OUTER JOIN (foo2bar JOIN bar ON (foo2bar.bid = bar.bid AND zid = 30)) USING (fid); ``` Tested on MySQL 5.0.51. This is not a subquery, it just uses parentheses to specify the precedence of joins.
``` SELECT * FROM foo LEFT JOIN ( Foo2bar JOIN bar ON foo2bar.bid = bar.bid AND zid = 30 ) ON foo.fid = foo2bar.fid; ``` untested
How do you do many to many table outer joins?
[ "", "sql", "join", "many-to-many", "operator-precedence", "" ]
I'm working on a very simple game (essentially an ice sliding puzzle), for now the whole things in one file and the only level is completely blank of any form of obstacle. It throws up a few errors. My current annoyance is an expected primary expression error, can anyone tell me how to fix it (it throws up at line 99)?...
This might help: ``` void movePlayer(){ tempX = x; tempY = y; if (key[KEY_UP] && map[y - 1][x] == 3) for ( ; map[y - 1][x] == 3; --y){ } else if(key[KEY_DOWN] && map[y + 1][x] == 3) for ( ; map[y + 1][x] == 3; ++y){ } else if(key[KEY_RIGHT] && map[y...
What is going on here? ``` [y - 1][x] == 3 ``` Did you mean: ``` map[y - 1][x] == 3 ```
c++ expected primary expression
[ "", "c++", "expression", "" ]
I'm struggling with the following problem. I use the [jQuery autocomplete plugin](http://docs.jquery.com/Plugins/Autocomplete/autocomplete) to get a list of suggested values from the server. The list would look like this: ``` Username1|UserId1 Username2|UserId2 ``` So if I start typing "U", a list of `"Username1"` an...
Use the `result` method of the `autocomplete` plugin to handle this. The data is passed as an array to the callback and you just need to save `data[1]` somewhere. Something like this: ``` $("#my_field").autocomplete(...).result(function(event, data, formatted) { if (data) { $("#the_id").attr("value", data[...
I was going to list a few methods here but all but one is junk. Do the string->user conversion on the server as you've been doing to generate a list for the auto-complete. By all means keep the auto-complete and do AJAX validation, but if you try and smuggle vital form data (like this) in the form via JS, something *w...
jQuery autocomplete - How to handle extra data?
[ "", "javascript", "jquery", "autocomplete", "" ]
I'm looking for some useful books for a beginner who wants to better understand the Sun JVM
Not specific to the Sun Java Virtual Machine implementation, but [The Java Virtual Machine Specifications](http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html) from Sun may be an interesting read.
You can try out this. Ivor Horton's Beginning Java 2 SDK 1.5 Edition
Understanding the Sun JVM
[ "", "java", "jvm", "" ]
I have an abstract class defining a pure virtual method in c++: ``` class Base { Base(); ~Base(); virtual bool Test() = 0; }; ``` I have subclassed this with a number of other classes (which provide an implementation for Test()), which I'll refer to as A, B, C, etc. I now want to create an array of any of these type...
There is only a slight misunderstanding in that code. Instead of allocating Base objects, you have to allocate pointers. A pointer can exist at any time. A pointer to a abstract class, to an incomplete type, and even to void is valid: ``` int main(int argc, char* argv[]) { int size = 0; Base** bases = new Base...
First, make sure that your destructor is also declared as virtual: ``` virtual ~Base(); ``` You're better off storing a an array of pointers to instances: ``` Base** bases = new Base *[10]; ```
How to allocate memory to an array of instances using an abstract class?
[ "", "c++", "memory", "abstraction", "" ]
[Tomcat documentation](http://tomcat.apache.org/tomcat-5.5-doc/deployer-howto.html) says: The locations for Context Descriptors are; $CATALINA\_HOME/conf/[enginename]/[hostname]/context.xml $CATALINA\_HOME/webapps/[webappname]/META-INF/context.xml On my server, I have at least 3 files floating around: ``` 1 ...to...
For the files you listed, the simple answer assuming you are using all the defaults, the order is (note the **conf**/Catalina/localhost): ``` ...tomcat/conf/context.xml ...tomcat/conf/Catalina/localhost/myapp.xml ...tomcat/webapps/myapp/META-INF/context.xml ``` I'm basing this (and the following discussion) on the [T...
My understanding is: * tomcat/conf/context.xml is the "default" context.xml whose contents are overlayed with the webapp context definitions. My TC 5 default context.xml has almost nothing in it, other than listing the web.xml as a watched resource, which supports this notion. * tomcat/Catalina//.xml is used for the w...
Which Tomcat 5 context file takes precedence?
[ "", "java", "tomcat", "configuration", "settings", "context.xml", "" ]
I'm currently building a project and I would like to make use of some simple javascript - I know some people have it disabled to prevent XSS and other things. Should I... a) Use the simple javascript, those users with it disabled are missing out b) Don't use the simple javascript, users with it enabled have to click ...
Degrade gracefully - make sure the site works without JavaScript, then add bells and whistles for those with JavaScript enabled.
Everyone else has committed good comments, but there are a few other considerations to make. ### Sometimes the javascript will be hosted on a different domain, and be prone to timeout. Sometimes that domain may become inacessible, while your site remains accessible. Its not good to have your site completely stack its...
Is it worth it to code different functionality for users with javascript disabled?
[ "", "javascript", "" ]
what is the best way to track and lower GDI windows handles . .
Two links worth reading... [Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code](http://msdn.microsoft.com/en-us/magazine/cc301756.aspx) [GDI Resource Leaks](http://www.relisoft.com/win32/GdiLeaks.html)
Personally I use [IARSN TaskInfo](http://www.iarsn.com/taskinfo.html) to see the number of handles my program uses, GDI included. As for lowering the number of active handles, then I would look at what in your application is using handles. Things like (but not limited to): * Pens * Bitmaps * Controls (I don't think a...
What is the best way to track and lower GD handles?
[ "", "c#", "windows", "memory", "gdi", "" ]
I want to centrally locate all of my application settings in the database. I have a database object which stores the app.settings in an XML column. I'd like to have my application read that object and then parse the XML column into its own app settings. Is there any easy way to arbitrarily read an XML object into your ...
Read the object from your XML object, and then through your code you can save your config file as : > Configuration configFile = > WebConfigurationManager.OpenWebConfiguration("~"); > > AppSettingsSection AppSection = > configFile.GetSection("appSettings") > as AppSettingsSection; > > AppSection.Settings.Add( > new Ke...
I dont know if you can alter the appsettings in runtime what i do know you can do is create the appsettings section like shown [here](http://msmvps.com/blogs/simpleman/archive/2005/06/23/54733.aspx) and have a relay application that loads the correct xml for you appsettings save the file and then launch the desire appl...
Application Settings in the Database
[ "", "c#", ".net", "settings", "" ]
I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient. ``` Allocation(Param1 = Val1, Param2 = Val2 ) ``` However, it does not support param names with ...
Here's my preference. ``` AllocationSet( Alloc( name="some name", value=1.23 ), Alloc( name="another name", value=2.34 ), Alloc( name="yet another name", value=4.56 ), ) ``` These are relatively easy class declarations to create. The resulting structure is pleasant to process, too.
I'd imagine that there would be some way to do it. But I feel compelled to ask, is there really a big enough difference in readability from this ``` Allocation(Param1 = Val1, Param2 = Val2 ) ``` To this: ``` Allocation(Param 1 = Val1, Param 2 = Val2 ) ``` to make that big a difference? I'm sure there's a way to do ...
Python method arguments with spaces
[ "", "python", "dsl", "" ]
Hey everyone. I'm trying to make a swing GUI with a button and a label on it. im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field). any idea how to fix this?
You have to add the button to another panel, and then add that panel to the frame. It turns out the BorderLayout expands what ever component is in the middle Your code should look like this now: Before ``` public static void main( String [] args ) { JLabel label = new JLabel("Some info"); JButton button = n...
Or just use Absolute layout. It's on the Layouts Pallet. Or enable it with : ``` frame = new JFrame(); ... //your code here // to set absolute layout. frame.getContentPane().setLayout(null); ``` This way, you can freely place the control anywhere you like.
JButton expanding to take up entire frame/container
[ "", "java", "user-interface", "swing", "jframe", "jbutton", "" ]
I'm trying to connect to a remote database (hosted on Netfirms [www.netfirms.ca](http://www.netfirms.ca) if anyone is curious) using hibernate. My mapping file is as follows: ``` <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> ...
It turns out that there were several issues with the connection: 1. Although the site said to use mysql.netfirms.ca on the Control Panel, their generic instructions were correct and I was supposed to use mysql.netfirms.com as someone else mentioned earlier. 2. Netfirms was having some issues with their site, and appar...
I guess the first step will be to check (since you didn't say that you already tried), if you can connect to the database using some SQL tool. Like SQuirrel for example.
Problem connecting to a remote database using hibernate
[ "", "java", "database", "hibernate", "" ]
I've been reading through the details of the `System` libraries `set` and `get` methods yet the parameters are usually Strings. Would you consider the use of `String` as parameters bad practise since the inclusion of `enum`? A better alternative at minimum might be `public final String`, No?
I would consider Enums to be a better approach than Strings. They are type safe and comparing them is faster than comparing Strings. As a pre Java 1.5 alternative you could use the type-safe enum pattern suggested by Joshua Bloch in his book Effective Java. For type-safe enums see also <http://www.javacamp.org/designP...
If your set of parameters is limited and known at compile time, use `enum`. If your set of parameters is open and unkown at compile time, use strings.
Java: `enum` vs `String` as Parameters
[ "", "java", "enums", "string", "constants", "" ]
I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class a...
You need an event handler in your bind expression ``` self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) ``` needs to be changed to: ``` self.bind(wx.EVT_MENU, <event handler>, <id of menu item>) ``` where your event handler responds to the event and instantiates the subpanel: ``` def OnMenuItem(self, evt): #...
You should handle the button click event, and create the panel in your button handler (like you already do with your OnQuit method). I think the following code basically does what you're after -- creates a new Frame when the button is clicked/menu item is selected. ``` import wx class MyFrame(wx.Frame): def __in...
How do I Create an instance of a class in another class in Python
[ "", "python", "oop", "wxpython", "" ]
I'm trying to scrape a price from a web page using PHP and Regexes. The price will be in the format £123.12 or $123.12 (i.e., pounds or dollars). I'm loading up the contents using libcurl. The output of which is then going into `preg_match_all`. So it looks a bit like this: ``` $contents = curl_exec($curl); preg_mat...
Have you try to use \ in front of £ ``` preg_match_all('/(\$|\£)[0-9]+(\.[0-9]{2})/', $contents, $matches); ``` I have try this expression with .Net with \£ and it works. I just edited it and removed some ":". [![alt text](https://i.stack.imgur.com/DwYIJ.png)](https://i.stack.imgur.com/DwYIJ.png) (source: [clip2net...
maybe pound has it's html entity replacement? i think you should try your regexp with some sort of couching program (i.e. match it against fixed text locally). i'd change my regexp like this: `'/(?:\$|£)\d+(?:\.\d{2})?/'`
Scrape a price off a website
[ "", "php", "regex", "character-encoding", "" ]
I have just come across a Visual C++ option that allows you to force file(s) to be included - this came about when I was looking at some code that was missing a `#include "StdAfx.h"` on each .cpp file, but was actually doing so via this option. The option can be found on the **Advanced C/C++ Configuration Properties**...
I would discourage from /FI ([MSDN](http://msdn.microsoft.com/en-us/library/8c5ztk84.aspx) says it's called /FI . Not sure whether i looked at the right page though), simply because people or yourself reading the files don't notice a header is magically included anyway. You can be sure this will cause much debugging t...
I would say the opposite to litb above if you're using precompiled headers. If you use "stdafx.h" as your precompiled header and have code like this: ``` #include "afile.h" #include "stdafx.h" ``` then you'll be spending an age trying to figure out why "afile.h" isn't being included. When using precompiled headers, a...
Visual C++ 'Force Includes' option
[ "", "c++", "visual-c++", "" ]
I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn't work in Internet Explorer. Here is the JavaScript I have: ``` function SetTopMargin (ObjectID, Value) { document.getElementById(ObjectID).style.marginTop = Value.toString() + "px"; } ``` And i...
[Updated in 2016] On all current browsers (including IE8+), your code ``` document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px'; ``` works fine. On *very old* IE (< 8) versions, you must use this non-standard contraption instead: ``` document.getElementById(ObjectId).style.setAttribute( 'ma...
Your code works in IE8 for me. ``` <html> <head> <script type="text/javascript"> function SetTopMargin (ObjectID, Value) { document.getElementById(ObjectID).style.marginTop = Value.toString() + "px"; } </script> </head> <body> <button id="btnTest" onclick="SetTopMargin('btnTest', ...
How do I set the margin of an object in IE?
[ "", "javascript", "css", "internet-explorer", "" ]
I'm writing cross platform C++ code (Windows, Mac). Is there a way to check how much memory is in use by the current process? A very contrived snippet to illustrate: ``` unsigned long m0 = GetMemoryInUse(); char *p = new char[ random_number ]; unsigned long m1 = GetMemoryInUse(); printf( "%d bytes used\n", (m1-m0) ); ...
* There is no portable way to do that. * For most Operating systems, there isn't even a reliable way to do it specific to that OS.
Here's some code I wrote to try to do this in a portable way. It's not perfect, but I think it should at least give a pointer to how to do this on each of several platforms. (P.S. I use OSX and Linux regularly, and know this works well. I use Windows more rarely, so caveats apply to the Windows clause, but I think it'...
How do I programmatically check memory use in a fairly portable way? (C/C++)
[ "", "c++", "memory", "portability", "" ]
Every time that I change a value in the designer after saving it, the .designer.cs file will be deleted. Can anyone tell me how can I fix this problem?
Move `using` directives in your `DataContext.cs` and `DataContext.designer.cs` files into the `namespace` scope.
The \*.designer.cs files are completely generated by designer. You should not write any your own code into this file. The classes and/or methods are partial, so you can extend/change the behaviour in the separate file.
LINQ to SQL Designer Bug
[ "", "sql", "linq", "" ]
Just that... I get a string which contains a path to a file plus some arguments. How can I recognize the path? I thought about the index of the '.' in the file... but I don't like it. What about using regular expressions? Can anyone point me in the right direction? Regards Edit: Theses are valid entries... somefi...
For non-MSI programs, UninstallString is passed to CreateProcess, so you probably want to replicate its method of determining the filename. Read <http://msdn.microsoft.com/en-us/library/ms682425.aspx>, especially the notes for lpApplicationName and the second half of lpCommandLine. Programs installed by MSI have a sep...
You can use System.IO.Path, and it's static methods. ``` bool isPath = System.IO.Path.GetDirectoryName(@"C:\MyFolder\SomeFile.exe -i -d") != String.Empty; if (isPath) { Console.WriteLine("The string contains a path"); } ``` The static Path class has several other methods which are useful as well, like .GetFilenam...
How to recognize a path inside a string
[ "", "c#", "regex", "string", "" ]
I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a ...
See <http://code.activestate.com/recipes/546530/> This is the approximate size of Python objects. The OO size "penalty" is often offset by the ability to (a) simplify processing and (b) keep less stuff in memory in the first place. There is no OO performance overhead. Zero. In C++, the class definitions are optimize...
You'd have similar issues with procedural/functional programming languages. How do you store that much data in memory? A struct or array wouldn't work either. You need to take special steps to manage this scale of data. BTW: I wouldn't use this as a reason to pick either an OO language or not.
What is the object oriented programming computing overhead cost?
[ "", "python", "oop", "data-analysis", "" ]
Is it possible Firebug may be incorrectly adding downloads to the Net tab when things may be loaded from the cache? I have some code in a Javascript gallery which is meant to lazily download an image when the thumbnail is clicked and then display it once downloaded. It is meant to determine if it's been downloaded alr...
The image appearing in the net tab in firebug does not mean it is downloaded from the server. Check the HTTP response code that firebug reports for the image - for me after one visit, it kept returning "304 - Not Modified" which means it is being loaded from the cache. You can avoid the extra HTTP request that checks ...
Firebug might not be 100% correct, or at least, that might not be exactly what would be happening if Firebug was turned off. I would try using Fiddler or maybe WireShark to check the network activity, see if it looks any different. [Fiddler](http://www.fiddlertool.com/fiddler/) is a debugging proxy for IE, [WireShark]...
Is Firebug always correct at how it lists downloads with the Net tab?
[ "", "javascript", "firebug", "" ]
So here's what I'm looking to achieve. I would like to give my users a single google-like textbox where they can type their queries. And I would like them to be able to express semi-natural language such as ``` "view all between 1/1/2008 and 1/2/2008" ``` it's ok if the syntax has to be fairly structured and limited ...
You are describing a programming language. Granted it's a small language (often called a little language, or Domain Specific Language (DSL)). If you've never heard the term recursive descent parser, you are probably better off following Paul's advice and using drop down boxes of some description. However, again, I wou...
For a very simple language, I'd go with regexps. Main benefit there is you don't have to deal with any code generation. Debugging of the pattern matching is basically nil, though. If your language is moderately complex (you wouldn't mind specifying the entire thing in a single grammar file), I'd go with [Coco/R](http:...
Parsing a User's Query
[ "", "c#", "parsing", "tokenize", "" ]
In the case when I want to check, if a certain entry in the database exists I have two options. I can create an sql query using COUNT() and then check, if the result is >0... ...or I can just retrieve the record(s) and then count the number of rows in the returned rowset. For example with $result->num\_rows; What's ...
``` SELECT 1 FROM (SELECT 1) t WHERE EXISTS( SELECT * FROM foo WHERE id = 42 ) ``` Just tested, works fine on MySQL v5 COUNT(\*) is generally less efficient if: 1. you can have duplicates (because the DBMS will have to exhaustively search all of the records/indexes to give you the exact answer) or 2. h...
YMMV, but I suspect that if you are only checking for existence, and don't need to use the retrieved data in any way, the COUNT() query will be faster. How much faster will depend on how much data.
Where should I do the rowcount when checking for existence: sql or php?
[ "", "sql", "count", "" ]
I trying to learn swt, and I use maven for all my builds and eclipse for my IDE. When getting the swt jars out of the maven repository, I get: ``` Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-pi-gtk-3034 in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1709) at ja...
Sounds like Maven is pulling in an old version of SWT. As of v3.4 (and higher), the swt.jar is *all* you need. SWT will automatically extract the `.so`s, `.jnilib`s or `.dll`s as necessary. The only tricky thing you need to worry about is to ensure that you get the right swt.jar (meaning for your platform). Try instal...
I have uploaded the win32/64 & osx artifacts of the latest SWT version (4.2.2) to a googlecode repository, you can find it here: <https://swt-repo.googlecode.com/svn/repo/> To use it just put the following in your pom.xml: ``` <repositories> <repository> <id>swt-repo</id> <url>https://swt-repo.go...
How do you build an SWT application with Maven
[ "", "java", "maven-2", "swt", "" ]
A recent [question about string literals](https://stackoverflow.com/questions/372354/string-immutability) in .NET caught my eye. I know that string literals are [interned](http://en.wikipedia.org/wiki/String_intern_pool) so that different strings with the same value refer to the same object. I also know that a string c...
Strings in .NET are reference types, so they are always on the heap (even when they are interned). You can verify this using a debugger such as WinDbg. If you have the class below ``` class SomeType { public void Foo() { string s = "hello world"; Console.WriteLine(s); Console.Write...
In Java (from the [Java Glossary](http://mindprod.com/jgloss/interned.html#UNDERTHEHOOD)): > In Sun’s JVM, the interned Strings (which includes String literals) are stored in a special pool of RAM called the perm gen, where the JVM also loads classes and stores natively compiled code. However, the intered Strings beha...
Where do Java and .NET string literals reside?
[ "", "java", ".net", "string-literals", "string-table", "" ]
I am writing a client-side validation function for [CustomValidator](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx) and I need to check length of entered string. But before, to counteract cheaters a little, I want to remove all leading and trailing spaces from the string. What i...
The easiest way is to call the ValidatorTrim(value) javascript function on your page. This function comes from the javascript that every asp.net validator includes when added to a page. But i don't think its a documented feature, so you cant rely on it being available in future versions of the validators. So i would p...
Forgive me for being obtuse, but are you simply looking for a `trim` function in Javascript? If so, here's what jQuery uses: ``` function trim( text ) { return (text || "").replace( /^\s+|\s+$/g, "" ); } ```
How to trim string in ClientValidationFunction
[ "", "asp.net", "javascript", "validation", "client-side", "" ]