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 (x == null){
throw new ArgumentNullException("someMethod received a null argument!");
}
x.doSomething();
}
```
Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?
Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then? | 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 factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.
If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it. | 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](https://www.jetbrains.com/help/resharper/2016.1/Code_Analysis__Code_Annotations.html).
```
[Pure]
public static object Call([NotNull] Type declaringType,
[NotNull] string methodName,
[CanBeNull] object instance)
{
if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));
if (methodName == null) throw new ArgumentNullException(nameof(methodName));
```
Guard statements have been vastly improved with C# 6 providing the `nameof` operator. | 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 analyse the dependencys of all 600 projects, and allow me to only compile the 11 that are necessary.
In other words given the input of all 600 projects to scan, and BaseLibrary.csproj as a project that has been modified parameter, provide me only the 11 projects I need to compile as output.
I'm experienced in writing custom tasks, I'd just rather use a third party library to do the dependency analysis if there is already one out there.
My company does incremental releases to production every 3-4 months. As an experiment I wrote a custom task that looks at the previous releases "Subversion tag" and evaluates all the compiled files that have changed since then and maps them to a project.
The only use case I can think of that doesn't work is the one I mentioned where a base library is changed and the system doesn't know about all the projects that depend on it. | 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=""
ratio=All
node[width=.25,hight=.375,fontsize=12,color=lightblue2,style=filled]
1 -> 9;
1 -> 11;
9 -> 10;
11 -> 10;
1 [label="Drew.Controls.Map"];
9 [label="Drew.Types"];
10 [label="nunit.framework"];
11 [label="Drew.Util"];
}
```
With the list of projects and this script output, you can create your compilation list. | 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 cuff" (it does lots of graph mapping and dependency tracking).
I should add that it currently works by having a custom marker (xml file) in the root of every project that tracks what needs building; our code promotion process sets the flag, and the build process clears it.
The way it works at the moment is you get to the root that contains all the projects (at any depth), and just type `depends` (with a few switches), and it emits all the project paths that need building, in the right order.
Let me know if it is of interest... | 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 binary:
```
size_t mapLen = ciMap.size();
outFile.write(reinterpret_cast<char*>(&mapLen), sizeof(size_t));
outFile.write(reinterpret_cast<char*>(&ciMap), sizeof(ciMap));
```
And later building with:
```
inFile.read(reinterpret_cast<char*>(&mapLen), sizeof(size_t));
inFile.read(reinterpret_cast<char*>(&ciMap), sizeof(mapLen));
```
Doesn't work, I get string initilization error... something to do with NULL. Any suggestions? If you have better way of storing the bits and values I'd like to hear. | 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. Have a look at it. If you don't want to use it, you can do something like this:
```
typedef std::map<std::string, char> my_map;
my_map ciMap;
// saving
std::ofstream stream("file.txt");
for(my_map::const_iterator it = ciMap.begin(); it != ciMap.end(); ++it) {
stream << it->first << " " << it->second << std::endl;
}
// loading
char c;
std::string bits;
std::ifstream stream("file.txt");
while(stream >> bits >> c)
ciMap.insert(std::make_pair(bits, c));
```
Note that the above needs some changes if the characters stored could be whitespace characters too. Because of that, it's probably the best to first convert to an int before writing out, and then reading as an int when loading. Actually, i recommend boost serialization, and boost iostreams (<http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/index.html>), which includes a compression stream that transparently can compress your data too. | 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 bring them back in you reconstruct the map by reading the items off disk one by one and reinserting them into the map. | 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 J2EE?
My project uses ant for a java project with junit, Swing applications, and J2EE applications. | 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 name. You do not need to implement
> all of these in a single project.
```
all Build and test everything; create a distribution, optionally install.
clean Delete all generated files and directories.
deploy Deploy the code, usually to a remote server.
dist Produce the distributables.
distclean Clean up the distribution files only.
docs Generate all documentation.
init Initialize the build: create directories, call <tstamp> and other common actions.
install Perform a local installation.
javadocs Generate the Javadoc pages.
printerdocs Generate printable documents.
test Run the unit tests.
uninstall Remove a local installation.
```
This page also provides other good guidelines. | 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-Targets.html). | 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 host UDP client on internet?
Is there any other way to do that?
any suggestions? | 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 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 174ms, Maximum = 174ms, Average = 174ms
``` | 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 for exchanging data.
A server can listen on TCP or UDP sockets, with some restrictions. Some port numbers are privileged. Some port numbers are blocked by firewalls.
Port 80, while rarely blocked by firewalls is a privileged port. Generally, you need a web server (e.g., Apache) or privileges to listen on port 80.
"Sending 100 bytes" can be done using a lot of available protocols: Echo, Telnet, FTP, HTTP to name a few. | 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 best way to address the reminder email. Basically, I can think of three approaches:
1. Set up a SQL job that runs every night, kicking off SQL emails to people that have appointments that day.
2. Somehow send the email with a "do not deliver before" flag, although this seems like something I might be inventing.
3. Write *another* application that runs at a certain time every night.
Am I missing something obvious? How can I accomplish this? | 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 on a scheduled basis. The initial message can be flagged with an attribute that means "SEND NOW" - the reminder message can be flagged as "SCHEDULED" - and the sweeper simply needs to send any messages that it finds that are of the "SEND NOW" or that are "SCHEDULED" and have a toBeSentDate >= the current date. Once the message is successfully sent - the unit of work can be concluded by deleting the message from the queue.
This approach ensures messages are not lost - and enables the distribution of load to off-peak hours by adjusting the service polling interval.
As Rob Williams points out - my suggestion of MSMQ is a bit of overkill for this specific question...but it is a viable approach to keep in mind when you start looking at problems of scale - and you want (or need) to minimize/reduce database read/write activity (esepcially during peak processing periods).
Hat tip to Rob. | 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 we have to throw **two** exceptions.
It seems pretty unlikely that we will, though. So what happens and what should the code do here?
```
try { /* init code here */ }
catch (Exception ex)
{
try
{
_DeinitializeEngine();
}
catch (Exception ex2)
{
throw new OCRException("Engine failed to initialize; ALSO failed to deinitialize engine!", ex2);
}
finally
{
throw new OCRException("Engine failed to initialize; failed to initialize license!", ex);
}
}
``` | 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 exception? | 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 illustrate the idea that I explain in all the comments below.
```
static void Main(string[] args)
{
try
{
principalMethod();
}
catch (Exception e)
{
Console.WriteLine("Test : " + e.Message);
}
Console.Read();
}
public static void principalMethod()
{
try
{
throw new Exception("Primary");
}
catch (Exception ex1)
{
try
{
methodThatCanCrash();
}
catch
{
throw new Exception("Cannot deinitialize", ex1);
}
}
}
private static void methodThatCanCrash()
{
throw new NotImplementedException();
}
```
No need to use double throw with finalize. If you put a break point at the Console.WriteLine(...). You will notice that you have all the exception trace. | 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 to connect. If i change the port from 25 to 80 for example it works without problems on any host. So the problem seems to be only the port 25 no matter what host i use, i tried a lot of them and all work for port 80 and others but for 25 fails.
Connections are not blocked form firewall as if i telnet from shell it successfully connects to any port on any host.
Any idea what could be the problem as it's really weird?
LE: If i run the same php script from the shell, php scriptname.php it works so only when i run it by http it fails. I have apache with SuPHP so the problem is around here somewhere | 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 addition to port 25 to help users bypass overly restrictive firewalls. | 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`, etc.
I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.
What would be ideal is to have each scenario listed and the best solution for the same.
For example (just an example of how it should be):
1. for iterating an `array` of 1000+
strings - `for` is better than `foreach`
2. for iterating over `IList` (non generic) strings - `foreach` is better
than `for`
A few references found on the web for the same:
1. [Original grand old article by Emmanuel Schanzer](https://learn.microsoft.com/previous-versions/dotnet/articles/ms973839(v=msdn.10))
2. [CodeProject FOREACH Vs. FOR](https://www.codeproject.com/KB/cs/foreach.aspx)
3. [Blog - To `foreach` or not to `foreach`, that is the question](https://learn.microsoft.com/archive/blogs/kevin_ransom/to-foreach-or-not-to-foreach-that-is-the-question)
4. [ASP.NET forum - NET 1.1 C# `for` vs `foreach`](https://web.archive.org/web/20100123104946/http://weblogs.asp.net/mdavey/archive/2004/02/25/79504.aspx)
[Edit]
Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter. | 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 array is around 2 times cheaper than looping on List.
> * As a consequence, looping on array using for is 5 times cheaper
> than looping on List using foreach
> (which I believe, is what we all do). | 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.Diagnostics;
using System.Linq;
class Test
{
const int Size = 1000000;
const int Iterations = 10000;
static void Main()
{
double[] data = new double[Size];
Random rng = new Random();
for (int i=0; i < data.Length; i++)
{
data[i] = rng.NextDouble();
}
double correctSum = data.Sum();
Stopwatch sw = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
double sum = 0;
for (int j=0; j < data.Length; j++)
{
sum += data[j];
}
if (Math.Abs(sum-correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
double sum = 0;
foreach (double d in data)
{
sum += d;
}
if (Math.Abs(sum-correctSum) > 0.1)
{
Console.WriteLine("Summation failed");
return;
}
}
sw.Stop();
Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
}
}
```
Results:
```
For loop: 16638
Foreach loop: 16529
```
Next, validation that Greg's point about the collection type being important - change the array to a `List<double>` in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still *almost always* prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is. | 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));
```
However, some of my EditDate properties are null. I want these objects with a null EditDate property to show up at the top of my list (i.e. closer to the zero index). How can I do this? | 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 of `EndDate` that you consider as `null`, you could modify the above code to take that into account in a similar fashion to how I've coped with `t1` or `t2` being `null`. | 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 = nBandwidth/8; //Bytes/sec
nBandwidth = nBandwidth/FrameLength;
//Frames/Sec. Frame Length = 1518
UINT FramesPerBurst = (nBandwidth*Sleeptime)/1000;
//Frames/Burst
UINT nBufferSpaceNeededPerFrame = FrameLength-4 + sizeof(dump_bpf_hdr));
UINT nTxBufferSize = FramesPerBurst * nBufferSpaceNeededPerFrame;
unsigned char* pTxBuffer = new
unsigned char[m_nTxBufferSize];
``` | 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 time](http://en.wikipedia.org/wiki/Truncated_binary_exponential_backoff), which quantum is chosen randomly between 0 and 2^<nb collisions> - 1. | 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 real world data transfer rates. | 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 takes 4 times as much time for a 2 times larger number of digits (compare [Multiplication algorithms](http://en.wikipedia.org/wiki/Multiplication_algorithms)). | 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.
The result is that for a relatively small number of digits BigDecimal is OK (half as fast as the others for 1000 digits), but if you use more digits it is way off - JScience is about 4 times faster. But the clear performance winner is Apfloat. The other libraries seem to use naive multiplication algorithms that take time proportional to the square of the number of digits, but the time of Apfloat seems to grow almost linearly. On 10000 digits it was 4 times as fast as JScience, but on 40000 digits it is 16 times as fast as JScience.
On the other hand: JScience provides EXCELLENT functionality for mathematical problems: matrices, vectors, symbolic algorithms, solution of equation systems and what not. So I'll probably go with JScience and later write a wrapper to integrate Apfloat into the algorithms of JScience - due to the good design this seems easily possible.
(UPDATE: I wrote a test suite for the number package of JScience and fixed a number of bugs. This went into release 4.3.1. So I can recommend checking it out.) | 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 here is 5
```
**The particular behavior I'm looking at here is that sup.length changes without any methods being called.** I understand from [this question](https://stackoverflow.com/questions/365975/how-are-javascript-arrays-implemented) that the [] operator is overloaded in the case of arrays, and this accounts for this behavior. Is there a pure-javascript way to duplicate this behavior, or is the language not flexible enough for that?
According to the [Mozilla docs](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array), values returned by regex also do funky things with this index. Is this possible with plain javascript? | 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 = {};
Object.defineProperties(target, {
"length": {
value: 0,
writable: true
},
[Symbol.iterator]: {
// http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype-@@iterator
value: () => {
let index = 0;
return {
next: () => ({
done: index >= target.length,
value: target[index++]
})
};
}
}
});
const isArrayIndex = function(p) {
/* an array index is a property such that
ToString(ToUint32(p)) === p and ToUint(p) !== 2^32 - 1 */
const uint = p >>> 0;
const s = uint + "";
return p === s && uint !== 0xffffffff;
};
const p = new Proxy(target, {
set: function(target, property, value, receiver) {
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array-exotic-objects-defineownproperty-p-desc
if (property === "length") {
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-arraysetlength
const newLen = value >>> 0;
const numberLen = +value;
if (newLen !== numberLen) {
throw RangeError();
}
const oldLen = target.length;
if (newLen >= oldLen) {
target.length = newLen;
return true;
} else {
// this case gets more complex, so it's left as an exercise to the reader
return false; // should be changed when implemented!
}
} else if (isArrayIndex(property)) {
const oldLenDesc = Object.getOwnPropertyDescriptor(target, "length");
const oldLen = oldLenDesc.value;
const index = property >>> 0;
if (index > oldLen && oldLenDesc.writable === false) {
return false;
}
target[property] = value;
if (index > oldLen) {
target.length = index + 1;
}
return true;
} else {
target[property] = value;
return true;
}
}
});
return p;
}
```
I can't guarantee this is actually totally correct, and it doesn't handle the case where you alter length to be smaller than its previous value (the behaviour there is a bit complex to get right; roughly it deletes properties so that the `length` property invariant holds), but it gives a rough outline of how you can implement it. It also doesn't mimic behaviour of [[Call]] and [[Construct]] on `Array`, which is another thing you couldn't do prior to ES6—it wasn't possible to have divergent behaviour between the two within ES code, though none of that is hard.
This implements the `length` property in the same way the spec defines it as working: it intercepts assignments to properties on the object, and alters the `length` property if it is an "array index".
Unlike what one can do with ES5 and getters, this allows one to get `length` in constant time (obviously, this still depends on the underlying property access in the VM being constant time), and the only case in which it provides non-constant time performance is the not implemented case when `newLen - oldLen` properties are deleted (and deletion is slow in most VMs!). | [] 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 solution is to use a method that will work the same as the [] operator.
```
MyClass.prototype.getItem = function(index)
{
return {
name: 'Item' + index,
value: 2 * index
};
}
```
If what you want is have the same behaviour as a native Array in your class, it is always possible to use native Array methods directly on your class. Internally, your class will store data just like a native array does but will keep its class state. jQuery does that to make the jQuery class have an array behaviour while retaining its methods.
```
MyClass.prototype.addItem = function(item)
{
// Will add "item" in "this" as if it was a native array
// it will then be accessible using the [] operator
Array.prototype.push.call(this, item);
}
``` | 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 (' + result + ')
```
Thanks,
Dan | ```
'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 || param2 == 53)
{
throw new ArgumentOutOfRangeException("eek", "param2");
}
}
```
Now, I wonder if there is a way to set up constraints on the parameters and have the compiler already handle that for me? I believe that this is called "Contract" and I remember seeing that Spec# is supposed to do that, but that seems to be an experimental research project at the moment.
So I wonder: Is there anything that can give a clean enforcing of Constraints (at least the simple and often recurring ones like string.IsNullOrEmpty) for input parameters for .net 3.5 SP1 and ideally .net 3.0 already? | 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://msmvps.com/blogs/jon_skeet/archive/2008/11/06/net-4-0-s-game-changing-feature-maybe-contracts.aspx). | 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 to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.
In the prototype I've been creating, I have been storing a "LoginCredentials" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of "how do we track logged in users?" and "how do we authenticate users?" from my controller/business code.
It seems like Spring Security provides a (per-thread) "context" object to be able to access the username/principal info from anywhere in your app...
```
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
```
... which seems very un-Spring like as this object is a (global) singleton, in a way.
My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?
Do I need to wire this up in the initialization method of each test case?
```
protected void setUp() throws Exception {
...
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(testUser.getLogin(), testUser.getPassword()));
...
}
```
This seems overly verbose. Is there an easier way?
The `SecurityContextHolder` object itself seems very un-Spring-like... | 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 an "AuthenticationService" (singleton) and then inject this bean into other services that needed knowledge of the current Principal.
If you are implementing your own authentication service, you could basically do the same thing: create a session-scoped bean with a "principal" property, inject this into your authentication service, have the auth service set the property on successful auth, and then make the auth service available to other beans as you need it.
I wouldn't feel too bad about using SecurityContextHolder. though. I know that it's a static / Singleton and that Spring discourages using such things but their implementation takes care to behave appropriately depending on the environment: session-scoped in a Servlet container, thread-scoped in a JUnit test, etc. The real limiting factor of a Singleton is when it provides an implementation that is inflexible to different environments. | 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 your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
``` | 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 in a nice way?
```
public class IconListBox : FlowLayoutPanel {
private const int ITEM_PADDING = 2;
private const int MAX_IMAGE_SIZE = 64;
List<FlowLayoutPanel> _listItems;
public IconListBox() {
this.SizeChanged += new EventHandler(IconListBox_SizeChanged);
this.AutoScroll = true;
this.HorizontalScroll.Enabled = false;
this.HorizontalScroll.Visible = false;
this.VerticalScroll.Enabled = true;
this.VerticalScroll.Visible = true;
_listItems = new List<FlowLayoutPanel>();
}
void IconListBox_SizeChanged(object sender, EventArgs e) {
//foreach (FlowLayoutPanel item in _listItems) {
// item.Width = this.Width - 10;
//}
}
public void AddItem(string itemText) {
PictureBox pic = new PictureBox();
pic.Image = MyWave.Properties.Resources.mywave_icon;
pic.Width = pic.Height = MAX_IMAGE_SIZE;
pic.SizeMode = PictureBoxSizeMode.Normal;
pic.Enabled = false;
FlowLayoutPanel p = new FlowLayoutPanel();
p.Width = this.Width;
p.Height = pic.Image.Height + (ITEM_PADDING * 4);
p.BackColor = Color.White;
p.Padding = new Padding(ITEM_PADDING);
p.Margin = new Padding(0);
Label l = new Label();
l.Margin = new Padding(10, 5, 0, 0);
l.Width = this.Width - ITEM_PADDING - MAX_IMAGE_SIZE;
l.Height = p.Height - (ITEM_PADDING * 2);
l.Text = itemText;
l.Enabled = false;
//l.BorderStyle = BorderStyle.FixedSingle;
p.Controls.Add(pic);
p.Controls.Add(l);
p.MouseEnter += new EventHandler(p_MouseEnter);
p.MouseLeave += new EventHandler(p_MouseLeave);
p.MouseClick += new MouseEventHandler(p_MouseClick);
this.Controls.Add(p);
_listItems.Add(p);
p.Anchor = AnchorStyles.Right;
}
void p_MouseClick(object sender, MouseEventArgs e) {
//throw new NotImplementedException();
}
void p_MouseLeave(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.White;
}
void p_MouseEnter(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.LightBlue;
}
public void AddItem(string itemText, Image icon) {
}
}
``` | 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 the create a queryset containing them all:
```
Child_1().save()
Child_2().save()
(o1, o2) = Base.objects.all()
```
I want to determine if the object is of type Child\_1 or Child\_2 in basemethod, I can get to the child object via o1.child\_1 and o2.child\_2 but that reconquers knowledge about the childclasses in the baseclass.
I have come up with the following code:
```
def concrete_instance(self):
instance = None
for subclass in self._meta.get_all_related_objects():
acc_name = subclass.get_accessor_name()
try:
instance = self.__getattribute__(acc_name)
return instance
except Exception, e:
pass
```
But it feels brittle and I'm not sure of what happens when if I inherit in more levels. | 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 model instance without additional queries.
This [snippet](http://www.djangosnippets.org/snippets/1031/) shows a common method of adding a ContentType field to the base model:
```
from django.contrib.contenttypes.models import ContentType
class Base(models.Model):
content_type = models.ForeignKey(ContentType,editable=False,null=True)
def save(self):
if(not self.content_type):
self.content_type = ContentType.objects.get_for_model(self.__class__)
self.save_base()
def as_leaf_class(self):
content_type = self.content_type
model = content_type.model_class()
if(model == Base):
return self
return model.objects.get(id=self.id)
```
You can then say `if Base.content_type.model_class()` to determine the type.
[Here](http://www.djangosnippets.org/snippets/1034/) is another snippet that adds a custom manager into the mix.
As you can see, both of these solutions have the potential to be extremely expensive. If you have a large number of instances, using the as\_leaf\_class() method will require one query on each item.
Instead, if you have a known set of child models, simply query each model separately and aggregate the instances into one list. | 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()
# ...
Base.objects.all().select_subclasses() # returns instances of child classes
```
model-utils requires Django 1.2 or higher. | 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 group. I understand that it is not very secure but never the less I would like to know how to do this. In the best way.
It would be nice if the password is remembered for a while once user entered it correctly.
---
I am doing approximately what David Heggie suggested, except without cookies. It does seem insecure as hell, but it is probably better having a bad password protection then none at all.
This is for internal site where people would have hell of a time remembering their login and password and would never go through *sign up* process... unless it is really easy they would not use the system at all.
I wanted to see other solutions to this problem.
With user base consisting of not very tech savvy people what are other ways to do this. | **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 'hello'
$password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';
session_start();
if (!isset($_SESSION['loggedIn'])) {
$_SESSION['loggedIn'] = false;
}
if (isset($_POST['password'])) {
if (sha1($_POST['password']) == $password) {
$_SESSION['loggedIn'] = true;
} else {
die ('Incorrect password');
}
}
if (!$_SESSION['loggedIn']): ?>
<html><head><title>Login</title></head>
<body>
<p>You need to login</p>
<form method="post">
Password: <input type="password" name="password"> <br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
<?php
exit();
endif;
?>
```
Then on each file you want to protect, put at the top:
```
<?php
require('access.php');
?>
secret text
```
It isn't a very nice solution, but it might do what you want
**Edit**
You could add a logout.php page like:
```
<?php
session_start();
$_SESSION['loggedIn'] = false;
?>
You have logged out
``` | 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.parentElement.parentElement.parentElement.style.display = 'none';
This seems to work, with 1 exception. The offending section has a single read-only field, which I assume is the cause. No error is thrown. I've also tried variations with 2 and 4 ".parentElement" blocks.
How can I hide this section? | 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, javascript error)? | 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 in mind is not another JVM; thanks @Dave Ray**
My implementation considerations are typical
* performance
* ease of implementation and maintenance (simplicity?)
* reliability
* flexibility (i.e. can I call from a remote machine, etc.)
Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?
(Stuff people have actually done and can provide real-life feedback on would be great!) | 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 accept connections. When you get a connection read the request and send back a response. Almost every language can use sockets so this is a pretty universal solution. However, you'll have to define your own marshalling scheme, parsing, etc.
**[XML-RPC](http://www.xmlrpc.com/)** : this isn't as hip these days, but it's simple and effective. There are [Java libraries](http://ws.apache.org/xmlrpc/) as well as libraries in most other languages.
**CORBA** : as mentioned above, CORBA is an option, but it's pretty complicated and experts are getting harder to come by.
**Web Server** : set up an embedded web server in your app and handle reqests. I've heard good things about [Jetty](http://www.mortbay.org/jetty/) or you can use the [one provided with Java](http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html). I've used the latter successfully to server KML files to Google Earth from a simulation written in Java. Most other languages have libraries for making HTTP requests. How you encode the data (XML, text, etc) is up to you.
**Web Services** : This would be more complicated I think, but you could use [JAX-WS](https://jax-ws.dev.java.net/) to expose you objects as web services. NetBeans has pretty nice tools for building Web Services, but this may be overkill. | 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 pros are:
* Really easy to implement
* Really easy to call from other JVMs
* Support for remote machines
* jconsole allows you to manually test your MBean without writing a client
Cons:
* Client has to be on a JVM (I think)
* Not great for more complicated data structures and interactions. For example, I don't think an MBean can return a reference to another MBean. It will serialize and return a copy. | 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 not in range(128)
``` | … 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 most straightforward *encoding* of Unicode is UCS-4; every character occupies 4 bytes, and all ~1000000 characters are available. The 4 bytes contain the number of the character in the Unicode tables as a 4-byte integer. Another very useful encoding is UTF-8, which can encode any Unicode character with one to four bytes. But there also are some limited encodings, like "latin1", which include a very limited range of characters, mostly used by Western countries. Such *encodings* use only one byte per character.
Basically, Unicode can be *encoded* with many encodings, and encoded strings can be *decoded* to Unicode. The thing is, Unicode came quite late, so all of us that grew up using an 8-bit *character set* learned too late that all this time we worked with *encoded* strings. The encoding could be ISO8859-1, or windows CP437, or CP850, or, or, or, depending on our system default.
So when, in your source code, you enter the string "add “Monitoring“ to list" (and I think you wanted the string "add “Monitoring” to list", note the second quote), you actually are using a string already *encoded* according to your system's default codepage (by the byte \x93 I assume you use Windows codepage 1252, “Western”). If you want to get Unicode from that, you need to *decode* the string from the "cp1252" encoding.
So, what you meant to do, was:
```
"add \x93Monitoring\x94 to list".decode("cp1252", "ignore")
```
It's unfortunate that Python 2.x includes an `.encode` method for strings too; this is a convenience function for "special" encodings, like the "zip" or "rot13" or "base64" ones, which have nothing to do with Unicode.
Anyway, all you have to remember for your to-and-fro Unicode conversions is:
* a Unicode string gets *encoded* to a Python 2.x string (actually, a sequence of bytes)
* a Python 2.x string gets *decoded* to a Unicode string
In both cases, you need to specify the *encoding* that will be used.
I'm not very clear, I'm sleepy, but I sure hope I help.
PS A humorous side note: Mayans didn't have Unicode; ancient Romans, ancient Greeks, ancient Egyptians didn't too. They all had their own "encodings", and had little to no respect for other cultures. All these civilizations crumbled to dust. Think about it people! Make your apps Unicode-aware, for the good of mankind. :)
PS2 Please don't spoil the previous message by saying "But the Chinese…". If you feel inclined or obligated to do so, though, delay it by thinking that the Unicode BMP is populated mostly by chinese ideograms, ergo Chinese is the basis of Unicode. I can go on inventing outrageous lies, as long as people develop Unicode-aware applications. | 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.
Since I've been coding asp.net since 2000, I haven't really had to deal with the issue at all, since the platform is not scripted.
I may be working on PHP projects in the future, and I was wondering if any code generators for PHP exist, or if any good references for building these generators exist.
It would be for the Linux platform, not targeted to Win2008 Servers running PHP. | 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 generic abstract objects. | 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-usable-ui-the-fastest) that help you do this kind of stuff. | 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_4", typeof(string));
```
later on in my code I am wanting to insert a column between column 2 and column 4.
DataSets have methods for adding a column but I can't seem to find the best way in insert one.
I'd like to write something like the following...
```
...Columns.InsertAfter("column_2", "column_3", typeof(string))
```
The end result should be a data set that has a table with the following columns:
column\_1 column\_2 column\_3 column\_4
rather than:
column\_1 column\_2 column\_4 column\_3 which is what the add method gives me
surely there must be a way of doing something like this.
**Edit**...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:
> I am getting a data set from a stored
> procedure. I am then having to add
> additional columns to the data set
> which is then converted into an Excel
> document. I do not have control over
> the data returned by the stored proc
> so I have to add columns after the
> fact. | 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.Tables[0].Columns.Add("column_4", typeof(string));
ds.Tables[0].Columns.Add("column_3", typeof(string));
//set column 3 to be before column 4
ds.Tables[0].Columns[3].SetOrdinal(2);
``` | 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 ArgumentException(/** snip **/);
columns.Add(newColumn);
//add the new column after the current one
columns[newColumn.ColumnName].SetOrdinal(currentColumn.Ordinal + 1);
}
```
I can now write:
```
dt = ds.Tables[0];
dt.Columns.InsertAfter(dt.Columns["column_2"], new DataColumn("column_3"));
``` | 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've read that there are some serious time-resolution issues between different operating systems (namely that Mac / Linux have an almost 1 ms resolution while Windows has a 50ms resolution??). I'm primarly running my apps on windows and 50ms resolution seems pretty inaccurate.
Are there better options than the two I listed?
Any suggestions / comments? | 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 the Java Documentation:
> ```
> public static long nanoTime()
> ```
>
> Returns the current value of the most precise available system timer, in nanoseconds.
>
> This method can only be used to
> measure elapsed time and is not
> related to any other notion of system
> or wall-clock time. The value returned
> represents nanoseconds since some
> fixed but arbitrary *origin* time (perhaps in
> the future, so values may be
> negative). This method provides
> nanosecond precision, but not
> necessarily nanosecond accuracy. No
> guarantees are made about how
> frequently values change. Differences
> in successive calls that span greater
> than approximately 292 years (263
> nanoseconds) will not accurately
> compute elapsed time due to numerical
> overflow.
For example, to measure how long some code takes to execute:
```
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
```
See also: [JavaDoc System.nanoTime()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--) and [JavaDoc System.currentTimeMillis()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--) for more info. | 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 want to compute the amount of time that has elapsed between two events, like a stopwatch, use `nanoTime()`; changes in the system wall-clock make `currentTimeMillis()` incorrect for this use case. | 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 expected
```
But then in VB.NET...
```
Structure Person
Public name As String
End Structure
...
Dim someone As Person = Nothing 'Wha? this is okay?
```
Is Nothing not the same as null (*Nothing != null - LOL?)*, or is this just different ways of handling the same situation between the two languages?
Why or what is handled differently between the two that makes this okay in one, but not the other?
**[Update]**
Given some of the comments, I messed with this a bit more... it seems as if you actually have to use Nullable if you want to allow something to be null in VB.NET... so for example...
```
'This is false - It is still a person'
Dim someone As Person = Nothing
Dim isSomeoneNull As Boolean = someone.Equals(Nothing) 'false'
'This is true - the result is actually nullable now'
Dim someoneElse As Nullable(Of Person) = Nothing
Dim isSomeoneElseNull As Boolean = someoneElse.Equals(Nothing) 'true'
```
Too weird... | 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 to emulate the `readonly` attribute for a `select` tag, and still get the POST data? | 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() {
$('#formdata_container').show();
$('#formdata').html($(this).serialize());
return false;
});
$('#enableselect').click(function() {
$('#mainform input[name=animal]')
.attr("disabled", true);
$('#animal-select')
.attr('disabled', false)
.attr('name', 'animal');
$('#enableselect').hide();
return false;
});
```
```
#formdata_container {
padding: 10px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id="mainform">
<select id="animal-select" disabled="true">
<option value="cat" selected>Cat</option>
<option value="dog">Dog</option>
<option value="hamster">Hamster</option>
</select>
<input type="hidden" name="animal" value="cat"/>
<button id="enableselect">Enable</button>
<select name="color">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<input type="submit"/>
</form>
</div>
<div id="formdata_container" style="display:none">
<div>Submitted data:</div>
<div id="formdata">
</div>
</div>
``` | 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" documentation, I'd prefer to read them first. Thanks. | 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/16921039/V8-Internals-Building-a-High-Performance-JavaScript-Engine)
* [Chrome V8 - Design Elements](https://developers.google.com/v8/design?hl=it)
About Firefox Javascript Engine (Spidermonkey):
* [Spidermonkey Internals](https://developer.mozilla.org/en-US/docs/SpiderMonkey/Internals)
* [Spidermonkey is on diet](https://blog.mozilla.org/nnethercote/2011/11/01/spidermonkey-is-on-a-diet/)
* [IonMonkey: Mozilla’s new JavaScript JIT compiler](http://www.infoq.com/news/2011/05/ionmonkey)
* [Tracemonkey](http://ejohn.org/blog/tracemonkey/) (obsolete JIT compiler, but however the article is still interesting)
About IE 9+ Javascript Engine (Chakra):
* [Advances in JavaScript Performance in IE10 and Windows 8 - Internals of Chakra](http://blogs.msdn.com/b/ie/archive/2012/06/13/advances-in-javascript-performance-in-ie10-and-windows-8.aspx)
About Safari Javascript engine (SquirrelFish):
* [Announcing SquirrelFish](https://www.webkit.org/blog/189/announcing-squirrelfish/)
* [Introducing SquirrelFish Extreme](https://www.webkit.org/blog/214/introducing-squirrelfish-extreme/)
General overview:
* [JavaScript Engines: Under the Hood](http://ontwik.com/javascript/javascript-engines-under-the-hood/)
* [The Future of JavaScript Engines: Replace Them With JavaScript Compilers](http://www.shorestreet.com/node/43) | 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 else has written. If you're looking for the intellectual challenge, why not have a go at writing one?
I've written a couple, for run time environments that the years have rendered irrelevant.
There are two approaches
* adding something to each function or other significant point that logs the time and where it is.
* having a timer going off regularly and taking a peek where the program currently is.
The JVMPI version seems to be the first kind - the link provided by uzhin shows that it can report on quite a number of things (see section 1.3). What gets executed changes to do this, so the profiling can affect the performance (and if you're profiling what was otherwise a very lightweight but often called function, it can mislead).
If you can get a timer/interrupt telling you where the program counter was at the time of the interrupt, you can use the symbol table/debugging information to work out which function it was in at the time. This provides less information but can be less disruptive. A bit more information can be obtained from walking the call stack to identify callers etc. I've no idea if these is even possible in Java...
Paul. | 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 contain... unusual characters. Specifically, the "section" symbol (§).
If I view the output of the PHP script in a web browser, the symbol appears fine.
But when I read the output of the PHP script into my .NET program, the symbol doesn't appear correctly (it appears as a generic "block" symbol).
I've tried all the different character encoding options that you can use when reading the response stream (from the HttpWebResponse). I've tried outputting the stream directly to a text file (no good), displaying it in a TextBox (no good), and even when viewing the results directly in the Visual Studio debugger, the character appears as a block instead of as the "section" symbol.
I've examined the output in a hex editor (as suggested by a related question, "[how do you troubleshoot character encoding problems](https://stackoverflow.com/questions/29499/how-do-you-troubleshoot-character-encoding-problems)."
When I write out the section symbol (§) from .NET itself, the hex bytes I see representing it are "c2 a7" (makes sense if it's unicode, right? requires two bytes?). When I write out the output from the PHP script directly to a file and examine that with a hex editor, the symbol shows up as "ef bf bd" - three bytes instead of two?
I'm at a loss as to what to do - if I need to specify some other character encoding, or if I'm missing something obvious about this.
Here's the code that's used to get the output of the PHP script (VB-style comments modified so they appear correctly on this site):
```
Dim myRequest As HttpWebRequest = WebRequest.Create("http://www.example.com/sample.php")
Dim myResponse As HttpWebResponse = myRequest.GetResponse()
// read the response stream
Dim myReader As New StreamReader(myResponse.GetResponseStream())
// read the entire output in one block (just as an example)
Dim theOutput as String = myReader.ReadToEnd()
```
Any ideas?
* Am I using the wrong kind of StreamReader? (I've tried passing the character encoding in the call to create the new StreamReader - I've tried all the ones that are in System.Text.Encoding - UTF-8, UTF-7, ASCII, UTF-32, Unicode, etc.)
* Should I be using a different method for reading the output of the PHP script?
* Is there something I should be doing different on the PHP-side when outputting the text?
**UPDATED INFO:**
* The output from PHP is specifically encoded UTF-8 by calling: `utf8_encode($file);`
* When I wrote out the symbol from .NET, I copied and pasted the symbol from the Character Map app in Windows. I also copied & pasted it directly from the file's name (in Windows) and from this web page itself - all gave the same hex value when written out (c2 a7).
* Yes, the "section symbol" I'm talking about is U+00A7 (ALT+0167 on Windows, according to Character Map).
* The content-type is set explicitly via `header('Content-Type: text/html; charset=utf-8');` right at the beginning of the PHP script.
**UPDATE:**
Figured it out myself, but I couldn't have done it without the help from the people who answered. Thank you! | **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 wrapped in a `utf8_encode()` call. This caused the entire page to be output in ISO-8859-1 instead of UTF-8.
I noticed this when I checked my testing script's "encoding" property (in Firefox, "View Page Info"). It was UTF-8 for the testing script, but ISO-8859-1. The production script also printed the date of the file; this was not wrapped in a call to utf8\_encode - and that caused the entire output to change to ISO-08859-1.
[Insert sound of me slapping my forehead here]
Thanks to everyone who answered! You were very helpful! | 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) - is that the one you mean? I've no idea why PHP would represent that as "ef bf bd" though.
Using a StreamReader should be fine, but you'll need to know the correct encoding.
EDIT: Okay, so it's *meant* to be UTF-8, and certainly isn't - so the problem is on the PHP side. If you run `utf8_encode($file)` and then print out the bytes of the result explicitly (without the web server getting in the way) what happens? I'm really surprised that a browser is managing to get the right symbol though... is this just plain HTML? Are you sure that all of "ef bf bd" is just the section symbol?
Is this web server public anywhere? If I could point my browser at it, I *might* be able to work out what's going on. | 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 on what's wrong . I am using Visual Studio 2005 Professional Edition . | 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 algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.
Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both. | 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, we will need to only store two items from the original list per bin, and thus can represent the split with a single percentage.
Let's us take the example of five equally weighted choices, `(a:1, b:1, c:1, d:1, e:1)`
To create the alias lookup:
1. Normalize the weights such that they sum to `1.0`. `(a:0.2 b:0.2 c:0.2 d:0.2 e:0.2)` This is the probability of choosing each weight.
2. Find the smallest power of 2 greater than or equal to the number of variables, and create this number of partitions, `|p|`. Each partition represents a probability mass of `1/|p|`. In this case, we create `8` partitions, each able to contain `0.125`.
3. Take the variable with the least remaining weight, and place as much of it's mass as possible in an empty partition. In this example, we see that `a` fills the first partition. `(p1{a|null,1.0},p2,p3,p4,p5,p6,p7,p8)` with `(a:0.075, b:0.2 c:0.2 d:0.2 e:0.2)`
4. If the partition is not filled, take the variable with the most weight, and fill the partition with that variable.
Repeat steps 3 and 4, until none of the weight from the original partition need be assigned to the list.
For example, if we run another iteration of 3 and 4, we see
`(p1{a|null,1.0},p2{a|b,0.6},p3,p4,p5,p6,p7,p8)` with `(a:0, b:0.15 c:0.2 d:0.2 e:0.2)` left to be assigned
At runtime:
1. Get a `U(0,1)` random number, say binary `0.001100000`
2. bitshift it `lg2(p)`, finding the index partition. Thus, we shift it by `3`, yielding `001.1`, or position 1, and thus partition 2.
3. If the partition is split, use the decimal portion of the shifted random number to decide the split. In this case, the value is `0.5`, and `0.5 < 0.6`, so return `a`.
[Here is some code and another explanation](http://prxq.wordpress.com/2006/04/17/the-alias-method/), but unfortunately it doesn't use the bitshifting technique, nor have I actually verified it. | 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:
```
import heapq
import math
import random
def WeightedSelectionWithoutReplacement(weights, m):
elt = [(math.log(random.random()) / weights[i], i) for i in range(len(weights))]
return [x[1] for x in heapq.nlargest(m, elt)]
```
This is very similar in structure to the first approach proposed by Nick Johnson. Unfortunately, that approach is biased in selecting the elements (see the comments on the method). Efraimidis and Spirakis proved that their approach is equivalent to random sampling without replacement in the linked paper. | 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 to get the id field value, but I don't think there is an equivalent for an update?
I know I can use a scrollable resultset to do what I want
i.e.
```
stmt = conn.prepareStatement("select top 1 myCol, itemId from myTable", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = stmt.executeQuery();
if(resultSet.first()){
resultSet.updateString(1, "foo");
resultSet.updateRow();
String theItemId = resultSet.getString(1)
}
resultSet.close();
```
but I'm concerned about performance as testing shows lock timeouts under load and I was wondering if there was a better/simpler way?
-- EDIT:
Just to finalise this issue...
When we migrate to MSSQL2005 we will upgrade our code to use Rich's answer.
In the current release we have used the lock hints: (UPDLOCK ROWLOCK READPAST) to mitigate the performance problems our original code showed. | 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 KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
-- An insert which will return the identity
INSERT INTO [dbo].[TEST_TABLE] ([name])
OUTPUT inserted.id
VALUES('Test 1')
-- Another insert which will return the identity
INSERT INTO [dbo].[TEST_TABLE] ([name])
OUTPUT inserted.id
VALUES('Test 2')
-- Now an update which will return the identity
UPDATE [dbo].[TEST_TABLE]
SET [name] = 'Updated Test 1'
OUTPUT inserted.id
WHERE [name] = 'Test 1'
SELECT id, [name] FROM [dbo].[TEST_TABLE]
```
And more specifically to your query...
```
update myTable
set myCol = 'foo'
output inserted.itemid
where itemId in (select top 1 itemId from myTable )
``` | 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 not need to be cryptographically safe. | 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 bits
This is impossible, proof:
If it was possible, I could generate a GUID G1 and you could generate another GUID G2. Since we both ignore the standard and use the same reserved prefix, and my personal scheme for the other bits is outside your control, my GUID G1 can clash with your GUID G2. The non-collision propery of GUIDs follows from sticking to the GUID standard.
The mechanisms to prevent collisions are indeed inherently privacy-sensitive. If I generate at random a GUID G1, I can guarantee that random GUID is unique if two conditions are satisfied:
* 1 It's a member of the subset of GUIDs under my control and
* 2 I didn't generate the GUID before.
For GUIDs outside the subset under your control, you cannot guarantee (2). But how do you assign non-overlapping subsets of GUIDs to a single person? Using the MAC of a NIC is a simple, effective way. Other means are also possible. But in any case, the mere existence of such a subset is privacy-implicating. It's got to belong to someone, and I must be able to determine whether that's me or someone else. It's a bit harder to prove whether two random GUIDs G1 and G2 belong to the same subset (ie. person) but the current schemes (which you object to) do not try to hide that. | 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.faqs.org/rfcs/rfc4122.html), the GUID format breaks down to:
```
UUID = time-low "-" time-mid "-"
time-high-and-version "-"
clock-seq-and-reserved
clock-seq-low "-" node
time-low = 4hexOctet
time-mid = 2hexOctet
time-high-and-version = 2hexOctet
clock-seq-and-reserved = hexOctet
clock-seq-low = hexOctet
node = 6hexOctet
hexOctet = hexDigit hexDigit
hexDigit =
"0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" /
"a" / "b" / "c" / "d" / "e" / "f" /
"A" / "B" / "C" / "D" / "E" / "F"
```
The only static data in there is version (4 bits) and reserved/variant (2-3 bits). I don't see that they allowed for any "user specified" versions, but I'd say you'll be safe for the foreseeable future if you use 1111 as your version identifier. The existing versions are in section 4.1.3, but only 5 have been defined so far...that gives you 11 more revisions before collision.
So, if you can live with 6 or 7 bits of distinctness, a combination of [Guid.NewGuid().ToByteArray()](http://msdn.microsoft.com/en-us/library/system.guid.tobytearray.aspx) and creating a [new Guid](http://msdn.microsoft.com/en-us/library/system.guid.guid.aspx) after your bit fiddling should get you there. | 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 (scrollableHeight > visibleHeight) {
var checkbox = document.getElementById("agreebox");
checkbox.checked=false;
checkbox.disabled=true;
agreement.onscroll = handleScroll;
}
}
function handleScroll() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
var position = agreement.scrollTop;
if (position + visibleHeight == scrollableHeight) {
document.getElementById("agreebox").disabled=false;
}
}
</script>
</head>
<body>
<form>
<textarea id="agreetext" rows="8" cols="40">Long agreement</textarea>
<br/><br/>
<input type="checkbox" id="agreebox" value="true"/> <label id="agreelabel" for="agreebox">I agree</label>
<br/><br/>
<input type="submit" value="Continue"/>
</form>
<script type="text/javascript">
// We put this at the end of the page rather than in an document.onload
// because the document.onload event doesn't fire until all images have loaded.
setupPage();
</script>
</body>
</html>
``` | 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 (scrollableHeight > visibleHeight) {
var checkbox = document.getElementById("agreebox");
checkbox.checked=false;
checkbox.disabled=true;
document.getElementById("agreelabel").style.color = "#777";
agreement.onscroll = handleScroll;
}
}
function handleScroll() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
var position = agreement.scrollTop;
if (position + visibleHeight == scrollableHeight) {
document.getElementById("agreebox").disabled=false;
document.getElementById("agreelabel").style.color = "black";
}
}
``` | 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 against which the regular expression was matched.
>
> index: A read-only property that is the zero-based index of the match in the string.
etc... is it possible to create your own object in JavaScript which will have read-only properties, or is this a privilege reserved to built-in types implemented by particular browsers? | **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 support "older" browsers, you could use one of the methods in this answer as a fallback.
---
In Firefox, Opera 9.5+, and Safari 3+, Chrome and IE (tested with v11) you can define getter and setter properties. If you only define a getter, it effectively creates a read-only property. You can define them in an object literal or by calling a method on an object.
```
var myObject = {
get readOnlyProperty() { return 42; }
};
alert(myObject.readOnlyProperty); // 42
myObject.readOnlyProperty = 5; // Assignment is allowed, but doesn't do anything
alert(myObject.readOnlyProperty); // 42
```
If you already have an object, you can call `__defineGetter__` and `__defineSetter__`:
```
var myObject = {};
myObject.__defineGetter__("readOnlyProperty", function() { return 42; });
```
Of course, this isn't really useful on the web because it doesn't work in Internet Explorer.
You can read more about it from [John Resig's blog](http://ejohn.org/blog/javascript-getters-and-setters/) or the [Mozilla Developer Center](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters). | 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 an exception.
Example from [ejohn.org](https://web.archive.org/web/20170330213334/http://ejohn.org/blog/ecmascript-5-objects-and-properties/):
```
var obj = {};
Object.defineProperty( obj, "<yourPropertyNameHere>", {
value: "<yourPropertyValueHere>",
writable: false,
enumerable: true,
configurable: true
});
``` | 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).
And one more thing, which memcached client that is good to use with c# and .net 3.5 ?
I've found many alternate such as [Memcached Providers @ Codeplex](http://www.codeplex.com/memcachedproviders), [Beitmemcached](http://code.google.com/p/beitmemcached/), and [memcached provider @ Sourceforge](http://sourceforge.net/projects/memcacheddotnet) | 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 licenses for all those boxes. Linux will offer you all the OSS benefits. TCO will rise linearly with memcached on Windows
**Edit:**
It’s been around 1.5 years since I wrote this answer and lot of things have changed since. You’ve to take notice, especially when someone like Dustin comments.
So here’s how you can get memcached on windows running. [Download memcached for windows from Couchbase (formerly Northscale)](http://blog.couchbase.com/memcached-144-windows-32-bit-binary-now-available).
Typically if you plan to run memcached on the same production machine you’d want to start it in limited memory, i.e. define the maximum memory memcached is allowed to use.
> c:\Program
> Files\memcached>memcached.exe -m 128.
*Here memcached runs with a maximum of 128 mb usage. You don’t want memcached to take up all the memory on your webserver.*
The moment you decided to [scale out](http://en.wikipedia.org/wiki/Scale_out#Scale_horizontally_.28scale_out.29) memcached you’ll need to consider what I said earlier. Additionally compress your values in the key value combinations. Web servers typically consume very little CPU (2-3%) usage and compression brings in a lot of value to network throughout in comparison to the CPU usage. If you are too concerned about normal compression, try [LZO](http://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Oberhumer) | 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 an officially supported platform, it runs perfectly under windows with all tests passing. I have windows builds (using Cygwin) available here:
<https://github.com/ServiceStack/ServiceStack.Redis#redis-server-builds-for-windows>
It also has client bindings for nearly every programming language in use today. I maintain a rich Open Source C# Redis client with native API support for any C# POCO type, transaction support and Thread-safe client managers that are ready to be dropped into any IOC at:
<https://github.com/ServiceStack/ServiceStack.Redis> | 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 input for each key/value pair.
I am wondering, **is there a way to get an array of posted data via the CodeIgniter api?**
Thanks! | 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 into the laziness: I have a nasty feeling that this small script I'm writing will grow over time and would *like* to create a proper testing environment, but given that it might *not* grow over time, I don't want to do much work to get the mock server running. | 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: ImapProtocol(mailbox_map), 'localhost', 1143)
server = loop.run_until_complete(factory)
```
The mailbox\_map is a map of map : email -> map of mailboxes -> set of messages. So all the messages/mailboxes are in memory.
Each time a client connects, a new instance of ImapProtocol is created.
Then, the ImapProtocol executes and answers for each client, implementing capability/login/fetch/select/search/store :
```
class ImapHandler(object):
def __init__(self, mailbox_map):
self.mailbox_map = mailbox_map
self.user_login = None
# ...
def connection_made(self, transport):
self.transport = transport
transport.write('* OK IMAP4rev1 MockIMAP Server ready\r\n'.encode())
def data_received(self, data):
command_array = data.decode().rstrip().split()
tag = command_array[0]
self.by_uid = False
self.exec_command(tag, command_array[1:])
def connection_lost(self, error):
if error:
log.error(error)
else:
log.debug('closing')
self.transport.close()
super().connection_lost(error)
def exec_command(self, tag, command_array):
command = command_array[0].lower()
if not hasattr(self, command):
return self.error(tag, 'Command "%s" not implemented' % command)
getattr(self, command)(tag, *command_array[1:])
def capability(self, tag, *args):
# code for it...
def login(self, tag, *args):
# code for it...
```
Then in my tests, I start the server during setup with :
```
self.loop = asyncio.get_event_loop()
self.server = self.loop.run_until_complete(self.loop.create_server(create_imap_protocol, 'localhost', 12345))
```
When I want to simulate a new message :
```
imap_receive(Mail(to='dest@fakemail.org', mail_from='exp@pouet.com', subject='hello'))
```
And stop it at teardown :
```
self.server.close()
asyncio.wait_for(self.server.wait_closed(), 1)
```
cf <https://github.com/bamthomas/aioimaplib/blob/master/aioimaplib/tests/imapserver.py>
---
***EDIT***: I had a buggy stop of the server, I rewrote it with asyncio.Protocol and modify the answer to reflect the changes | 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("HKLM\Foo\Bar\Baz");
// registryKey might be null!
if (registryKey == null)
{
// What exception to throw?
throw new ???Exception("Could not load settings from HKLM\foo\bar\baz.");
}
``` | 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 exception that is thrown when one
> of the arguments provided to a method
> is not valid.
...
**IMO writing a proper exception message is more important.** | 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 == null)
{
throw new KeyNotFoundException("Could not load settings from HKLM\foo\bar\baz.");
}
```
Also, instead of inheriting from `Exception` you could inherit from `ApplicationException`. This depends on the kind of failure you want your application to have in this situation. | 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 is the stringstream approach I have used in the past:
```
std::string intToString(int i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
```
Of course, this could be rewritten as so:
```
template<class T>
std::string t_to_string(T i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
```
However, I have the notion that this is a fairly 'heavy-weight' implementation.
Zan noted that the invocation is pretty nice, however:
```
std::string s = t_to_string(my_integer);
```
At any rate, a nicer way would be... nice.
> ### Related:
>
> [Alternative to itoa() for converting integer to string C++?](https://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c) | 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_cast &){
...
}
``` | 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 obtain a similar behavior in Python in a concise way? | 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 server? How would I do this? | 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 three word name such as **Don Juan DiMarco**? If you decide to split the name based on whitespace, you'll have to determine how to assign the first and last names.
```
$arrNames = preg_split('/\s+/', $_POST['name']);
```
The above will give you (in PHP) an array of values split by white space. Running that on the string **Don Juan DiMarco** would give you an array like:
```
Array([0] => "Don", [1] => "Juan", [2] => "DiMarco")
```
From there you have to determine which ones are the first name, and which are a middle, and which are a last name. It gets even harder if you have 4 or 5 names entered, which is entirely realistic for certain cultures. All of this is guesswork, which is why I would recommend simply adding a Last Name input field on the front-end. This would eliminate all guess work as to which name is the first name and which is the last name. | 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 massaging and data validation there.
Javascript should only be used to enhance the UI experience, not perform import data manipulation, it can be both a security hole and a point of failure if use Javascript for these important tasks.
Also, when manipulating names, keep in mind all the different kinds of formats you will get, such as:
```
John Smith Jr
Dr John Smith
John Smith Esq.
John Smith IV
John A Smith
```
So be careful, massaging names is very messy business and the public will enter whatever they want, at the very least, add a small label and ask them to only enter "first and last name" and pray for the best. | 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 mouseBall to a new ball when the user clicks the mouse. The user can then drag the mouse around and the ball will follow where the mouse goes. When the user releases the ball I have another mouse event that sets mouseBall = null.
The problem is, my render loop is running fast enough that at random times the conditional (mouseBall != null) will return true, but in that split second after that point the user will let go of the mouse and I'll get a nullpointer exception for attempting .draw() on a null object.
What is the solution to a problem like this? | 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) tmpBall.draw();
}
``` | 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 alpha characters was a variable name.
Was that the right answer? Are there any more reasons?
```
string 2BeOrNot2Be = "that is the question"; // Why won't this compile?
``` | 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.category
select new
{
category = p.category,
subcategories = (
from p2 in sr.products
where p2.category == p.category
select p2.subcategory).Distinct()
}).Distinct();
```
sr.products looks like this
```
category subcategory
----------------------
cat1 subcat1
cat1 subcat2
cat2 subcat3
cat2 subcat3
```
what i get in results is
```
cat1, [subcat1,subcat2]
cat1, [subcat1,subcat2]
```
but i only want one entry
solved my problem with this code:
```
var rootcategories2 = (from p in sr.products
group p.subcategory by p.category into subcats
select subcats);
```
now maybe it is time to think of what was the right question.. (-: | 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 = (from p in products
where p.category == c
select p.subcategory).Distinct()
};
``` | 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 way for the sake of clarity in complex queries where other factors are driving the performance. | 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 button click, reload order query. Or should this go through the model layer at all?
Any example code would be great! | 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 wanted the same functionality).
Model - Wrap access to data in models. In my apps, all SQL lives in the Model layer, no direct data access is allowed in the Views or Controllers. As Elie points out in another answer, the idea here is to (at least partially) insulate your Controllers/Views from changes in database structure. Models are also a good place to implement logic such as updating a "last modified" date whenever a field changes. If a major data source for your application is an external web service, consider whether wrapping that in a model class.
Controllers - Used to glue Models and Views together. Implement application logic here, validate forms, transfer data from models to views, etc.
For example, in my apps, when a page is requested, the controller will fetch whatever data is required from the models, and pass it to a view to generate the page the user sees. If that page was a form, the form may then be submitted, the controller handles validation, creates the necessary model and uses it to save the data.
If you follow this method, Models end up being quite generic and reusable. Your controllers are of a manageable size and complexity because data access and display has been removed to Models and Views respectively, and your views should be simple enough that a designer (with a little training) could comprehend them. | 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 represents the Business Objects (without any knowledge of HOW to access their data).
This will allow you to test the components of your system more easily, as it supports mocking. | 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 `lengthOfByTagName()` function returns `0` in IE but `1` in Firefox.
Is there something I am doing wrong?
```
<html>
<head>
<title>IE doesn't see Object element?</title>
<script type="text/javascript">
function byId()
{
var video = document.getElementById("VideoPlayer");
alert(video);
}
function lengthOfByTagName()
{
var length = document.getElementsByTagName("object").length;
alert(length);
}
</script>
</head>
<body>
<object type="" id="VideoPlayer">
<param name="allowScriptAcess" value="always" />
<param name="allowfullscreen" value="true" />
VideoPlayer element
</object>
<br>
<br>
<a href="#" onclick="javascript:byId()">getElementById("VideoPlayer")</a>
<br>
<a href="#" onclick="javascript:lengthOfByTagName()">getElementsByTagName("object").length</a>
</body>
</html>
``` | 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" />
<param name="allowfullscreen" value="true" />
</object>
```
It will work as expected. | 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/25/2008 3:14:10 PM ID: 1023
.NET Runtime version 2.0.50727.1433 - Fatal Execution Engine Error (79FFEE24) (80131506)
I could not find any useful information on the MS sites. Does anybody have an idea where I should start my investigation?
tia | 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 people even claimed it was the antivirus (!)
YMMV, good luck. | 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-type/>
Seems to be ideal piece of code for starting downloading in JavaScript. | 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="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
```
The file 'download.php' (needs to be put on your server) simply contains:
```
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
```
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc. | 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:
* [Aspyct](http://www.aspyct.org)
* [Lightweight AOP for Python](http://www.cs.tut.fi/~ask/aspects/aspects.html)
### Edit 2
In which context will I use these?
I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack. | 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/pytilities/) ([Documentation](http://pytilities.sourceforge.net/doc/1.2.0/); [svn repo](https://sourceforge.net/p/pytilities/code/HEAD/tree/)). It is currently the most powerful (as far as I know).
Its features are:
* make reusable Aspect classes
* apply multiple aspects to an instance or class
* unapply aspects to an instance/class
* add new attributes to an instance by using an aspect
* apply advice to all attributes of an instance/class
* ...
It also has other goodies such as some special descriptors (see the documentation) | 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 syntactically.
Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't.
Here's an example for a simple caching decorator (I wrote it for [this question](https://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean#287616)):
```
import pickle, functools
def cache(f):
_cache = {}
def wrapper(*args, **kwargs):
key = pickle.dumps((args, kwargs))
if key not in _cache:
_cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache
return _cache[key] # read value from cache
functools.update_wrapper(wrapper, f) # update wrapper's metadata
return wrapper
import time
@cache
def foo(n):
time.sleep(2)
return n*2
foo(10) # first call with parameter 10, sleeps
foo(10) # returns immediately
``` | 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 the complexity of a hash lookup vs. a binary tree, I mean more like analytical problems, such as "imagine there are 4 bumble bees, each buzzing bla bla bla."
Now personally I prefer to keep phone screens a little more concrete, and leave the abstract questions for the white board. So when conducting c++ phone interviews, what kind of topics do you cover, especially for Sr. developers?
I know there is another thread similar to this, but frankly it seems to completely have missed the point that this is about phone screens, not interviews that are face to face. Plus this is more c++ specific. | 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 that we close our sockets properly? Of course the proper answer would be to wrap it in a RAII object, but don't ask them that directly (it's easy to google "RAII", while the above question "how would you ensure resources get released properly" actually shows you whether or not they know the appropriate techniques. If they answer "wrap everything in try/catch", they might have a problem. And this ties in nicely with questions about the differences between heap and stack.
You might be able to come up with some simple question about exception safety too, which doesn't require any real code. In general, I'd say a discussion of all the various C++ idioms might be a good idea, because many of them don't require much actual code, but are still vital language-specific concepts.
See if they know about smart pointers (again preferably by giving them a situation where smart pointers are called for, and see how they would solve the problem), and maybe templates/metaprogrammin (in the latter case, probably just find out if they're aware that it's possible ,rather than requiring them to code actual metaprograms on the phone)
You might also want to ask about some common areas of undefined behavior (what are the values of a and b after executing `a = b++ + b++?`?), or allocate an array of 10 elements, and add 10 or 11 to the array pointer, and ask what the result is in each case (+=10 is legal, gives you a past-the-end pointer, +=11 is undefined). Or give them a scenario where they need to copy a lot of objects, and ask how they'd do that (plain for-loop copying each element at a time, memcpy or std::copy are obvious answers. Note the caveats with memcpy, that it's not safe for non-POD objects)
Or ask about their coding style in general. How do they feel about iterators? Do they prefer plain old for-loops? Do they know how to use std::for\_each or std::transform?
*Edit:*
Seems the `a = b++ + b++` (the answer is undefined behavior, btw) suggestion in particular generated a lot of comments. Perhaps people read too much into it. As the OP said he preferred to ask *concrete* (not abstract, and easy to explain/answer/discuss over the phone) questions, that'd reveal a bit about the interviewee's C++ skills, and this is a simple (and yes, perhaps nitpicky) example of that. The reasoning behind it is that 1) it has an intuitive meaning, which is wrong, and 2) you have to have a certain level of experience with C++ before you realize this. And of course 3), it's short and easy to ask over the phone. It doesn't require anyone to write code down. No, it won't reveal whether the candidate is a "great programmer", but as I understood the question, that wasn't the goal either. If someone gets it wrong, it doesn't mean much at all, but if they get it right, you can be fairly sure that they know a bit of C++. But if you read my answer again, you'll see that it was just a quick example of a category of questions I thought should be represented. C++ is full of undefined behavior, even in code that looks completely harmless and intuitive. Asking the candidate to recognize *some* instance of this may be useful, whether it's the "modify the same variable twice in the same expression" example above, or something different. | 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 this one could be quite illuminating!
The "you really need to interview me" answer to the last question would cover
* allocation - limits, use-cases, failure modes, efficiency, resource cleanup, destructors
* stack call-frames - what happens when a function is called, parameters, backtraces | 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 file is that I have to parse. Since I know exactly all of the content of the HTML files that I am going to have to work with, this HTML snippet pretty much covers my entire use case. If I can get a regex to extract the body of this example, I'll be happy.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
</head>
<body contenteditable="true">
<p>
Example paragraph content
</p>
<p>
</p>
<p>
<br />
</p>
<h1>Header 1</h1>
</body>
</html>
```
Conceptually, I've been trying to build a regex string that matches everything BUT the inner body content. With this, I would use the C# `Regex.Split()` method to obtain the body content. I thought this regex:
```
((.|\n)*<body (.)*>)|((</body>(*|\n)*)
```
...would do the trick, but it doesn't seem to work at all with my test content in RegexBuddy. | 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 negative look-ahead... This should also work (for a well-formed xhtml document):
```
(.*<\s*body[^>]*>)|(<\s*/\s*body\s*\>.+)
``` | 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 parser is too slow.
There are two kinds of XML parser, one called DOM is big and heavy and easy and friendly, it builds a tree out of the document before you can do anything. The other is called SAX and is fast and light and more work, it reads the file sequentially. You will want SAX to find the Body tag.
The DOM method is good for multiple uses, pulling tags and finding who is what's child. The SAX parser reads across the file in order and qill quickly get the information you are after. The Regex won't be any faster than a SAX parser, because they both simply walk across the file and pattern match, with the exception that the regex won't quit looking after it has found a body tag, because regex has no built in knowledge of XML. In fact, your SAX parser probably uses small pieces of regex to find each tag. | 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 ZipEntry(filename);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
zos.close();
return baos.toByteArray();
}
``` | 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, byte[]> reporte : mapReporte.entrySet()) {
ZipEntry entry = new ZipEntry(reporte.getKey() + extension);
entry.setSize(reporte.getValue().length);
zos.putNextEntry(entry);
zos.write(reporte.getValue());
}
zos.closeEntry();
zos.close();
return baos.toByteArray();
}
``` | 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 an online image gallery.
Any ideas?
Below is the code:
```
ini_set("memory_limit","30M");
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);
$imagepath = $imagename;
//below here for the removed code
$save = "thumbs/uploads/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file
$imagesize = getimagesize($file);
list($width, $height) = $imagesize;
unset($imagesize);
if($width>$height)
{
$modwidth = 150;
$diff = $width / $modwidth;
$modheight = $height / $diff;
}else{
$modheight = 150;
$diff = $height / $modheight;
$modwidth = $width / $diff;
}
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
$imagecopy = imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagedestroy($image);
imagedestroy($im);
imagedestroy($imagecopy);
imagedestroy($source);
$imagejpg = imagejpeg($tn, $save, 100);
imagedestroy($tn);
imagedestroy($imagejpg);
```
---
EDIT
This has now been sorted out hopefully. One of my colleagues had a solution all along but neglected to tell me! | 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 or some other program. It depends a bit on what you're trying to accomplish. | 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, for example, imagecreatetruecolour() will use up 1024\*768\*4 = 3145728 bytes, or around 3MB.
The problem is that this scales up quite dramatically. A 3072x2034 (6 megapixel) image, by the same sort of calculation, needs around 24MB just to be loaded into memory - I would guess this is the sort of size you're dealing with.
The solution is to hand off the processing to something else like imagemagick or NetPBM that will run as a separate process and not count towards the PHP memory limit.
[NetPBM](http://netpbm.sourceforge.net/) is my personal favourite and would look something like:
```
anytopnm <file> | pnmscale -xysize <dimensions> | pnmtojpg > <outfile>
``` | 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 haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.
Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.
Am I missing something simple?
Thanks. | 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 `HTTPRedirectHandler` to capture information that you'll then check as part of your unit testing.
```
cookie_handler= urllib2.HTTPCookieProcessor( self.cookies )
redirect_handler= HTTPRedirectHandler()
opener = urllib2.build_opener(redirect_handler,cookie_handler)
```
You can then use this `opener` object to POST and GET, handling redirects and cookies properly.
You may want to add your own subclass of `HTTPHandler` to capture and log various error codes, also. | 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._opener = urllib2.build_opener(redirect_handler, cookie_handler)
def GET(self, url):
return self._opener.open(url).read()
def POST(self, url, parameters):
return self._opener.open(url, urllib.urlencode(parameters)).read()
if __name__ == "__main__":
bot = HttpBot()
ignored_html = bot.POST('https://example.com/authenticator', {'passwd':'foo'})
print bot.GET('https://example.com/interesting/content')
ignored_html = bot.POST('https://example.com/deauthenticator',{})
``` | 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**: the xml files are served as is from the server, so I need a client side solution
**Note**: the main problem is XML doesn't render correctly in most browsers, all the brackets and attributes disappear, leaving you with text that doesn't look like xml | 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`.
But, if you truely need to see it in a DIV you will have to build yourself an `XML` rendering function `XML2HTML`. You can use the `HTML` [`PRE`](http://www.w3schools.com/TAGS/tag_pre.asp) tag for that, if your `XML` string is already formatted (line breaks and tabs). In that case you will have to replace `<` to `>` in the `XML` string.
**Conclusion:** `The browser` can't render `XML` and `HTML` in the same document. If you need it, you just have to workaround it. | 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 *traditionally* not been a good idea to have more than a few hundred files in a directory. File systems have improved at this in general, but I don't know what the current state is with NTFS and Fat32. | 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
and
```
LARGE_INTEGER i1, i2;
QueryPerformanceCounter(&i1);
intcount = QDir("c:/windows/system32").entryList(QDir::Files).count();
QueryPerformanceCounter(&i2);
__int64 result += i2.QuadPart - i1.QuadPart;
```
Result is about 2.100.000.000
Files count is 2125 | 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>();
Double[] d = f.getA();
```
You will get a `CastClassException` with the message `java.lang.Object` cannot be cast to `java.lang.Double`.
Can anyone tell me why? My understanding of `ClassCastException` is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:
```
Object o = new Double(3.);
Double d = (Double) o; // Working cast
String s = (String) o; // ClassCastException
```
And it seems I can do this. If `a` was just a `T` instead of an array `T[]`, we can get `a` and cast it without a problem. Why do arrays break this?
Thanks. | ```
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];
```
You cannot cast from Object to Double, hence the ClassCastException.
**Update and Clarification:** Actually, after running some test code, the ClassCastException is more subtle than this. For example, this main method will work fine without any exception:
```
public static void main(String[] args) {
Foo<Double> f = new Foo<Double>();
System.out.println(f.getA());
}
```
The problem occurs when you attempt to assign `f.getA()` to a reference of type `Double[]`:
```
public static void main(String[] args) {
Foo<Double> f = new Foo<Double>();
Double[] a2 = f.getA(); // throws ClassCastException
System.out.println(a2);
}
```
This is because the type-information about the member variable `a` is erased at runtime. Generics only provide type-safety at *compile-time* (I was somehow ignoring this in my initial post). So the problem is not
```
private T[] a = (T[]) new Object[5];
```
because at run-time this code is really
```
private Object[] a = new Object[5];
```
The problem occurs when the result of method `getA()`, which at runtime actually returns an `Object[]`, is assigned to a reference of type `Double[]` - this statement throws the ClassCastException because Object cannot be cast to Double.
**Update 2**: to answer your final question "why do arrays break this?" The answer is because the language specification does not support generic array creation. [See this forum post for more](http://forums.sun.com/thread.jspa?threadID=530823) - in order to be backwards compatible, nothing is known about the type of T at runtime. | 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 the same case as following:
```
Object[] oarr = new Object[10];
Double[] darr = (Double[]) oarr;
```
This is obviously not allowed.
For your issue of creating typesafe arrays, another alternative is to except a class object in init and use Array.newInstance:
```
import java.lang.reflect.Array;
class Foo<T> {
private T[] a ;
public Foo(Class<T> tclass) {
a = (T[]) Array.newInstance(tclass, 5);
}
public T[] getA() {
return a;
}
public static <T> Foo<T> create(Class<T> tclass) {
return new Foo<T>(tclass);
}
}
class Array1
{
public static final void main(final String[] args) {
Foo<Double> f = Foo.create(Double.class);
Double[] d = f.getA();
}
}
``` | 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, but little documentation as to where the strings came from and what they mean. And it also seems like the different algorithms may require different implementations of the KeySpec class, so I'm not sure what algorithms can use the PBEKeySpec class I'm looking at. Furthermore, the examples all seem a little out of date, many requiring you to get an older cryptography package that used to not be part of the JDK, or even a third-party implementation.
Can someone provide a straightforward introduction to what I need to do to implement encrypt(String data, String passphrase) and decrypt(byte[] data, String passphrase)? | 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) is a good starting point. Check out the accompanying [code example](http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#PBEEx) illustrating Password-Based Encryption (PBE).
Btw, the standard JRE provides only a few options out-of-the-box for PBE ("PBEWithMD5AndDES" is one of them). For more choices, you'll need the "strong encryption pack" or some third-party provider like [Bouncy Castle](http://www.bouncycastle.org/). Another alternative would be to implement your own PBE using the hash and cipher algorithms provided in the JRE. You can implement PBE with SHA-256 and AES-128 this way ([sample encrypt/decrypt methods](http://gmailassistant.sourceforge.net/src/org/freeshell/zs/common/Encryptor.java.html)).
Briefly, the encrypt method for PBE may involve the following steps:
1. Get password and cleartext from the user, and convert them to byte arrays.
2. Generate a secure random [salt](http://en.wikipedia.org/wiki/Salt_(cryptography)).
3. Append the salt to the password and compute its cryptographic [hash](http://en.wikipedia.org/wiki/Cryptographic_hash_function). Repeat this many times.
4. Encrypt the cleartext using the resulting hash as the [initialization vector](http://en.wikipedia.org/wiki/Initialization_vector) and/or secret [key](http://en.wikipedia.org/wiki/Key_(cryptography)).
5. Save the salt and the resulting ciphertext. | 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.com/docs/cd/E12839_01/apirefs.1111/e10668/oracle/security/crypto/core/PBEAlgorithmIdentifier.html). It is also included in the .NET Base Class Library ([Rfc2898DeriveBytes](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx)).
There are some LGPL implementations in Java out there, but on a quick look [this one](http://www.rtner.de/software/PBKDF2.html) looks a little over complicated. There is also a good [javascript version](http://anandam.name/pbkdf2/pbkdf2.js.txt). (I produced [a modified version of that one](http://cheeso.members.winisp.net/srcview.aspx?dir=AES-example&file=Ionic.Com.PBKDF2.wsc) and packaged it as a Windows Script Component)
Lacking a good implementation with an appropriate license, I packaged some code up from Mattias Gartner. This is the code in its entirety. Short, simple, easy to understand. It's licensed under the [MS Public License](http://www.opensource.org/licenses/ms-pl.html).
```
// PBKDF2.java
// ------------------------------------------------------------------
//
// RFC2898 PBKDF2 in Java. The RFC2898 defines a standard algorithm for
// deriving key bytes from a text password. This is sometimes
// abbreviated "PBKDF2", for Password-based key derivation function #2.
//
// There's no RFC2898-compliant PBKDF2 function in the JRE, as far as I
// know, but it is available in many J2EE runtimes, including those from
// JBoss, IBM, and Oracle.
//
// It's fairly simple to implement, so here it is.
//
// Created Sun Aug 09 01:06:57 2009
//
// last saved:
// Time-stamp: <2009-August-09 02:19:50>
// ------------------------------------------------------------------
//
// code thanks to Matthias Gartner
//
// ------------------------------------------------------------------
package cheeso.examples;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class PBKDF2
{
public static byte[] deriveKey( byte[] password, byte[] salt, int iterationCount, int dkLen )
throws java.security.NoSuchAlgorithmException, java.security.InvalidKeyException
{
SecretKeySpec keyspec = new SecretKeySpec( password, "HmacSHA1" );
Mac prf = Mac.getInstance( "HmacSHA1" );
prf.init( keyspec );
// Note: hLen, dkLen, l, r, T, F, etc. are horrible names for
// variables and functions in this day and age, but they
// reflect the terse symbols used in RFC 2898 to describe
// the PBKDF2 algorithm, which improves validation of the
// code vs. the RFC.
//
// dklen is expressed in bytes. (16 for a 128-bit key)
int hLen = prf.getMacLength(); // 20 for SHA1
int l = Math.max( dkLen, hLen); // 1 for 128bit (16-byte) keys
int r = dkLen - (l-1)*hLen; // 16 for 128bit (16-byte) keys
byte T[] = new byte[l * hLen];
int ti_offset = 0;
for (int i = 1; i <= l; i++) {
F( T, ti_offset, prf, salt, iterationCount, i );
ti_offset += hLen;
}
if (r < hLen) {
// Incomplete last block
byte DK[] = new byte[dkLen];
System.arraycopy(T, 0, DK, 0, dkLen);
return DK;
}
return T;
}
private static void F( byte[] dest, int offset, Mac prf, byte[] S, int c, int blockIndex ) {
final int hLen = prf.getMacLength();
byte U_r[] = new byte[ hLen ];
// U0 = S || INT (i);
byte U_i[] = new byte[S.length + 4];
System.arraycopy( S, 0, U_i, 0, S.length );
INT( U_i, S.length, blockIndex );
for( int i = 0; i < c; i++ ) {
U_i = prf.doFinal( U_i );
xor( U_r, U_i );
}
System.arraycopy( U_r, 0, dest, offset, hLen );
}
private static void xor( byte[] dest, byte[] src ) {
for( int i = 0; i < dest.length; i++ ) {
dest[i] ^= src[i];
}
}
private static void INT( byte[] dest, int offset, int i ) {
dest[offset + 0] = (byte) (i / (256 * 256 * 256));
dest[offset + 1] = (byte) (i / (256 * 256));
dest[offset + 2] = (byte) (i / (256));
dest[offset + 3] = (byte) (i);
}
// ctor
private PBKDF2 () {}
}
``` | 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 actually handle. | 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 (SpecificException2 ex2)
{
// handle Specific Exception 2
}
catch (SpecificException3 ex3)
{
// handle Specific Exception 3
}
catch (Exception ex)
{
// handle an exception that isn't specific
}
``` | 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). If the date has changed, make it call a callback function in the main part of your app.
Like I said, this doesn't seem like a brilliant solution to your problem and there are probably much better ways of doing it. | 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 also be of interest
"[How to subclass CListBox and Cedit inside of CComboBox](http://support.microsoft.com/default.aspx?scid=kb;en-us;Q174667)"
Really one has to ask if it is worth the effort, and alot of that depends things like
* number of entries in the list
* number of times the dialog will show
* variability of the combo content
* optomising elsewhere
+ not drawing until the screen is complete
+ only building the dialog once and re showing it.
+ using the one combo but showing it in different locations at different times | 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 plotted is to be read from a shapefile.
I have the following doubts:
1. How to use the WGS84 projection of the .shp file(as read from the .prj file of the shapefile,WKT format) into my existing glOrtho projection..is there any conversion that needs to be done? and how is it different from what the glOrtho() sets up?basically how to use this information?
2. My application needs to be setup in such a way that i can know the exact lat/long of a point on the map.for eg. if i am hovering on X city,its correct lat/long could be fetched.I know that this can be done by using opensource utils/apis like GDAL/OGR but i am messed up as the documentation of these apis are not getting into my head.
I tried to find some sample c++ progs but couldnt find one.
3. I have already written my own logic to read the coordinates from a shapefile containing either points/polyline/polygon(using C-shapelib) and plotted over my opengl screen.I found a OGR sample code in doc to read a POINTS shapefile but none for POLYGON shapefile.And the problem is that this application has to be so dynamic that upon loading the shapefile,it should correctly setup the projection of the opengl screen depending upon the projection of the .shp file being read..eg WGS84,LCC,EVEREST MODIFIED...etc. how to achieve this from OGR api?
Kindly give your inputs on this problem.. I am really keen to make this work but im not getting the right start.. | 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 file is projection info. WGS84 gives you lat/long coords(Spherical).
But your display system is 2D(Rectangular). So, you need to convert 3D Spherical coords to 2D Rectangular coords(This is the meaning of Projection).Projection types are numerous,depending on the area of interest on the globe(remember projection distorts area/shape/size of features).Projection types range from Polyconic, Modified Everest, NAD, UTM, etc.,
3. If you simply need WGS84 ,then read bounding box coords of your .sh file and assign them to glOrtho. If you have any projection(eg:-UTM), then you convert your bounding box coords into Projection coords and then assign the newly projected coords to glOrtho. For converting lat/long into any Projection, you may require projection libraries like "Projlib" or "GeotransEngine" and etc.
For further clarifications you may contact me on dgplinux@ y a h o o . c o m | 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 system read from OGR sources. | 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 in the following example?
* User
+ UserPrefence
+ Order
* Order
+ Product
Order has a relationship with both product and user but you wouldn't put functionality for all 4 entities in the same repository. What do you do when you are dealing with the user entities and gathering order information? You may need extra information about the product and often ORMs will offer the ability of lazy loading. However if your product entity is in a separate repository to the user entity then surely this would cause a conflict between repositories? | 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 only allow Aggregates to relate to each other through a read only interface. One of the key thoughts behind Aggregates is that you can't change state of underlying objects without going through the root. So if Product and User are root Aggregates in your model than I can't update a Product if I got to it by going through User->Order->Product. I have to get the Product from the Product repository to edit it. (From a UI point of view you can make it look like you go User->Order->Product, but when you hit the Product edit screen you grab the entity from the Product Repository).
When you are looking at a Product (in code) by going from User->Order->Product you should be looking at a Product interface that does not have any way to change the underlying state of the Product (only gets no sets etc.)
Organize your Aggregates and therefor Repositories by how you use them. I can see User and Prodcut being their own Aggregates and having their own Repositories. I'm not sure from your description if Order should belong to User or also be stand alone.
Either way use a readonly interface when Aggregates relate. When you have to cross over from one Aggregate to the other go fetch it from its own Repository.
If your Repositories are caching then when you load an Order (through a User) only load the Product Id's from the database. Then load the details from the Product Repository using the Product Id. You can optimize a bit by loading any other invariants on the Product as you load the Order. | 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 of the tables. | 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(cc[1]);
// Do stuff
} else {
// Error, regex did not match
}
``` | 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>
<script>
<!--
function showDetails()
{
var elem = document.getElementById("my_div");
alert("elem.className=" + elem.className);
alert("elem.style.padding=" + elem.style.padding);
alert("elem.style.paddingLeft=" + elem.style.paddingLeft);
alert("elem.style.margin=" + elem.style.margin);
alert("elem.style.marginLeft=" + elem.style.marginLeft);
alert("elem.style.border=" + elem.style.border);
alert("elem.style.borderLeft=" + elem.style.borderLeft);
}
-->
</script>
</head>
<body>
<div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
some text here
</div>
<button onclick="showDetails();">show details</button>
</body>
</html>
```
you can see, if you click the button, that the padding is not reported right. Only the properties defined directly through "style" are reported back, those defined through a CSS class are not reported.
Is there a way to get back the final values of these properties? I mean the values obtained after all CSS settings are computed and applied by the browser. | 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.getComputedStyle(div);
display("Current marginTop: " + style.marginTop);
```
if you are using jQuery, @vsync 's solution is fine. | 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 methods:
```
/* Gets the total number of results. */
int getFullListSize();
/* Gets the current page of results. */
List getList();
/* Gets the page size. */
int getObjectsPerPage();
/* Gets the current page number. */
int getPageNumber();
/* Get the sorting column and direction */
String getSortCriterion();
SortOrderEnum getSortDirection();
```
I'm thinking of throwing my PaginatedList implementation a Criteria object and let it work along theese lines...
```
getFullListSize() {
criteria.setProjection(Projections.rowCount());
return ((Long) criteria.uniqueResult()).intValue();
}
getList() {
if (getSortDirection() == SortOrderEnum.ASCENDING) {
criteria.addOrder(Order.asc(getSortCriterion());
} else if (getSortDirection() == SortOrderEnum.DECENDING) {
criteria.addOrder(Order.desc(getSortCriterion());
}
return criteria.list((getPageNumber() - 1) * getObjectsPerPage(),
getObjectsPerPage());
}
```
But this doesn't work, because the `addOrder()` or the `setProjection()` calls modify the criteria object rendering it in-usable for the successive calls. I'm not entirely sure of the order of the calls, but the db throws an error on `getFullListSize()` trying to do a "`select count(*) ... order by ...`" which is obviously wrong.
I think I could fix this by creating an object of my own to keep track of query conditions and rebuilding the Criteria object for each call, but that feels like reinventing yet another wheel. Is there a smarter way, possibly copying the Criteria initially passed in and working on that copy?
***Update***:
It looks like `getList` is called first, and `getFullListSize` is called multiple times after, so, as soon as there's an ordering passed in, `getFullListSize` will fail. It would make sense to hit the db only once (in `getList` I'd say) and cache the results, with no need to copy/reset the `Criteria` object, but still...
***Update (again)***:
Forget about that, once I've done the `count` I can't do the `select`, and vice versa. I really need two distinct `Criteria` objects. | 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 PaginatedList ALWAYS runs a count query before looking for results, so ordering isn't an issue. | 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 | 1 |
| 2 | 3 |
| 4 | 4 |
+------+------+
select * from bar
+------+-------+------+
| bid | value | zid |
+------+-------+------+
| 1 | 2 | 10 |
| 2 | 4 | 20 |
| 3 | 8 | 30 |
| 4 | 42 | 30 |
+------+-------+------+
```
What I want to request is, "Give me a list of all the fid and values with zid of 30"
I expect an answer for all the fids, so the result would look like:
```
+------+--------+
| fid | value |
+------+--------+
| 1 | null |
| 2 | 8 |
| 3 | null |
| 4 | 42 |
+------+--------+
``` | ```
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)?
Here's the whole thing,
```
#include <allegro.h>
BITMAP* buffer;
int x = 15;
int y = 11;
int tempX = 15;
int tempY = 11;
//This will be our background, 1 = clouds, 2 = brick, 3 = floor
int map[24][32] = {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}};
//This will contain all the objects, 100 = player
int objMap[24][32] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
void setupGame(){
buffer = create_bitmap( 640, 480);
for (int i = 0; i <= 24; i++){
for( int t = 0; t <= 32; t++){
if( map[i][t] == 1) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 128, 255, 255));
else if( map[i][t] == 2) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 255, 128, 0));
else if( map[i][t] == 3) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 0, 0, 255));
}
}
for (int i = 0; i <= 24; i++){
for( int t = 0; t <= 32; t++){
if( objMap[i][t] == 100) circlefill( buffer, (t * 20) + 10, (i * 20) + 10, 10, makecol( 255, 255, 0));
}
}
draw_sprite( screen, buffer, 0, 0);
}
void movePlayer(){
tempX = x;
tempY = y;
if ( key[KEY_UP] && map[y - 1][x] == 3){
for ([y - 1][x] == 3; --y){ // these lines are the ones
}
}
else if( key[KEY_DOWN] && map[y + 1][x] == 3){
for ([y + 1][x] == 3; ++y){
}
}
else if( key[KEY_RIGHT] && map[y][x + 1] == 3){
for ([y][x + 1] == 3; ++x){
}
}
else if( key[KEY_LEFT] && map[y][x - 1] == 3){
for ([y][x - 1] == 3; --x){
}
}
acquire_screen();
rectfill( buffer, tempX * 20, tempY * 20, (tempX + 1) * 20, (tempY + 1) * 20, makecol( 255, 0, 0));
circlefill( buffer, (x * 20) + 10, (y * 20) + 10, 10, makecol( 255, 255, 0));
draw_sprite( screen, buffer, 0, 0);
release_screen();
rest(20);
}
int main(){
allegro_init();
install_keyboard();
set_color_depth(16);
set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0);
setupGame();
while( !key[KEY_ESC]){
modePlayer();
}
return 0;
}
END_OF_MAIN();
```
and here's the section that breaks;
```
void movePlayer(){
tempX = x;
tempY = y;
if ( key[KEY_UP] && map[y - 1][x] == 3){
for ([y - 1][x] == 3; --y){
}
}
else if( key[KEY_DOWN] && map[y + 1][x] == 3){
for ([y + 1][x] == 3; ++y){
}
}
else if( key[KEY_RIGHT] && map[y][x + 1] == 3){
for ([y][x + 1] == 3; ++x){
}
}
else if( key[KEY_LEFT] && map[y][x - 1] == 3){
for ([y][x - 1] == 3; --x){
}
}
```
it's the for lines it doesn't like.
thanks if you can help. | 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][x + 1] == 3)
for ( ; map[y][x + 1] == 3; ++x){
}
else if(key[KEY_LEFT] && map[y][x - 1] == 3)
for ( ; map[y][x - 1] == 3; --x){
}
``` | 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"` and `"Username2"` pops up, as expected. I could chose the first item and the `<input>`'s value would become `"Username1"`, but what I *really* want to send to the server is the user ID.
Can I somehow get a hold of the ID that is following the user name? I intend to do the form post on change of the text box. Maybe I'm just too blind to see it in the docs or to find it on Google? | 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[1]);
}
});
``` | 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 *will* go wrong at some point.
Besides, if you need to handle non-js user-agents, you'll need to write this method in any way. | 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 types using this base class:
```
int main(int argc, char* argv[])
{
int size = 0;
Base* bases = new Base[10];
bases[size++] = new A();
bases[size++] = new B();
for (int i = 0; i < size; i++)
{
Base* base = bases[i];
base->Test();
}
}
```
(Excuse any errors I might have made, I'm writing this on the fly to provide a simple example).
The problem is I can't instantiate the array as it would require creating an instance of the Base class (which it can't do as it's abstract). However, without doing this, it hasn't allocated the memory needed to assign to the indices of the array, and thus provides a segmentation fault when trying to access that memory. I am under the impression that it's not good practice to mix new and delete with malloc and free.
It may be that I have confused the way this should be used and I should be attempting to use templates or some other mechanism to do this, but hopefully I've provided enough information to illustrate what I'm attempting to do.
So what is the best way of doing this and how would I get around this problem of allocating memory to an abstract class?
Thanks,
Dan | 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*[10];
bases[size++] = new A();
bases[size++] = new B();
for (int i = 0; i < size; i++)
{
Base* base = bases[i];
base->Test();
}
}
``` | 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 ...tomcat/conf/context.xml
2 ...tomcat/Catalina/localhost/myapp.xml
3 ...tomcat/webapps/myapp/META-INF/context.xml
```
What is the order of precedence? | 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 [Tomcat 5.5 official documentation for the **Context Container**](http://tomcat.apache.org/tomcat-5.5-doc/config/context.html).
So if that's the simple answer, whats the complete answer?
Tomcat 5.5. will look in a couple of other places for `<Context>` elements beyond those you've listed (see the official docs).
The `META-INF/context.xml` will never be opened if Tomcat finds a `Catalina/localhost/myapp.xml`. So if you actually have all the files above, its more correct to say the the `META-INF/context.xml` is **irrelevant**, not that it's the lowest precedence.
If you say `<Context override="true" ...>` in your `Catalina/localhost/myapp.xml` that will make it the **highest** precedence, regardless of `conf/context.xml`. Same thing in your `META-INF\context.xml`, as long as you don't have a `Catalina/localhost/myapp.xml` (see previous paragraph).
Also, the `/Catalina/localhost/` portion of the path in the files above actually comes out of the "default" `conf/server.xml` and matches the `<Engine name="Catalina" defaultHost="localhost">`. If your `server.xml` uses different values for `name` and `defaultHost` in the `<Engine>`, that's the dir structure where Tomcat will look.
Finally, for the `...tomcat\` portion of the files you listed, Tomcat uses the dir from the `$CATALINA_BASE` environment variable. If that's not set, then it uses the dir from the `$CATALINA_HOME` environment variable, which is the directory of the Tomcat installation. I like to set and use `$CATALINA_BASE` so that I don't "pollute" my Tomcat installation. | 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 webapp. Either it is place here manually, or is taken from your webapp *at deployment time*...so this is the real master that TC uses. If you edit this changes will be read next start.
* tomcat/webapps/myapp/META-INF/context.xml - this is copied to tomcat/Catalina/ upon *initial deployment* if you alter this after initial deployment, I don't think that has any effect | 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 a little more
c) Code both javascript-enabled and javascript-disabled functionality
I'm not really sure as the web is always changing, what do you recommend? | 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 itself in this scenario.
For this reason, "blocking" scripts ( ie: document write inline ) like that present in google's tracker, should be avoided, or at very least, should go as late in the page as possible so the page renders whether or not the domain is timing out requests or not.
If you happen to be serving JS from a broken/malicious server, by intent or by accident, one can halt page rendering simply by having a script that serves that javascript which just calls "sleep(forever)" once its sent all the headers.
### Some People Use NoScript
Like the above problem, sometimes the clients environment may block certain script sources, be it the users choosing, or other reasons ( ie: browser security satisfactions, odd antivirus/anti-malware apps ). The most popular and controllable instance of this is NoScript, and I myself paranoidly block some of the popular tracking/advertising services with it ( some proxy servers will do this too ).
However, if a site is not well designed, the failing of one script to load still executes code that was dependant on that script being present, which yeilds errors and stops everything working.
My recommendation is :
1. Use Firebug
2. Use NoScript and block out everything --> See Site still works
3. Enable core site scripts that you cant' do without for anything --> See site still works and firebug doesn't whine.
4. Enable 3rd party stuff --> See site still works and firebug doesn't whine.
There are a lot of other complications that can crop up, but satisfying the above 2 should solve most of them. Just assume that, for whatever reason, one or more resources that comprise a page are viable to spontaneously disappear ( they do, all the time ), and you want the page to "survive" this problem as amicably as possible. For the problems that may persist for < 10 seconds, its not so bad, refresh the page and its fixed, but if its a problem that can occur, and severley hamper usability for an hour or more at a time.
In essence, instead of thinking "oh, theres the edge case users that don't have javascript", try thinking more a long the lines of "its really easy to have something go wrong, and have *ALL* of our users with broken javascript. Ouch! Lets try make it so we dont' really hose ourself when that does happen"
( I've seen IE updates get rolled out and hose javascript for that entire browser until the people whom wrote the scripts find a workaround. Losing all your IE customers is not a good thing )
`:set sarcasm`
`:set ignoreSpelling`
`:set iq=76`
### Don't worry, its only a 5% Niché Market
Nobody cares about targeting Niché markets right? All those funny propeller heads running lynx in their geeky stupid linoox cpus, spending all their time on the intarwebs surfing because they have nothing better to do with their life or money? the crazy security paranoid nerds disabling javascript left and right because they don't like it?
Nobody wants them as your primary customer now do they?
Niché markets. Pfft. Who cares!
`:set nosarcasm` | 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 all of them uses handles)
Do you have a specific problem with too many handles, or perhaps even a handle leak? | 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 current appsettings? | 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 KeyValueConfigurationElement("SMTP",
> "mail.bhaidar.net")
> );
>
> configFile.Save();
The above code would add the following line to the appSettings section.
> < appSettings >
>
> ```
> < add key="SMTP" value="mail.bhaidar.net" / >
> ```
>
> < / appSettings > | 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 application. | 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 spaces.
```
Allocation(Param 1 = Val1, Param 2 = Val2 )
```
Python parser friendly versions can look as follows, but not very user friendly.
```
Allocation(("Param 1",Val1), ("Param 2",Val1) )
Allocation(**{"Param 1":Val1, "Param 2":Val1} )
```
Is there a way to make this more readable in python? | 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 what you want to do, but my first concern is if the effort involved would be worth the result.
> my goal is to provide a DSL which can be used for data entry into the system. In the above scenario, params would be people names and values would be percentages.
I have a better understanding of what you want to do now, but I still think that you might end up having to sacrifice some readability to get what you want. Personally, I would go with something like:
```
Allocation(
{ 'name1' : value1,
'name1' : value2, }
)
```
If that's not something you can go with, then you might want to reconsider whether you want to use Python for your DSL or go with something home-grown. Allowing whitespace allows too many ambiguities for most programming languages to allow it.
If you still want to pursue this with using python, you might want to consider posting to the C-API SIG ([SIGS](http://www.python.org/community/sigs/)) or maybe the [python-dev list](http://mail.python.org/mailman/listinfo/python-dev) (as a last resort). The only way that I can see to do this would be to embed the python interpreter into a C/C++ program and do some kind of hacking with it (which can be difficult!). | 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 = new JButton("Ok");
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( button , BorderLayout.CENTER );
....
}
```
Change it to something like this:
```
public static void main( String [] args ) {
JLabel label = new JLabel("Some info");
JButton button = new JButton("Ok");
JPanel panel = new JPanel();
panel.add( button );
JFrame frame = ...
frame.add( label, BorderLayout.NORTH );
frame.add( panel , BorderLayout.CENTER);
....
}
```
Before/After
[Before http://img372.imageshack.us/img372/2860/beforedl1.png](http://img372.imageshack.us/img372/2860/beforedl1.png)
[After http://img508.imageshack.us/img508/341/aftergq7.png](http://img508.imageshack.us/img508/341/aftergq7.png) | 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>
<property name="hibernate.connection.url">jdbc:mysql://mysql.netfirms.ca:3306/d60549476</property>
<property name="hibernate.connection.username">u70612250</property>
<property name="hibernate.connection.password">******</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Use the C3P0 connection pool provider -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- List of XML mapping files -->
<mapping resource="customer.hbm.xml"/>
<mapping resource="customerSummary.hbm.xml"/>
<mapping resource="charity.hbm.xml"/>
<mapping resource="charitySummary.hbm.xml"/>
</session-factory>
</hibernate-configuration>
```
When I start my application, I get the following printout:
```
16 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
....
94 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
....
485 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
532 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
532 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
547 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
547 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://mysql.netfirms.ca:3306/d60549476
547 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=u70612250, password=****}
168719 [main] WARN org.hibernate.cfg.SettingsFactory - Could not obtain connection metadata
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.NoRouteToHostException
MESSAGE: No route to host: connect
STACKTRACE:
java.net.NoRouteToHostException: No route to host: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
```
I ensured that my database is configured to allow remote access. I'm wondering what causes this. Obviously, I'm unable to establish a connection with the host, but I'm not sure why. Assuming the host name, user, and password are correct, am I missing something?
Addendum: I tried connecting using the same driver with Squirrel, and got the same exact error. | 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 apparently I was the only one to notice, that connections from remote machines was not available. They sent an apology earlier, and now I can connect just fine.
Thanks to everyone for your help. | 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/designPattern/enum.html> | 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 and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class.
Here is the code
```
import wx
class mainPanel(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450))
wx.Panel(self,-1)
wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10))
menubar = wx.MenuBar()
parser = wx.Menu()
one =wx.MenuItem(parser,1,'&Extract Tables with One Heading or Label')
two =wx.MenuItem(parser,1,'&Extract Tables with Two Headings or Labels')
three =wx.MenuItem(parser,1,'&Extract Tables with Three Headings or Labels')
four =wx.MenuItem(parser,1,'&Extract Tables with Four Headings or Labels')
quit = wx.MenuItem(parser, 2, '&Quit\tCtrl+Q')
parser.AppendItem(one)
parser.AppendItem(two)
parser.AppendItem(three)
parser.AppendItem(four)
parser.AppendItem(quit)
menubar.Append(parser, '&Table Parsers')
textRip = wx.Menu()
section =wx.MenuItem(parser,1,'&Extract Text With Section Headings')
textRip.AppendItem(section)
menubar.Append(textRip, '&Text Rippers')
dataHandling = wx.Menu()
deHydrate =wx.MenuItem(dataHandling,1,'&Extract Data from Tables')
dataHandling.AppendItem(deHydrate)
menubar.Append(dataHandling, '&Data Extraction')
self.Bind(wx.EVT_MENU, self.OnQuit, id=2)
```
# this is where I think I am being clever by using a button click to create an instance
# of subPanel.
```
self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1)
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
def OnQuit(self, event):
self.Close()
class subPanel(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450))
wx.Panel(self,-1)
wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10))
getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350))
getDirectory.SetDefault()
getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400))
getTerm1.SetDefault()
#getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button)
self.Centre()
self.Show(True)
app = wx.App()
mainPanel(None, -1, '')
app.MainLoop()
``` | 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): #don't forget the evt
sp = SubPanel(self, wx.ID_ANY, 'TEST')
#I assume you will add it to a sizer
#if you aren't... you should
test_sizer.Add(sp, 1, wx.EXPAND)
#force the frame to refresh the sizers:
self.Layout()
```
Alternatively, you can instantiate the subpanel in your frame's `__init__` and call a `subpanel.Hide()` after instantiation, and then your menuitem event handler and call a show on the panel `subpanel.Show()`
Edit: Here is some code that will do what I think that you are asking:
```
#!usr/bin/env python
import wx
class TestFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
wx.Frame.__init__(self, parent, *args, **kwargs)
framesizer = wx.BoxSizer(wx.VERTICAL)
mainpanel = MainPanel(self, wx.ID_ANY)
self.subpanel = SubPanel(self, wx.ID_ANY)
self.subpanel.Hide()
framesizer.Add(mainpanel, 1, wx.EXPAND)
framesizer.Add(self.subpanel, 1, wx.EXPAND)
self.SetSizerAndFit(framesizer)
class MainPanel(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
panelsizer = wx.BoxSizer(wx.VERTICAL)
but = wx.Button(self, wx.ID_ANY, "Add")
self.Bind(wx.EVT_BUTTON, self.OnAdd, but)
self.panel_shown = False
panelsizer.Add(but, 0)
self.SetSizer(panelsizer)
def OnAdd(self, evt):
if not self.panel_shown:
self.GetParent().subpanel.Show()
self.GetParent().Fit()
self.GetParent().Layout()
self.panel_shown = True
else:
self.GetParent().subpanel.Hide()
self.GetParent().Fit()
self.GetParent().Layout()
self.panel_shown = False
class SubPanel(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
spsizer = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel')
spsizer.Add(text, 1, wx.EXPAND)
self.SetSizer(spsizer)
if __name__ == '__main__':
app = wx.App()
frame = TestFrame(None, wx.ID_ANY, "Test Frame")
frame.Show()
app.MainLoop()
``` | 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 __init__(self, parent, title="My Frame", num=1):
self.num = num
wx.Frame.__init__(self, parent, -1, title)
panel = wx.Panel(self)
button = wx.Button(panel, -1, "New Panel")
button.SetPosition((15, 15))
self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# Now create a menu
menubar = wx.MenuBar()
self.SetMenuBar(menubar)
# Panel menu
panel_menu = wx.Menu()
# The menu item
menu_newpanel = wx.MenuItem(panel_menu,
wx.NewId(),
"&New Panel",
"Creates a new panel",
wx.ITEM_NORMAL)
panel_menu.AppendItem(menu_newpanel)
menubar.Append(panel_menu, "&Panels")
# Bind the menu event
self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel)
def OnNewPanel(self, event):
panel = MyFrame(self, "Panel %s" % self.num, self.num+1)
panel.Show()
def OnCloseWindow(self, event):
self.Destroy()
def main():
application = wx.PySimpleApp()
frame = MyFrame(None)
frame.Show()
application.MainLoop()
if __name__ == "__main__":
main()
```
---
**Edit**: Added code to do this from a menu. | 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_match_all('/(?:\$|£)[0-9]+(?:\.[0-9]{2})?/', $contents, $matches);
```
So far so simple. The problem is, PHP isn't matching anything at all - even when there are prices on the page. I've narrowed it down to there being a problem with the '£' character - PHP doesn't seem to like it.
I think this might be a charset issue. But whatever I do, I can't seem to get PHP to match it! Anyone have any ideas?
(Edit: I should note if I try using the [Regex Test Tool](http://www.spaweditor.com/scripts/regex/index.php) using the same regex and page content, it works fine) | 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 ":".
[](https://i.stack.imgur.com/DwYIJ.png)
(source: [clip2net.com](http://clip2net.com/clip/m12122/1227972904-clip-9kb.png))
Read my comment about the possibility of Curl giving you bad encoding (comment of this post). | 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** page and equates to the **/FI** compiler option.
This option could prove really useful but before I rush off and start using it I thought I'd ask if there are any gotchas? | 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 time for someone that wants to figure out where specific macros come from, even though there are no `#include` lines at the top of the file. | 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, all the includes and #defines are ignored up to the "stdafx.h". So, if you force include the "stdafx.h" then the above will never happen and you'll get a project that uses the precompiled option efficiently.
As for litb's comment about finding macros, good IDE's usually have an option to jump to the definition of a symbol, whether it be a #define, function, class, etc. | 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 it is called like this:
```
SetTopMargin("test_div_id", 100);
```
So does anyone know some code that will work in Internet Explorer? | [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(
'marginTop', Value.ToString() + 'px');
```
**EDIT** - From deleted comment by OP:
> Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..) | 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', 100);">Test</button>
</body>
</html>
```
In IE6, it appears to be working as well after a very short pause. | 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) );
```
Of course (m1-m0) should equal random\_number, but I'm trying to do this on a more complicated level, including possible library calls that could allocate memory.
The following are not preferable:
1. Use Valgrind (or its ilk)
2. Use a custom memory allocator to track
allocated memory. | * 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's right.)
```
#ifdef __linux__
# include <sys/sysinfo.h>
#endif
#ifdef __APPLE__
# include <mach/task.h>
# include <mach/mach_init.h>
#endif
#ifdef _WINDOWS
# include <windows.h>
#else
# include <sys/resource.h>
#endif
/// The amount of memory currently being used by this process, in bytes.
/// By default, returns the full virtual arena, but if resident=true,
/// it will report just the resident set in RAM (if supported on that OS).
size_t memory_used (bool resident=false)
{
#if defined(__linux__)
// Ugh, getrusage doesn't work well on Linux. Try grabbing info
// directly from the /proc pseudo-filesystem. Reading from
// /proc/self/statm gives info on your own process, as one line of
// numbers that are: virtual mem program size, resident set size,
// shared pages, text/code, data/stack, library, dirty pages. The
// mem sizes should all be multiplied by the page size.
size_t size = 0;
FILE *file = fopen("/proc/self/statm", "r");
if (file) {
unsigned long vm = 0;
fscanf (file, "%ul", &vm); // Just need the first num: vm size
fclose (file);
size = (size_t)vm * getpagesize();
}
return size;
#elif defined(__APPLE__)
// Inspired by:
// http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
size_t size = (resident ? t_info.resident_size : t_info.virtual_size);
return size;
#elif defined(_WINDOWS)
// According to MSDN...
PROCESS_MEMORY_COUNTERS counters;
if (GetProcessMemoryInfo (GetCurrentProcess(), &counters, sizeof (counters)))
return counters.PagefileUsage;
else return 0;
#else
// No idea what platform this is
return 0; // Punt
#endif
}
``` | 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...
somefile.msi /a
C:\MyFolder\SomeFile.exe -i -d
I don't care much about the arguments cause once I have the path I'll assume the rest are arguments | 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 separate system (msi!MsiConfigureProduct or msi!MsiRemovePatches). | 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 .GetFilename, .GetExtension and .GetPathRoot.
You can also probably use System.IO.Directory and System.IO.File for additional features. | 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 concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?
Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical
\*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care *that* much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.\* | 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 optimized out of existence, and all you have left is C. In Python -- like all dynamic languages -- the dynamic programming environment adds some run-time lookups. Mostly, these are direct hashes into dictionaries. It's slower than code where a compiler did all the resolving for you. However it's still very fast with relatively low overhead.
A bad algorithm in C can easily be slower than the right algorithm in Python. | 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 already first (via an array with Boolean values), and if it has been downloaded before, simply display from cache.
I thought it was working fine for a while (because of the speed at which they would appear when clicked twice), but I recently looked into Firebug's Net tab and it seems to be downloading the large image every time (and the total file size gets bigger with every click).
I'm not sure what I have done wrong as a bit of debugging has informed me the Boolean values are being updated correctly.
So my question is, could Firebug be incorrect (I doubt it), or is there any way I can force it to display from cache (I thought using the exact same path to the image for the image.src would do this)
This was my first venture into objects in Javascript so I'm not 100% confident about my code so please be kind! | 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 if the cache is still fresh by sending[far-future headers](http://www.askapache.com/htaccess/apache-speed-expires.html) for components you want to cache hard. Bear in mind though, that in order to force the client to re-download a component that was cached this way you'll have to change the filename. | 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](http://www.wireshark.org/) is a packet sniffer.
I can't say exactly how Firebug net monitor works, because I've never dived under the hood, but I have experienced a few things which I thought were bugs of my doing, which went away when Firebug was turned off.
It seems that Firebug in the act of measuring things, alters things in a "looking at your quantum cat" kind of a way. Firebug still rocks, but it does have some limitations. | 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 to this specific domain ... these are expert users who will be using this.
Ultimately, I think I'd like the parse results to be available as some sort of expression tree. But if you've got some other ideas about what data structure might be better.
This is in C# :-) | 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 would have to agree with him, that if you want to do it, Antlr is the way to go. There are tutorials on the site that might help you get started. Basically, you will need to describe how the syntax using [Backus-Naur Form](http://en.wikipedia.org/wiki/Backus-Naur_form) notation.
You will then run Antlr over your grammer, and it will generate your parser. You can then feed the input from your textbook into an Abstract Syntax Tree. You can then use that Tree to generate your query. It's not as difficult as it all sounds, but there's a bit to it.
If you're really into this and/or want to stretch your programming wings a bit, you could read more on the topic with the Dragon Book, AKA Compilers: Principles, Techniques and Tools.
Good luck my friend. | 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://www.ssw.uni-linz.ac.at/Research/Projects/Coco/) -- it's fast, easy to use, and makes extremely debuggable code.
For a more complex language, my current favorite is [Antlr v3](http://www.antlr.org/). Supports multi-file grammars (via the 'import' statement), which is very nice. The generated code is debuggable, but takes a bit of getting used to before debugging could be considered 'easy.' | 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 better/faster? in mysql? in general? | ```
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. have NULL entries (for the same
reason)
If you are COUNT'ing based on a WHERE clause that is guaranteed to produce a single record (or 0) *and* the DBMS knows this (based upon UNIQUE indexes), then it ought to be just as efficient. But, it is unlikely that you will always have this condition. Also, the DBMS may not always pick up on this depending on the version and DBMS.
Counting in the application (when you don't need the row) is almost always guaranteed to be slower/worse because:
1. You have to send data to the client, the client has to buffer it and do some work
2. You may bump out things in the DBMS MRU/LRU data cache that are more important
3. Your DBMS will (generally) have to do more disk I/O to fetch record data that you will never use
4. You have more network activity
Of course, if you want to DO something with the row if it exists, then it is definitely faster/best to simply try and fetch the row to begin with! | 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 java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1030)
at org.eclipse.swt.internal.Library.loadLibrary(Library.java:100)
at org.eclipse.swt.internal.gtk.OS.<clinit>(OS.java:19)
at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:63)
at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:54)
at org.eclipse.swt.widgets.Display.<clinit>(Display.java:112)
at wenzlick.test.swt.main.Main.main(Main.java:30)
```
Has anyone successfully got a swt app to build and run using maven?
**Edit**: I did a little research and found the problem. look at my post below | 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 installing SWT 3.4 in your local repository by hand. If that still gives you the same problem, then something is probably fishy. After that, I would try extracting the `.so`s manually and then specifying the `java.library.path` variable using the `-D` switch on invocation. Sometimes on Linux the loading of the libraries can fail due to dependency problems (in things like libpango). In such cases, often the error will be just the generic `UnsatisifedLinkError`, making the problem difficult to debug. | 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.googlecode.com/svn/repo/</url>
</repository>
</repositories>
```
Then you can just reference the SWT dependency relevant to your platform. For example:
```
<dependency>
<groupId>org.eclipse.swt</groupId>
<artifactId>org.eclipse.swt.win32.win32.x86</artifactId>
<version>4.2.2</version>
</dependency>
```
For other platforms, just replace artifactId with the appropriate value:
* org.eclipse.swt.win32.win32.x86
* org.eclipse.swt.win32.win32.x86\_64
* org.eclipse.swt.cocoa.macosx
* org.eclipse.swt.cocoa.macosx.x86\_64
Artifacts for additional platforms and older versions are available as well, visit the repository link above to find them.
Happy coding! | 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 can be interned at runtime:
```
string now = DateTime.Now.ToString().Intern();
```
Obviously a string that is interned at runtime resides on the heap but I had assumed that a literal is placed in the program's data segment (and said so in my [answer](https://stackoverflow.com/questions/372354/string-immutability#372380) to said question). However I don't remember seeing this anywhere. I assume this is the case since it's how I would do it and the fact that the `ldstr` IL instruction is used to get literals and no allocation seems to take place seems to back me up.
To cut a long story short, where do string literals reside? Is it on the heap, the data segment or some-place I haven't thought of?
---
**Edit:** If string literals *do* reside on the heap, when are they allocated? | 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.WriteLine("press enter");
Console.ReadLine();
}
}
```
And you call `Foo()` on an instance, you can use WinDbg to inspect the heap.
The reference will most likely be stored in a register for a small program, so the easiest is to find the reference to the specific string is by doing a `!dso`. This gives us the address of our string in question:
```
0:000> !dso
OS Thread Id: 0x1660 (0)
ESP/REG Object Name
002bf0a4 025d4bf8 Microsoft.Win32.SafeHandles.SafeFileHandle
002bf0b4 025d4bf8 Microsoft.Win32.SafeHandles.SafeFileHandle
002bf0e8 025d4e5c System.Byte[]
002bf0ec 025d4c0c System.IO.__ConsoleStream
002bf110 025d4c3c System.IO.StreamReader
002bf114 025d4c3c System.IO.StreamReader
002bf12c 025d5180 System.IO.TextReader+SyncTextReader
002bf130 025d4c3c System.IO.StreamReader
002bf140 025d5180 System.IO.TextReader+SyncTextReader
002bf14c 025d5180 System.IO.TextReader+SyncTextReader
002bf15c 025d2d04 System.String hello world // THIS IS THE ONE
002bf224 025d2ccc System.Object[] (System.String[])
002bf3d0 025d2ccc System.Object[] (System.String[])
002bf3f8 025d2ccc System.Object[] (System.String[])
```
Now use `!gcgen` to find out which generation the instance is in:
```
0:000> !gcgen 025d2d04
Gen 0
```
It's in generation zero - i.e. it has just be allocated. Who's rooting it?
```
0:000> !gcroot 025d2d04
Note: Roots found on stacks may be false positives. Run "!help gcroot" for
more info.
Scan Thread 0 OSTHread 1660
ESP:2bf15c:Root:025d2d04(System.String)
Scan Thread 2 OSTHread 16b4
DOMAIN(000E4840):HANDLE(Pinned):6513f4:Root:035d2020(System.Object[])->
025d2d04(System.String)
```
The ESP is the stack for our `Foo()` method, but notice that we have a `object[]` as well. That's the intern table. Let's take a look.
```
0:000> !dumparray 035d2020
Name: System.Object[]
MethodTable: 006984c4
EEClass: 00698444
Size: 528(0x210) bytes
Array: Rank 1, Number of elements 128, Type CLASS
Element Methodtable: 00696d3c
[0] 025d1360
[1] 025d137c
[2] 025d139c
[3] 025d13b0
[4] 025d13d0
[5] 025d1400
[6] 025d1424
...
[36] 025d2d04 // THIS IS OUR STRING
...
[126] null
[127] null
```
I reduced the output somewhat, but you get the idea.
**In conclusion**: strings are on the heap - even when they are interned. The interned table holds a reference to the instance on the heap. I.e. interned strings are not collected during GC because the interned table roots them. | 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 behave no differently than had they been stored in the ordinary object heap. | 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 is the easiest way to do it in this scenario?
Thank you! | 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 prolly go through jQuery, or add your own function as J Cooper points out. | 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",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.