Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a `Player` class, which inherits from an `ArmedHumanoids` class, which inherits in turn from a `Humanoids` class.
Where and when should I create the `Player` object so that it is accessible in all my other classes - for example, a `selectPlayerRace` class?
I know that by extending the `Player` class it becomes accessible, but I am thwarted because all my other classes extend `JFrame`. There can be only one extension, not two.
At the moment the NetBeansIDE complains that it cannot locate the `Player` object when I code for it in `selectPlayerRace`, after creating the `Player` object in my `Main` class.
Obviously, it is happier when I create the `Player` object in the `selectPlayerRace` class, but then I can't access the `Player` object in all my other classes as it is internal to `selectPlayerRace`.
The `Player` object is intended to be a universal object accessible in all my other classes. | This sounds like a singleton pattern.
```
public class Player extends ArmedHumanoid {
private static Player instance = new Player();
private Player() {}
public static Player getIntstance() {
return instance
}
}
```
Then any class can call `Player.getInstance()` to get access to the Player object. | > The `Player` object is intended to be a
> universal object accessible in all my
> other classes.
Why not just pass this `Player` object in the constructor of the other classes, or in the methods that you call? | Inheritance and where to declare an intended universal object | [
"",
"java",
"inheritance",
"object",
""
] |
For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this:
```
>>> import win32net
>>> win32net.NetUserGetGroups('domain_name.com', 'username')
[(u'Domain Users', 7), ...]
```
I spent a while googling before I figured this out though, and the examples I found almost exclusively used LDAP for this kind of thing. Is there any reason why that's to be preferred over this method? Bear a couple things in mind:
1. I'm not using Active Directory to actually perform authentication, only permissions. Authentication is performed by another server.
2. While it would be nice to have some cross-platform capabilities, this will probably run almost exclusively on Windows. | AD's LDAP interface has quite a few 'quirks' that make it more difficult to use than it might appear on the surface, and it tends to lag significantly behind on features. When I worked with it, I mostly dealt with authentication, but it's probably the same no matter what you're doing. There's a lot of weirdness in terms of having to be bound as a certain user just to do simple searches that a normal LDAP server would let you do as anonymous.
Also, at least as of a year ago, when I worked on this, python-ldap was the only Python LDAP implementation to support anywhere close to the full feature set, since it's built on top of OpenLDAP, However, OpenLDAP is rather difficult to build on Windows (and in general), so most builds will be missing one or more features. Although you're not doing authentication, a lack of SASL/Kerberos support (which was missing at the time I used it) might make things complicated for you.
If you have something that works, and only need to run it on Windows, I would really recommend sticking to it; using AD via LDAP can turn into a big project. | ```
import wmi
oWMI = wmi.WMI(namespace="directory\ldap")
ADUsers = oWMI.query("select ds_name from ds_user")
for user in ADUsers:
print user.ds_name
``` | Is there any preferable way to get user/group information from an Active Directory domain in Python? | [
"",
"python",
"winapi",
"active-directory",
"ldap",
"pywin32",
""
] |
I need to remove commas within a String only when enclosed by quotes.
example:
```
String a = "123, \"Anders, Jr.\", John, john.anders@company.com,A"
```
after replacement should be
```
String a = "123, Anders Jr., John, john.anders@company.com,A"
```
Can you please give me sample java code to do this?
Thanks much,
Lina | Probably grossly inefficiënt but it seems to work.
```
import java.util.regex.*;
StringBuffer ResultString = new StringBuffer();
try {
Pattern regex = Pattern.compile("(.*)\"(.*),(.*)\"(.*)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(a);
while (regexMatcher.find()) {
try {
// You can vary the replacement text for each match on-the-fly
regexMatcher.appendReplacement(ResultString, "$1$2$3$4");
} catch (IllegalStateException ex) {
// appendReplacement() called without a prior successful call to find()
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}
}
regexMatcher.appendTail(ResultString);
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
``` | I believe you asked for a regex trying to get an "elegant" solution, nevertheless maybe a "normal" answer is better fitted to your needs... this one gets your example perfectly, although I didn't check for border cases like two quotes together, so if you're going to use my example, check it thoroughly
```
boolean deleteCommas = false;
for(int i=0; i > a.length(); i++){
if(a.charAt(i)=='\"'){
a = a.substring(0, i) + a.substring(i+1, a.length());
deleteCommas = !deleteCommas;
}
if(a.charAt(i)==','&&deleteCommas){
a = a.substring(0, i) + a.substring(i+1, a.length());
}
}
``` | Regex for removing comma in a String when it is enclosed by quotes | [
"",
"java",
"regex",
""
] |
> ### Duplicate
>
> [Why don’t self-closing script tags work?](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work)
I'm writing an ASP.net page, which have some Javascript code in JS file for client-side authentication.
While using this code **prevented** from my server-side code from working:
```
<script src="../../JavaScript/BaseJS.js" type="text/javascript" defer="defer" />
```
**This code** somehow worked:
```
<script src="../../JavaScript/BaseJS.js" type="text/javascript" defer="defer"></script>
``` | The [HTML4.01 manual section](http://www.w3.org/TR/html401/interact/scripts.html#edef-SCRIPT) defining the `SCRIPT` element, states:
> 18.2.1 The SCRIPT element
>
> ...
>
> Start tag: **required**, End tag: **required** | Am I right in saying you're testing with IE? This is a [known](http://www.phpied.com/ie-script-tag-problem/) [bug](http://webbugtrack.blogspot.com/2007/08/bug-153-self-closing-script-tag-issues.html). (I'm sure there are lots of other pages referring to it too.)
EDIT: In fact, there's [another Stack Overflow question](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work) about this too. | Javascript syntax <script /> VS <script></script> - the weirdest thing | [
"",
"javascript",
"html",
"xhtml",
""
] |
A lot of times you get a form where you need to enter an email address (or other form field) twice in order to confirm that you typed it correctly the first time. Some forms disable the copy and paste action (via javascript) in the browser to force the user to type the email address again.
Personally I find this highly annoying. What are your thoughts? Are there other options? | If you really want to check the email address you could implement a confirm email address function, which sends an email to the provided email address. The email could contain a link which allows the user to confirm his/her email address.
For obscured fields like password fields, it is always best to implement a double entry input field in case the user made a typo. | I find it highly annoying as well since, in many cases, the initial entry was done from an autofill that I know is correct.
Please note that this should be a community wiki! | What is the best approach for confirming html form fields? | [
"",
"javascript",
"validation",
""
] |
I think the question pretty much sums up my query. | When you use the Google web page to do searches while you're logged into GMail or other Google services, it uses information about your browsing history to modify the results. It can't do that with an API, since it assumes you're doing it for somebody other than yourself.
Also, as [@Walden](https://stackoverflow.com/users/20661/walden) mentioned in his answer, you may be hitting different servers for the two queries, and Google does a "slow sync" between the servers so they might not all have the latest search database or the latest version of the page ranking code. | Your Google web search may return different results than my Google web search for the same query. Google is constantly updating its search routines, and often will roll the updates out at different times in different data centers so each data center, and even each cluster in a data center may return different results.
Therefore, the results from the API probably come from a different codebase (version of the codebase) than your web request. | Why does a google search through the google api return different results to a search in the web page? | [
"",
"c#",
"search-engine",
""
] |
I'm writing a class library that will offer some asynchronous processing, and want to try and avoid running into threading issues later on down the line. So I'm after any suggestions people can make to avoid running into issues later on, and instead start with a good design.
Some of the situations that I can see that might cause problems, and am not neccessairly sure the best way to resolve:
1) I have a class that takes an IEnumerable and uses a ToList to construct an IList. The T's are a class declared as public within my assembly. Upon starting an async process this IList is used to create a new collection, however at this point the calling assembly may be modifying the original T's used to generate my new internal collection.
2) I have a Boolean property that I'm expecting the user to use in a polling loop. I'm fairly sure that this won't be a problem with me setting the property in my assembly?
3) I regularly used an internal collection that needs to be used on two seperate threads. I'm currently planning to use a synchronized collection and clone it whenever I need a copy... although I'm hoping this won't be too slow.
4) Throughout my async method I'm wanting to fire events whenever the progress or status changes. Do I need to be aware of anything when firing events from processing threads? Again with some of these I need to pass a variable which will be taken as a clone of something used internally within the processing threads to try and avoid any issues with the user changing it.
Thanks in advance for any assistance!
Ian | 1) Try to make your types immutable if possible. If that's not possible, you need to work on appropriate locking.
2) Make the underlying variable `volatile` so that updates get seen in all threads
3) We'd need more information to be able to sensibly comment.
4) The event handlers would need to be aware that they could be called on multiple threads. You should also look at a fully [thread-safe event pattern](http://www.yoda.arachsys.com/csharp/threads/lockchoice.shtml) if you need to be able to subscribe to and unsubscribe from events from various threads. | 2: watch out for `volatile` ([see here](https://stackoverflow.com/questions/458173/can-a-c-thread-really-cache-a-value-and-ignore-changes-to-that-value-on-other-th/458193#458193) for example why); and don't do a "tight" loop. Signals (such as a Monitor.Pulse, or a ManualResetEvent, etc) are often preferred
4: if this is for display purposes, you'll need to marshal these back to the UI thread | Any Tips on Threading Considerations + Design for following cases | [
"",
"c#",
"multithreading",
"assemblies",
""
] |
How could I prevent esc from closing a dialog box?
I searched for this topic, but all I found was for MFC (You can overwrite PreTranslateMessage function in MFC). but my program is written in Windows API, **not MFC**.
I tried to catch all Keyboard messages in Dialog procedure, but none of them works. I also tried using subclassing in dialog box, but it didn't work too.
How could I do that?
Thanks. | You can determine whether it's from the system menu easily enough -- check out the "return value" section of [this MSDN page](http://msdn.microsoft.com/en-us/library/ms647591(VS.85).aspx) to see how.
If you can't determine whether it's from the ESCAPE key or a button, you could always get around that by using a different identifier for your Cancel button. | Handle WM\_COMMAND and check for IDCANCEL. Then do not pass the control to the default window procedure. | VC++ : How to prevent esc from closing a dialog box (not mfc) | [
"",
"c++",
"windows",
"visual-c++",
"dialog",
""
] |
I'm looking for the alternative of `mysql_real_escape_string()` for SQL Server. Is `addslashes()` my best option or there is another alternative function that can be used?
An alternative for `mysql_error()` would also be useful. | `addslashes()` isn't fully adequate, but PHP's mssql package doesn't provide any decent alternative. The ugly but fully general solution is encoding the data as a hex bytestring, i.e.
```
$unpacked = unpack('H*hex', $data);
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (0x' . $unpacked['hex'] . ')
');
```
Abstracted, that would be:
```
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
```
`mysql_error()` equivalent is `mssql_get_last_message()`. | ```
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
```
Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.
EDIT:
There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: <http://php.net/manual/en/pdo.prepared-statements.php> | How to escape strings in SQL Server using PHP? | [
"",
"php",
"sql-server",
"escaping",
"sanitization",
""
] |
In my application I load resources in this manner:
```
WinProcessor.class.getResource("repository").toString();
```
and this gives me:
```
file:/root/app/repository (and I replace "file:" with empty string)
```
This works fine when I run my application from the IDE, but when I run the jar of my application:
```
java -jar app.jar
```
The path becomes:
```
jar:/root/app.jar!/repository
```
is there any way to solve this problem?
I'll use the "repository" dir name in order to create this:
```
ConfigurationContext ctx = (ConfigurationContext) ConfigurationContextFactory.createConfigurationContextFromFileSystem(repositoryString, null);
```
In the same manner, I'll get one file name (instead of a dir) and I'll use it this way:
```
System.setProperty("javax.net.ssl.trustStore", fileNameString)
``` | It sounds like you're then trying to load the resource using a `FileInputStream` or something like that. Don't do that: instead of calling `getResource`, call [`getResourceAsStream`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)) and read the data from that.
(You could load the resources from the URL instead, but calling `getResourceAsStream` is a bit more convenient.)
EDIT: Having seen your updated answer, it seems other bits of code rely on the data being in a physical single file in the file system. The answer is therefore not to bundle it in a jar file in the first place. You *could* check whether it's in a separate file, and if not extract it to a temporary file, but that's pretty hacky IMO. | When running code using `java -jar app.jar`, java uses ONLY the class path defined in the manifest of the JAR file (i.e. `Class-Path` attribute). If the class is in `app.jar`, or the class is in the class path set in the `Class-Path` attribute of the JAR's manifest, you can load that class using the following code snippet, where the `className` is the fully-qualified class name.
```
final String classAsPath = className.replace('.', '/') + ".class";
final InputStream input = ClassLoader.getSystemResourceAsStream( path/to/class );
```
Now if the class is not part of the JAR, and it isn't in the manifest's `Class-Path`, then the class loader won't find it. Instead, you can use the `URLClassLoader`, with some care to deal with differences between windows and Unix/Linux/MacOSX.
```
// the class to load
final String classAsPath = className.replace('.', '/') + ".class";
// the URL to the `app.jar` file (Windows and Unix/Linux/MacOSX below)
final URL url = new URL( "file", null, "///C:/Users/diffusive/app.jar" );
//final URL url = new URL( "file", null, "/Users/diffusive/app.jar" );
// create the class loader with the JAR file
final URLClassLoader urlClassLoader = new URLClassLoader( new URL[] { url } );
// grab the resource, through, this time from the `URLClassLoader` object
// rather than from the `ClassLoader` class
final InputStream input = urlClassLoader.getResourceAsStream( classAsPath );
```
In both examples you'll need to deal with the exceptions, and the fact that the input stream is `null` if the resource can't be found. Also, if you need to get the `InputStream` into a `byte[]`, you can use Apache's commons `IOUtils.toByteArray(...)`. And, if you then want a `Class`, you can use the class loader's `defineClass(...)` method, which accepts the `byte[]`.
You can find this code in a [`ClassLoaderUtils`](http://sourceforge.net/p/diffusive/code/ci/5168b7cc7015788bf54b1bddc370c71b144a1762/tree/src/org/microtitan/diffusive/utils/ClassLoaderUtils.java?format=raw) class in the Diffusive source code, which you can find on SourceForge at github.com/robphilipp/diffusive
And a method to create URL for Windows and Unix/Linux/MacOSX from relative and absolute paths in [`RestfulDiffuserManagerResource.createJarClassPath(...)`](https://github.com/robphilipp/diffusive/blob/develop/restful_server/src/main/java/org/microtitan/diffusive/diffuser/restful/resources/RestfulDiffuserManagerResource.java?source=c) | Load a resource contained in a jar | [
"",
"java",
"jar",
"resources",
""
] |
Let's get the duplication allegation out of the way.
I saw couple of variations of this question, notably, [link](https://stackoverflow.com/questions/15779/what-are-the-best-unknown-features-of-visual-studio-net-2005). However, it doesn't address issue specific to C# developers. I want to collect a list most used/powerful/cool tricks--tips in VS from people who are using C# under visual studio 2005 (it's ok to mention for 2008 as well). Below are the links that I have used as a guide:
[msdn](http://msdn.microsoft.com/en-us/library/bb245788(VS.80).aspx) <-- our guys from Microsoft have a tip or two to share
[Kirill's Visual Studio Tips](http://blogs.msdn.com/kirillosenkov/archive/2008/10/21/kirill-s-visual-studio-tips.aspx) <-- This blog also has couple of good links
*Debugging tips are also encouraged*
Thank for sharing your tips and increasing my productivity :)
**Some of my arsenal:**
* `Ctrl`+`-`, `Ctrl`+`+`, navigates back and forward where you've been recently
* `Ctrl`+`Shift`+`V`, which will cycle through your clipboard history
* `F12` to go to definition of variable.
* `Ctrl`+`K`, `Ctrl`+`C` to comment a block of text with // at the start
* `Ctrl`-`K`, `Ctrl`-`U` to uncomment a block of text with // at the start
* `Ctrl`+`/` to get to the find box.
* `Ctrl`+`I` for incremental search, `F3` to iterate
* Select an expression/variable in debug mode and type `Ctrl`+`D`, `Ctrl`+`Q` to open the quick watch window. | Have you seen [this blog](http://blogs.msdn.com/saraford/archive/tags/Visual+Studio+2008+Tip+of+the+Day/default.aspx)... and the [book "Microsoft Visual Studio Tips"](https://rads.stackoverflow.com/amzn/click/com/0735626405) that came from it? | Here is a site I just found last week
<http://scottcate.com/tricks/>
The #1 tip I have is go buy Resharper! | Tips and tricks for VS2005 specifically for C# developers | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"visual-studio-2005",
""
] |
Build vs. Buy... We've all been down this road... It seems like content management solutions need to be a tool that you keep inside the toolbox for some quick wins and they are only getting better. I could certainly look at building one, but by the time you get all the bells and whistles in there, it would have been cheaper to get one off the shelf...
I've searched [StackOverflow](https://stackoverflow.com/search?q=content+management) for some recommendations, but it appears that there really haven't been any highly rated ideas for ASP.NET implementations.
Don't get me wrong, PHP and mySQL certainly have their place, but there are some instances where you really have to stick with ASP.NET and SQL Server implementations due to other limitations. Both [Drupal](http://drupal.org/) and [WordPress](http://wordpress.org/) seem pretty cool, but I won't be able to get these setup and installed in the environments I have to work with.
What are the best ASP.NET CMS solutions out there? | I'd try a slightly more targeted search:
> [[asp.net] "content management"](https://stackoverflow.com/search?q=[asp.net]+%22content+management%22)
Filter it to just questions tagged "asp.net", and ensure that you're searching for the phrase Content Management, rather than the two words.
A lot of it comes down to your definition of "Content Management" really. I've spent the last 5 years working professionally with things like Microsoft's CMS, and recently a bit of MOSS Web Content Management, and before that on two or three bespoke CMS that we'd written for a publishing house, so I consider a CMS to be a complete site building tools, focused around publishing multiple types and styles of content.
On the opensource/free/cheap side I've looked at few recently and found the following:
* [N2 CMS](http://www.n2cms.com) - This is what I've settled on using, mainly because they have a working MVC implementation, and I want to learn that, but it's also the closest I've found to my definition of a CMS
* [Umbraco](http://www.umbraco.net/) - Close second, let down by the lack of MVCness at the time.
* [Graffiti CMS](http://graffiticms.com/) - Didn't really cut it with me as a CMS, more of a glorified blogging engine
* [DotNetNuke](http://www.dotnetnuke.com/) - VB, and I work in C#. Great if what you really want is a portal however.
Just my thoughts to back up the usual bland lists. | You might want to check out [Umbraco](http://www.umbraco.net/) - completely written in C#/.NET, with a very powerful programming API (using lots of XSLT for transformations).
They offer both a free community edition as well as commercial versions.
Marc | Content Management - ASP.NET Recommendations | [
"",
"asp.net",
"sql",
"content-management",
""
] |
((Answer selected - see Edit 5 below.))
I need to write a simple pink-noise generator in C#. The problem is, I've never done any audio work before, so I don't know how to interact with the sound card, etc. I do know that I want to stay away from using DirectX, mostly because I don't want to download a massive SDK just for this tiny project.
So I have two problems:
1. How do I generate Pink Noise?
2. How do I stream it to the sound card?
**Edit**: I *really* want to make a pink noise generator... I'm aware there are other ways to solve the root problem. =)
**Edit 2**: Our firewall blocks streaming audio and video - otherwise I'd just go to [www.simplynoise.com](http://www.simplynoise.com) as suggested in the comments. :(
**Edit 3**: I've got the generation of white-noise down, as well as sending output to the sound card - now all I need to know is how to turn the white-noise into pink noise. Oh - and I don't want to loop a wav file because every application I've tried to use for looping ends up with a tiny little break in between loops, which is jarring enough to have prompted me in this direction in the first place...
**Edit 4**: ... I'm surprised so many people have jumped in to very explicitly *not* answer a question. I probably would have gotten a better response if I lied about why I need pink noise... This question is more about how to generate and stream data to the sound card than it is about what sort of headphones I should be using. To that end I've edited out the background details - you can read about it in the edits...
**Edit 5**: I've selected Paul's answer below because the link he provided gave me the formula to convert white noise (which is easily generated via the random number generator) into pink noise. In addition to this, I used [Ianier Munoz's CodeProject entry "Programming Audio Effects in C#"](http://www.codeproject.com/KB/audio-video/cswavplayfx.aspx) to learn how to generate, modify, and output sound data to the sound card. Thank you guys for your help. =) | Maybe you can convert the C/C++ code here to C#:
<http://www.firstpr.com.au/dsp/pink-noise/>
The easiest way to get sound to the sound card is to generate a wav (spit out some hardcoded headers and then sample data). Then you can play the .wav file. | Pink noise is just white noise put through a -3dB/octave LPF. You can generate white noise using rand() (or any function that generates uniformly random numbers).
Streaming stuff to the soundcard is reasonably trivial, as long as you have Google handy. If you choose to avoid DirectX, consider using PortAudio or ASIO for interfacing with the soundcard... although I think you're gonna have to use C++ or C.
Other than that, why waste CPU time generating it? Loop a damn WAV file! | How can I make a Pink Noise generator? | [
"",
"c#",
".net",
"audio",
"noise",
""
] |
Looks like it's not.
If I convert the file name to its short value, then Process.Start() works.
```
Process runScripts = new Process();
runScripts.StartInfo.FileName = @"C:\long file path\run.cmd";
runScripts.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
runScripts.StartInfo.UseShellExecute = true;
runScripts.StartInfo.RedirectStandardOutput = false;
runScripts.Start();
```
The above code fails. But...
```
Process runScripts = new Process();
runScripts.StartInfo.FileName = @"C:\short\file\path\run.cmd";
runScripts.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
runScripts.StartInfo.UseShellExecute = true;
runScripts.StartInfo.RedirectStandardOutput = false;
runScripts.Start();
```
succeeds.
I managed to get around this by converting the long path name to a short path name.
But I am a bit surprised to find this.
Any reasons or background info on this?
Thanks.
**Update 1**
Microsoft .NET Framework Version 2.0.50727 | To reproduce your problem, I used the following program:
```
// file test.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
public class Test
{
public static int Main()
{
string error;
try {
ProcessStartInfo i = new ProcessStartInfo();
i.FileName = @"C:\long file path\run.cmd";
i.WindowStyle = ProcessWindowStyle.Hidden;
i.UseShellExecute = true;
i.RedirectStandardOutput = false;
using (Process p = Process.Start(i)) {
error = "No process object was returned from Process.Start";
if (p != null) {
p.WaitForExit();
if (p.ExitCode == 0) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
return 0;
}
error = "Process exit code was " + p.ExitCode;
}
}
}
catch (Win32Exception ex) {
error = "(Win32Exception) " + ex.Message;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Whooops: " + error);
Console.ResetColor();
return 1;
}
}
```
The code starts a new process (as per your code sample) and reports the different ways in which it may fail to execute. You can compile the program from command line:
```
c:\windows\Microsoft.NET\Framework\v2.0.50727\csc test.cs
```
(assuming test.cs is in the current directory; it will create test.exe in the same directory as test.cs)
As expected, when "C:\long file path\run.cmd" does not exist, the program fails with:
```
Whooops: (Win32Exception) The system cannot find the file specified
```
Now let's create a directory "C:\long file path" and put a very simple run.cmd in there:
```
rem file run.cmd
echo I ran at %Time% > "%~dp0\run.out.txt"
```
However, at this point I was unable to reproduce your failure. Once the above run.cmd is in place, test.exe runs successfully (i.e. run.cmd is executed correctly - you can verify this by looking for a newly created file "C:\long file path\run.out.txt".
I ran test.exe on Vista x64 (my main dev machine), Windows XP SP3 x86 (virtual machine), Windows Server 2008 x64 (virtual machine) and it works everywhere.
Could you try running the above code in your environment and report back whether it is failing for you? This way we will at least establish the same testing context (same .NET program will be trying to run the same batch file in the same location for you as it does for me). | It's curious, i reproduce the behavior, effectively, it doesn't execute as you stated, but modifying this, it worked:
```
System.Diagnostics.Process runScripts = new System.Diagnostics.Process();
runScripts.StartInfo.FileName = @"run.cmd";
// new
runScripts.StartInfo.WorkingDirectory = @"C:\long file path";
runScripts.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
runScripts.StartInfo.UseShellExecute = true;
runScripts.StartInfo.RedirectStandardOutput = false;
runScripts.Start();
``` | Does Process.StartInfo.FileName accept long file names? | [
"",
"c#",
""
] |
With GWT, we can write code in Java and have it translated to JavaScript code.
With Script#, we can write code in C# and have it translated to JavaScript code.
It sounds GWT and Script# will save web developers from suffering javascript pains. Then, why these tools haven't been dominant? Why still people dedicated to write javascript code? | Multiple reasons, and which one is most important differs from developer to deverloper. Here are two:
* Because JavaScript is a more nice/flexible/powerful/(insert adjective of choice here) language than Java/C#
* People don't trust the output generated by GWT/Script# | I can speak for only GWT, but here's the things that I think are holding it back:
* compile time (GWT takes a long time to compile, javascript changes are instant)
* learning new language (a lot of web developers don't know how to code java)
* FUD over leaky abstractions and compiler. People fear a compiler making javascript for them and the leaky abstractions thing. Both are just FUD in my opinion, but that's doesn't make it any less of a reason.
* people often don't understand where and how to use GWT and are put off by it because they try to wedge it into the wrong holes.
* There's a perception that GWT was created to allow back end developers to code javascript, but it's not the case at all.
* The whole idea of using VerticalPanels, HorizontalPanels, FlowPanels and FlexTables is foreign to people who have already learned how to lay things out in HTML.
* Google is bad at marketing. No offence GWT guys, but if it was marketed/showed off a bit better it would have taken off like hotcakes
* Lack of great widget libraries for GWT. The widgets that come with it by default are good, but we need a bit more. Libraries like GWT-ext aren't helping in my opinion, because they are just attempts to wrap javascript libraries in GWT, and don't take advantage of the power of coding in Java.
* Steep learning curve for web developers, because it's framework is more Swing like than HTML like.
I still use it in my day to day coding, but I've long accepted that it's not about to take off. | Why Haven't GWT- and Script#-style Frameworks Become Dominant? | [
"",
"javascript",
"gwt",
"code-generation",
"script#",
""
] |
I aim to have a similar Bar at the top as here: <http://www.keltainenporssi.fi/>
The colour of the current site is in red, while other sites are in black.
How would you reach my aim?
Perhaps by php?
The syntax in pseudo-code may be
```
if $site = A
use-styleA
if $site = B
use-styleB
else
use-FinalStyle
``` | Non-dynamic approach:
You can use a CSS rule for each site, like so:
```
/* site-one.css */
#top-nav li.site-one a {
color: red;
}
/* site-two.css */
#top-nav li.site-two a {
color: red;
}
/* site-three.css */
#top-nav li.site-three a {
color: red;
}
```
HTML:
```
<ul id="top-nav">
<li class="page-one"><a href="pages/one">Page one</a></li>
<li class="page-two"><a href="pages/two">Page two</a></li>
<li class="page-three"><a href="pages/three">Page three</a></li>
</ul>
``` | It is common to use a server-side script such as PHP to do such a thing. For example:
```
<?PHP
echo '<ul id="top-nav">';
foreach($page as $pageId => $text) {
echo '<li';
if($curPage == $pageId)
echo ' class="active"';
echo '>';
echo '<a href="pages/' . htmlspecialchars($pageId) . '">';
echo htmlspecialchars($text);
echo '</a>';
echo '</li>';
}
echo '</ul>';
?>
```
This would produce output like: *(Formatted for readability)*
```
<ul id="top-nav">
<li><a href="pages/home">Home</a></li>
<li class="active"><a href="pages/one">Page one</a></li>
<li><a href="pages/two">Page two</a></li>
</ul>
``` | Checking site and deciding then CSS style? | [
"",
"php",
"if-statement",
""
] |
How do I use php sessions in XSLT for example for making a shopping cart for a webshop?
A user can browse the site and click "Add to cart" on several items. Each item should then be stored in a session variable. The user can at all time view the items selected by clicking "View cart". | If you're using XSLT from within PHP, you can pass parameters to it by [`XSLTProcessor::setParameter()`](http://www.php.net/manual/en/xsltprocessor.setparameter.php). You'll have to declare that parameter in XSL with
```
<xsl:param name="«param name»"/>
```
For example...
PHP:
```
// $xsl, $xml -- DOMDocument objects
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
$proc->setParameter(''/*default namespace*/, 'test_param', $aValue);
$proc->setParameter('', 'session_name', session_name());
$proc->setParameter('', 'session_id', session_id());
echo $proc->transformToXML($xml);
```
XSL:
```
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="test_param"/>
<xsl:param name="session_name"/>
<xsl:param name="session_id"/>
<xsl:template match="/">
<p>Your test parameter is: <xsl:value-of select="$test_param"/></p>
<p>Your session name is: <xsl:value-of select="$session_name"/></p>
<p>Your session ID is: <xsl:value-of select="$session_id"/></p>
<p>
<a>
<xsl:attribute name="href">
<xsl:value-of select="concat('http://example.com/index.php?',$session_name,'=',$session_id)"/>
</xsl:attribute>
Link with session
</a>
</p>
</xsl:template>
</xsl:stylesheet>
``` | you're probably calling the xslt processor on some XML, why don't you just add the session data to that xml ? | How to use php sessions in xslt? | [
"",
"php",
"xslt",
"session",
""
] |
On the first click, it works as expected:
1. the class is changed
2. and the html content is changed from 'Show...' to 'Close...'
3. the content area is expanded with the slideDown effect,
Good so far.
On the second click, ...
1. the class changes
2. the html content is changed from 'Close...' to 'Show...'
3. The content area does NOT go away as expected.
On the third click, ...
1. the class is changed
2. the html content is changed
3. the already-shown content is re-shown with the slidedown effect.
So everything is working except for the 2nd click when the content is supposed to be hidden again.
Here's the jQuery:
-
```
$('.open_user_urls').live('click', function() {
$('#user_urls').slideDown('slow');
$(this).addClass('close_user_urls');
$(this).removeClass('open_user_urls');
$(this).html('Close Search History');
return false;
});
$('.close_user_urls').live('click', function() {
$('#user_urls').slideUp('slow');
$(this).addClass('open_user_urls');
$(this).removeClass('close_user_urls');
$(this).html('Show Search History');
return false;
});
```
Here's the HTML it's acting on:
```
<h3 class='open_user_urls'>Show Search History</h3>
<div id='user_urls'>
// an OL tag with content
</div>
```
And the only applicable CSS:
```
#user_urls { display: none; }
```
EDIT - I replaced my jquery code with functionally equivalent code supplied in an answer below, but the problem persists. So the cause must be elsewhere. I do recall this code working originally, but then it stopped. I'm stumped. Time to strip everything else out piece by piece...
EDIT 2 - Since the bug must be elsewhere, I'm accepting a code improvement for my jquery as the answer. Thanks.
Edit 3 - Found the source of the problem.
Inside the #user\_urls div I have an series of OLs with the following css:
```
.url_list {float: left; width: 285px; list-style-position: outside; margin-left: 25px;}
```
Each OL contains a list of 20 urls and is meant to display in as many multiple columns as required to display all the URLs.
Removing the float: left; on these OL tags causes the problem to go away.
So having a float on the content contained in the DIV thats showing and hiding is causing it not not hide at all. Why would this happen?
EDIT 4: Adding a inside the #user\_urls DIV allows the hiding action to work properly. | Perhaps something like this would be simpler?
```
$(".open_user_urls").toggle(
function () {
$(this).text("Close Search History").siblings(".user_urls").slideDown("slow");
},
function () {
$(this).text("Show Search History").siblings(".user_urls").slideUp("slow");
}
);
```
The toggle function is designed for precisely the scenario you're encountering. | To reiterate the problem and resolution to this question...
Inside the `#user_urls` `DIV` were a series of `OL` tags, each floated left. It was the float that was causing the problem.
Adding a `<br style='clear: left;' />` inside the `#user_urls` `DIV` fixed the problem. | jQuery Slide Toggle Not Working - Resolved | [
"",
"javascript",
"jquery",
""
] |
I'm thinking through all the points in my PHP application where it performs some sort of system process like database queries, or sending out an email, and I'm wondering if at all these points I should be notifying a user when something goes wrong. There are so many points where an application can fall apart, that I'm having trouble determining if it is worth it to notify the user. Is it better to have some sort of logging in place, where every few days I just monitor the logs? Is there a standard approach for large-scale applications? | You could probably use something like [log4php](http://logging.apache.org/log4php/), which is a php-based implementation of the famous [log4j](http://logging.apache.org/log4j/) library. You would then log messages whereever applicable using a 'severity'. Based on two factors - severity and category you configure 'where' and 'how' to log/process/display the messages thanks to the flexible appender system.
While i'm not sure if there is already a complete solution for php, you could for instance have non-severe errors logged to a database and diplayed by admininstration component within your application, while severe errors get sent to you by e-mail and im. | From a user perspective everything unexpected (that includes error messages prompts like "Are you sure" or similar) triggers the urge to get rid of it as soon as possible. Users don't read messages and likely won't notify you of problems, so overwhelming a user with technical details is in almost all cases the wrong way to go and you're usually better off with logging or perhaps an e-mail to you when something goes wrong.
As for the user, try to divide yuor failure cases into failures that can be mitigated by retrying and retry automatically before telling the user (but not endlessly) and failures that need administrative action or simply time to solve in which case a generic error message along with a more detailed log message for the developers should be best.
That is, if you're not assuming all your users are developers. | How do I decide if a failed system process like a database query or automated email merits an error message to the user? | [
"",
"php",
"unit-testing",
""
] |
Does anyone know of a free Ajax Dial control?
I'm looking for a speedometer, percentage etc control.
I'd expect to find loads of these as they seem to be in fashion at the moment in UI Design but I've yet to find any good looking free ones, and the only commercial one I've found costs $800 for a whole library of controls most of which I don't need.
**Update**
The context is to show a live (or as live as possible) measure of performance, I'm looking for it for a variety of applications, such as showing how close a team is to it's target etc. | There's the gauge from the Google Charts set, which you can animate:
<http://code.google.com/apis/ajax/playground/#gauge_interaction>
You'll have to plumb in your own Ajax-ness to retrieve the data - I believe the Google Web Toolkit can do the integration (never tried, just a guess) | Dojo has a great widget for exactly this, see [AnalogGauge](http://docs.dojocampus.org/dojox/widget/AnalogGauge) for usage examples. They can be updated on the fly as well. | Ajax Dial Control? | [
"",
"javascript",
"ajax",
"controls",
"charts",
""
] |
I'm using [proxool](http://proxool.sourceforge.net/) java connection pool (version 0.9.1). Everything works fine till I reach the maximum connection count. If the maximum connection count is reached proxool immediately throws an `SQLExcepion`:
```
java.sql.SQLException: Couldn't get connection because we are at maximum
connection count (n/n) and there are none available
```
Of course instead of `n` the maximum connection count is shown.
Why is proxool throwing an `SQLException` immediately instead of waiting for an available connection? Not forever of course, but a configurable timeout would be great.
I don't know if it important, but I'm using proxool in a Tomcat J2EE application. Parameters of proxool are defined in `context.xml` and I'm using [Proxool DataSource Support](http://proxool.sourceforge.net/datasource.html). | I was asking the question on the proxool mailing list and I got a quick, yet unfortunately negative [answer](http://sourceforge.net/mailarchive/forum.php?thread_name=b179a41c0903060630y7512fd26j5727fce6f14b4f97%40mail.gmail.com&forum_name=proxool-user).
Now there is no support for configurable (or any kind of) timeout, however there are plans to implement this feature. | I took a quick look at the source code and this looks like the standard behavior for ConnectionPool.getConnection. The [documentation](http://proxool.sourceforge.net/api-dev/org/logicalcobwebs/proxool/ConnectionPool.html#getConnection()) says the same thing.
There are other database pooling libraries (such as Apache DBCP and C3P0) but you'd have to do some refactoring to use them. The alternative is to wrap the getConnection method yourself (or modify the proxool source) and make it work the way you want. | Proxool maximum connection count | [
"",
"java",
"connection-pooling",
"proxool",
""
] |
I am currently working on some older java code that was developed without App Servers in mind. It is basically a bunch of "black box code" with an input interface, and an output interface. Everything in the "black box" classes are static Data Structures that contain state, which are put through algorithms at timed intervals (every 10 seconds). The black box is started from a main method.
To keep this easy for myself, I am thinking of making the "black box" a Singleton. Basically, anyone who wants to access the logic inside of the black box will get the same instance. This will allow me to use Message Driven beans as input to the black box, and a JMS Publisher of some sort as the output of the black box.
How bad of an idea is this? Any tips?
One of the main concerns I have though, is there may be Threads in the "black box" code that I am unaware of.
Is there such thing as "application scoped objects" in EJB?
Note: I am using Glassfish | If you use a simple singelton, **you will be facing problems once you enter a clustered environment**.
In such scenario, you have multiple classloaders on multiple JVMs, and your sinlgeton pattern **will** break as you will have several instances of that class.
The only acceptable use for a singleton in an app server (potentially in a clustered environment) is when you the singleton is totally state-less, and is only used as a convenience to access global data/functions.
I suggest checking your application server vendor's solution for this issue. Most, if not all vendors, supply some solution for requirements of your sort.
Specifically for Glassfish, which you say you are using, check out [**Singleton EJB support for Glassfish**](http://blogs.oracle.com/MaheshKannan/entry/singleton_ejb_support_in_glassfish). It might be as simple as adding a single annotation. | I would say that creating a singleton is actually the only viable idea. Assuming that code inside this "black box" is known to use static fields, it is absolutely unsafe to create two instances of this facade. Results are unpredictable otherwise. | Singleton in Java App Server.. How bad of an idea is this? | [
"",
"java",
"jakarta-ee",
"jboss",
"glassfish",
"ejb-3.0",
""
] |
I have the following query
```
DECLARE @userId INT
DECLARE @siteId INT
SET @siteId = -1
SET @userId = 1828
SELECT a.id AS alertId,
a.location_id,
a.alert_type_id,
a.event_id,
a.user_id,
a.site_id,
a.accepted_by
FROM alerts AS a
JOIN alert_types AS ats ON a.alert_type_id = ats.id
JOIN events AS tr ON a.event_id = tr.event_id
WHERE tr.end_Time IS null
AND tr.status_id = 0
AND ats.code = 'E'
AND a.site_id in (SELECT * FROM dbo.udf_get_event_sitelist(@siteId, @userId))
```
This query takes between 5 and 17 seconds to run, however under many circumstances the function dbo.udf\_get\_event\_sitelist(@siteId, @userId) returns no rows, so the query will not find any data.
How can I force SQL Server to execute the user defined function first. I appreciate that I could rewrite the query into a stored procedure and perform the sub-select first, however I would like to do it in a single SQL statement if possible. | make the "FROM" table the results set of the function and join the other tables to it
```
DECLARE @userId INT
DECLARE @siteId INT
SET @siteId = -1
SET @userId = 1828
SELECT a.id AS alertId,
a.location_id,
a.alert_type_id,
a.event_id,
a.user_id,
a.site_id,
a.accepted_by
FROM (SELECT * FROM dbo.udf_get_event_sitelist(@siteId, @userId)) dt
JOIN alerts AS a ON dt.site_id=a.site_id
JOIN alert_types AS ats ON a.alert_type_id = ats.id
JOIN events AS tr ON a.event_id = tr.event_id
WHERE tr.end_Time IS null
AND tr.status_id = 0
AND ats.code = 'E'
``` | you could select the results of udf\_get\_event\_sitelist into a table variable and only proceed with the big query if @@rowcount > 0 | How do I force SQL Server to execute a query in a particular order | [
"",
"sql",
"sql-server",
"query-optimization",
""
] |
From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc? | Actually, "signals" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the name has stuck.
Events are really signals, you might say! | Signals typically have an association with an operating system facility and events are typically application-defined. In some technology stacks, the OS-level stuff may be hidden well enough that there isn't a difference in the API, but in others perhaps not. | Why aren't signals simply called events? | [
"",
"python",
"signals",
"django-signals",
""
] |
What is the equivalent of a `static_cast` with `boost::shared_ptr`?
In other words, how do I have to rewrite the following
```
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);
```
when using `shared_ptr`?
```
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
``` | Use `boost::static_pointer_cast`:
```
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);
``` | There are three cast operators for smart pointers: `static_pointer_cast`, `dynamic_pointer_cast`, and `const_pointer_cast`. They are either in namespace `boost` (provided by `<boost/shared_ptr.hpp>`) or namespace `std::tr1` (provided either by Boost or by your compiler's TR1 implementation). | static_cast with boost::shared_ptr? | [
"",
"c++",
"boost",
"shared-ptr",
"static-cast",
""
] |
I need sphinx to sort the results by the sum of an attribute. I need to:
* Group the results by their IDs (done)
* Sort the results by the SUM of one attribute
I can't find a way to sum this attribute.
How could I do this?
(Im using sphinx PHP API) | Sphinx supports aggregate functions (sum, avg, min, max) since 0.9.9-rc2 version.
Check the documentation from [www.sphinxsearch.com/docs/current.html](http://www.sphinxsearch.com/docs/current.html) | Echoing the previous answer, it's just not possible to do within a Sphinx query. While [the expression syntax](http://sphinxsearch.com/docs/manual-0.9.8.html#sorting-modes) allows for some level of calculations in sorting, it doesn't have any aggregation functions. Unless you store that summed value as an attribute (which could be an option - calculate it during indexing), it's going to have to be a separate SQL query per record. | How to sum an attribute in a sphinx group search? | [
"",
"php",
"mysql",
"sorting",
"grouping",
"sphinx",
""
] |
I have a web.config file on my computer.
There are alot of things i need to change and add in the file.
*(I am actually working with my SharePoint web.config file)*
Can i do this with a Batch file, if so how would i do it.
Or how would i do it using VB.NET or C# code?
Any ideas guys?
Edit: i need to create a program to alter a web.config of lets say i web.config laying on my deskop and not the actual web.config of my project
Regards
Etienne | This is what i needed to do.......thanks for all the help!!!
```
// Read in Xml-file
XmlDocument doc = new XmlDocument();
doc.Load("C:/Web.config");
//SaveControl tag..........................................................
XmlNode n = doc.SelectSingleNode("/configuration/SharePoint/SafeControls");
XmlElement elemWeb = doc.CreateElement("SafeControl");
elemWeb.SetAttribute("Assembly", "SamrasWebOption4");
elemWeb.SetAttribute("Namespace", "SamrasWebOption4");
elemWeb.SetAttribute("TypeName", "*");
elemWeb.SetAttribute("Safe", "True");
XmlElement elemSmartPart = doc.CreateElement("SafeControl");
elemSmartPart.SetAttribute("Assembly", "Machine_Totals");
elemSmartPart.SetAttribute("Namespace", "Machine_Totals");
elemSmartPart.SetAttribute("TypeName", "*");
elemSmartPart.SetAttribute("Safe", "True");
//Appending the Nodes......................................................
n.AppendChild(elemWeb);
n.AppendChild(elemSmartPart);
//Saving the document......................................................
doc.Save("C:/Web.config");
``` | You can modify it from C# code, for example:
```
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
appSettingsSection.Settings["foo"].Value = "bar";
config.Save();
}
```
where foo is the key and bar the value of the key to set, obviously. To remove a value, use Settings.Remove(key);
See the [msdn documentation](http://msdn.microsoft.com/en-us/library/ms151456.aspx) for more information about the OpenWebConfiguration method and more. | Changing values in Web.config with a Batch file or in .NET code | [
"",
"c#",
".net",
"asp.net",
"vb.net",
"sharepoint",
""
] |
Sometimes, you want to test a class method and you want to do an expectation on a call of a super class method. I did not found a way to do this expectation in java using easymock or jmock (and I think it is not possible).
There is a (relative) clean solution, to create a delegate with the super class method logic and then set expectations on it, but I don't know why and when use that solution ¿any ideas/examples?
Thanks | Well, you can if you want to. I don't know if you are familiar with [JMockit](http://code.google.com/p/jmockit/), go check it out. The current version is 0.999.17 In the mean time, let's take a look at it...
Assume the following class hierarchy:
```
public class Bar {
public void bar() {
System.out.println("Bar#bar()");
}
}
public class Foo extends Bar {
public void bar() {
super.bar();
System.out.println("Foo#bar()");
}
}
```
Then, using JMockit in your `FooTest.java` you can validate that you're actually making a call to `Bar` from `Foo`.
```
@MockClass(realClass = Bar.class)
public static class MockBar {
private boolean barCalled = false;
@Mock
public void bar() {
this.barCalled = true;
System.out.println("mocked bar");
}
}
@Test
public void barShouldCallSuperBar() {
MockBar mockBar = new MockBar();
Mockit.setUpMock(Bar.class, mockBar);
Foo foo = new Foo();
foo.bar();
Assert.assertTrue(mockBar.barCalled);
Mockit.tearDownMocks();
}
``` | Expanding on @Cem Catikkas answer, using JMockit 1.22:
```
@Test
public void barShouldCallSuperBar() {
new MockUp<Bar>() {
@Mock
public void bar() {
barCalled = true;
System.out.println("mocked bar");
}
};
Foo foo = new Foo();
foo.bar();
Assert.assertTrue(mockBar.barCalled);
}
```
No need for the static class annotated with @MockClass, it is replaced by the MockUp class. | Can I mock a super class method call? | [
"",
"java",
"tdd",
"mocking",
"easymock",
"jmock",
""
] |
Is it possible to build a single mysql query (without variables) to remove all records from the table, except latest N (sorted by id desc)?
Something like this, only it doesn't work :)
```
delete from table order by id ASC limit ((select count(*) from table ) - N)
```
Thanks. | You cannot delete the records that way, the main issue being that you cannot use a subquery to specify the value of a LIMIT clause.
This works (tested in MySQL 5.0.67):
```
DELETE FROM `table`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `table`
ORDER BY id DESC
LIMIT 42 -- keep this many records
) foo
);
```
The intermediate subquery *is* required. Without it we'd run into two errors:
1. **SQL Error (1093): You can't specify target table 'table' for update in FROM clause** - MySQL doesn't allow you to refer to the table you are deleting from within a direct subquery.
2. **SQL Error (1235): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'** - You can't use the LIMIT clause within a direct subquery of a NOT IN operator.
Fortunately, using an intermediate subquery allows us to bypass both of these limitations.
---
Nicole has pointed out this query can be optimised significantly for certain use cases (such as this one). I recommend reading [that answer](https://stackoverflow.com/a/8303440/69713) as well to see if it fits yours. | I know I'm resurrecting quite an old question, but I recently ran into this issue, but needed something that **scales to large numbers well**. There wasn't any existing performance data, and since this question has had quite a bit of attention, I thought I'd post what I found.
The solutions that actually worked were the [Alex Barrett's double sub-query/`NOT IN`](https://stackoverflow.com/a/578926/143295) method (similar to [Bill Karwin's](https://stackoverflow.com/a/578905/143295)), and [Quassnoi's `LEFT JOIN`](https://stackoverflow.com/a/578884/143295) method.
Unfortunately both of the above methods create very large intermediate temporary tables and performance degrades quickly as the number of records **not** being deleted gets large.
What I settled on utilizes Alex Barrett's double sub-query (thanks!) but uses `<=` instead of `NOT IN`:
```
DELETE FROM `test_sandbox`
WHERE id <= (
SELECT id
FROM (
SELECT id
FROM `test_sandbox`
ORDER BY id DESC
LIMIT 1 OFFSET 42 -- keep this many records
) foo
);
```
It uses `OFFSET` to get the id of the **N**th record and deletes that record and all previous records.
Since ordering is already an assumption of this problem (`ORDER BY id DESC`), `<=` is a perfect fit.
It is much faster, since the temporary table generated by the subquery contains just one record instead of **N** records.
## Test case
I tested the three working methods and the new method above in two test cases.
Both test cases use 10000 existing rows, while the first test keeps 9000 (deletes the oldest 1000) and the second test keeps 50 (deletes the oldest 9950).
```
+-----------+------------------------+----------------------+
| | 10000 TOTAL, KEEP 9000 | 10000 TOTAL, KEEP 50 |
+-----------+------------------------+----------------------+
| NOT IN | 3.2542 seconds | 0.1629 seconds |
| NOT IN v2 | 4.5863 seconds | 0.1650 seconds |
| <=,OFFSET | 0.0204 seconds | 0.1076 seconds |
+-----------+------------------------+----------------------+
```
What's interesting is that the `<=` method sees better performance across the board, but actually gets better the more you keep, instead of worse. | SQL query: Delete all records from the table except latest N? | [
"",
"mysql",
"sql",
"sql-delete",
""
] |
What method do you use to get a compile time error when the database schema changes occur in an ASP.NET project?
For example, if you have a GridView bound to a DataSource, I can only get runtime errors when a schema change occurs, not a compile time error. Intellisense works fine on the code behind using datasets, LINQ, etc, but I cant seem to get a compile time error on an ASP.NET page when I change the schema.
Any advice? | Create a unit test that verifies the correctness of you data access layer, and make sure it covers all your DB-related code. Not everything can be caught at compile time... | One way I can think of easily achieving this behavior would be to databind to a dynamic DAL. There are some tools that can help do this DAL generation, I'd recommend taking a look at [SubSonic](http://subsonicproject.com/).
Once you have something like SubSonic in place you can bind to the resulting business objects. These business objects will automatically change in the case of a schema change in the database and this will break your binding code which will result in a compile time error.
**Update**
Assaf's recommendation to use Unit Tests is also a good idea. It doesn't solve your stated problem but it is definitely something that should be in place and is a great tool for flagging these type of problems. | How to get a compile time error when the database schema changes? | [
"",
"asp.net",
"sql",
"data-binding",
""
] |
I have a class called Player in the business layer of my web application.
Player class has fields PlayerID, CategoryID and CountryID
A function in Player Class calls a function in PlayerDB Class in the Data Access Layer which in turn calls a stored proc which returns data for PlayerID, CategoryID (foreign key to Category table) and CountryID(foreign key to Country table) from the Player table.
I now have a situation where I want to add Country Name and Country Image (url path) to the above call, returning the new fields from the Country table for each CountryID.
My question is, do I add the country name and country image as additional fields to the Player class or do I have new classes called Country(BLL) and CountryDB(DAL) and a new stored proc?
I want to do what is best practice rather than what may be the easiest way.
If it is relevant I am using ASP.NET, VB.NET and SQL2005.
As you can probably tell I am a newbie so forgive me if I have not used the correct terminology in my question. I hope you get the idea. | You could make a country class, and using object composition, make the country class a property of the player class.
```
Public Property Country() as BLL.Country
' etc
```
Then you'd call the methods like this:
```
Dim p as BLL.Player
a = p.Country.ID
b = p.Country.Name
c = p.Country.Image
d = p.ID
e = p.CategoryID
``` | Create a new class. If it makes sense as a separate logical entity then it should be it's own class. | When is it best to use a new class rather than add to an existing class | [
"",
"asp.net",
"sql",
"vb.net",
"class",
"class-design",
""
] |
I'm trying to retrieve a count of all unique values in a field.
Example SQL:
```
SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'
```
How can I do this kind of query inside of CodeIgniter?
I know I can use `$this->db->query()`, and write my own SQL query, but I have other requirements that I want to use `$this->db->where()` for. If I use `->query()` though I have to write the whole query myself. | ```
$record = '123';
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get('accesslog');
```
then
```
$query->num_rows();
```
should go a long way towards it. | try it out with the following code
```
function fun1()
{
$this->db->select('count(DISTINCT(accessid))');
$this->db->from('accesslog');
$this->db->where('record =','123');
$query=$this->db->get();
return $query->num_rows();
}
``` | CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query | [
"",
"php",
"mysql",
"codeigniter",
"distinct",
""
] |
In application frameworks I keep seeing frameworks that allow you to pass in multiple Int values (generally used in place of an enum) into a function.
For example:
```
public class Example
{
public class Values
{
public static final int ONE = 0x7f020000;
public static final int TWO = 0x7f020001;
public static final int THREE = 0x7f020002;
public static final int FOUR = 0x7f020003;
public static final int FIVE = 0x7f020004;
}
public static void main(String [] args)
{
// should evaluate just Values.ONE
Example.multiValueExample(Values.ONE);
// should evalueate just values Values.ONE, Values.THREE, Values.FIVE
Example.multiValueExample(Values.ONE | Values.THREE | Values.FIVE);
// should evalueate just values Values.TWO , Values.FIVE
Example.multiValueExample(Values.TWO | Values.FIVE);
}
public static void multiValueExample(int values){
// Logic that properly evaluates bitwise values
...
}
}
```
So what logic should exist in multiValueExample for me to properly evaluate multiple int values being passed in using the bitwise operator? | Your values should be powers of 2.
That way, you don't lose any information when you bitwise-OR them.
```
public static final int ONE = 0x01;
public static final int TWO = 0x02;
public static final int THREE = 0x04;
public static final int FOUR = 0x08;
public static final int FIVE = 0x10;
```
etc.
Then you can do this:
```
public static void main(String [] args) {
Example.multiValueExample(Values.ONE | Values.THREE | Values.FIVE);
}
public static void multiValueExample(int values){
if ((values & Values.ONE) == Values.ONE) {
}
if ((values & Values.TWO) == Values.TWO) {
}
// etc.
}
``` | As was already mentioned, consider use of enums instead of bit values.
According to [Effective Java 2](https://rads.stackoverflow.com/amzn/click/com/0321356683): *"Item 32: Use [EnumSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html) instead of bit fields"*
Usage of [EnumSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html) is quite effective for memory usage and very convenient.
Here is an example:
```
package enums;
import java.util.EnumSet;
import java.util.Set;
public class Example {
public enum Values {
ONE, TWO, THREE, FOUR, FIVE
}
public static void main(String[] args) {
// should evaluate just Values.ONE
Example.multiValueExample(EnumSet.of(Values.ONE));
// should evalueate just values Values.ONE, Values.THREE, Values.FIVE
Example.multiValueExample(EnumSet.of(Values.ONE, Values.THREE, Values.FIVE));
// should evalueate just values Values.TWO , Values.FIVE
Example.multiValueExample(EnumSet.of(Values.TWO, Values.FIVE));
}
public static void multiValueExample(Set<Values> values) {
if (values.contains(Values.ONE)) {
System.out.println("One");
}
// Other checks here...
if (values.contains(Values.FIVE)) {
System.out.println("Five");
}
}
}
``` | How to use a bitwise operator to pass multiple Integer values into a function for Java? | [
"",
"java",
"function",
"bit-manipulation",
"bitwise-operators",
"integer",
""
] |
What are the benefits/advantages of using delegates? Can anyone provide any simple examples? | They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.
Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:
```
var namesOfAdults = people.Where(person => person.Age >= 18)
.Select(person => person.Name);
```
(That can also be represented as a query expression, but let's not stray too far from delegates.)
Another way of thinking of a delegate is as a single-method interface type. For example, the `EventHandler` delegate type is a bit like:
```
public interface IEventHandler
{
void Invoke(object sender, EventArgs e)
}
```
But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.
For more on delegates and events, see [my article on the topic](http://pobox.com/~skeet/csharp/events.html). Its focus is events, but it covers delegates too. | This is a pretty vague topic, but here are a few things to consider -
Delegates are basically a cleaner, easier function pointer. Any place where function pointers were used in C++, you can think delegate.
**Advantages to using them in design:**
* Can lead to easy reuse of code
* Can provide a great amount of flexibility in your designs
* Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate `[Func<T,bool>]` to filter on, without having to write new code in the Where method
**Potential disadvantages:**
* They `~can~`, particularly if used naively, lead to code that is more difficult to read
* They can introduce behavior into your component that is unexpected, since 3rd party code out of your control will get called (For example, if somebody attaches a delegate to one of your events that causes an infinite loop, it can make your class look bad, even though it has nothing to do with you) | What are the advantages of delegates? | [
"",
"c#",
".net",
"delegates",
""
] |
I have four foreach loops that iterate through the collections and based on a condition do something.
Here is the code that I am writing now:
```
boolean breakFlag = false;
String valueFromObj2 = null;
String valueFromObj4 = null;
for(Object1 object1: objects){
for(Object2 object2: object1){
// I get some value from object2
valueFromObj2 = object2.getSomeValue();
for(Object3 object3 : object2){
for(Object4 object4: object3){
// Finally I get some value from Object4.
valueFromObj4 = object4.getSomeValue();
// Compare with valueFromObj2 to decide either to break all the foreach loop
breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );
if(breakFlag){break;}
} // fourth loop ends here
if(breakFlag){break;}
} // third loop ends here
if(breakFlag){break;}
} // second loop ends here
if(breakFlag){break;}
} // first loop ends here
```
The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable. | Use a label on the outermost loop, and include this label in the `break` statement when you want to jump out of all the loops. In the example below, I've modified your code to use the label `OUTERMOST`:
```
String valueFromObj2 = null;
String valueFromObj4 = null;
OUTERMOST: for(Object1 object1: objects){
for(Object2 object2: object1){
//I get some value from object2
valueFromObj2 = object2.getSomeValue();
for(Object3 object3 : object2){
for(Object4 object4: object3){
//Finally I get some value from Object4.
valueFromObj4 = object4.getSomeValue();
//Compare with valueFromObj2 to decide either to break all the foreach loop
if( compareTwoVariable(valueFromObj2, valueFromObj4 )) {
break OUTERMOST;
}
}//fourth loop ends here
}//third loop ends here
}//second loop ends here
}//first loop ends here
``` | Extract all the loops into the function and use return. | How do I break multiple foreach loops? | [
"",
"java",
"refactoring",
"foreach",
""
] |
HOW do i know when i need to dispose of something? Someone just mention i had several objects in my code that i need to dispose of. I had no idea i needed to dispose anything (this is my first week with C#). How do i know when i need to dispose an object? i was using <http://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithm.aspx> and i do not see any mention of dispose on the page or seen it mention in any other objs i was told i to dispose (by someone on SO).
I know i need to when something inherits IDisposable but HOW do i KNOW when it does inherit it? | You should dispose anything that implements IDisposable. Just wrap it on an using:
```
using(var some = new Something())
{
//use normally
}
``` | Similar questions here:
* [When should I dispose my objects in .NET?](https://stackoverflow.com/questions/245856/when-should-i-dispose-my-objects-in-net)
* [When should I manually dispose of controls? How do I know if a control implements IDisposable?](https://stackoverflow.com/questions/615466/when-should-i-manually-dispose-of-controls-how-do-i-know-if-a-control-implements)
* [How to dispose a class in .NET?](https://stackoverflow.com/questions/12368/how-to-dispose-a-class-in-net)
* [Will the GC call IDisposable.Dispose for me?](https://stackoverflow.com/questions/45036/will-the-gc-call-idisposable-dispose-for-me)
* [Identify IDisposable objects](https://stackoverflow.com/questions/591000/identify-idisposable-objects) | How do i know when i need to dispose an object? | [
"",
"c#",
"dispose",
""
] |
Recently I [asked a question](https://stackoverflow.com/questions/550374/checking-for-null-before-tostring) about how to clean up what I considered ugly code. One recommendation was to create an Extension Method that would perform the desired function and return back what I wanted. My first thought was 'Great! How cool are Extensions...' but after a little more thinking I am starting to have second thoughts about using Extensions...
My main concern is that it seems like Extensions are a custom 'shortcut' that can make it hard for other developers to follow. I understand using an Extension can help make the code syntax easier to read, but what about following the voice behind the curtain?
Take for example my previous questions code snippet:
```
if (entry.Properties["something"].Value != null)
attribs.something = entry.Properties["something"].Value.ToString();
```
Now replace it with an Extension:
```
public static class ObjectExtensions
{
public static string NullSafeToString(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
}
```
and call using the syntax:
```
attribs.something = entry.Properties["something"].Value.NullSafeToString();
```
Definetely a handy way to go, but is it really worth the overhead of another class object? And what happens if someone wants to reuse my code snippet but doesn't understand Extension? I could have just as easily used the syntax with the same result:
```
attribs.something = (entry.Properties["something"].Value ?? string.Empty).ToString()
```
So I did a little digging and found a couple of articles that talked about the pros/cons of using Extensions. For those inclined have a look at the following links:
[MSDN: Extension Methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)
[Extension Methods Best Practice](http://blogs.msdn.com/vbteam/archive/2007/03/10/extension-methods-best-practices-extension-methods-part-6.aspx)
[Extension Methods](http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx)
I can't really decide which is the better way to go. Custom Extensions that do what I want them to do or more displayed code to accomplish the same task? I would be really interested in learning what 'real' developers think about this topic... | Personally I think the "problems" of extension method readability are vastly overstated. If you concentrate on making your code easy to read in terms of *what* it's doing, that's more important most of the time than *how* it's doing it. If the developer wants to trace through and find out what's actually happening behind the scenes, they can always click through to the implementation.
My main problem with extension methods is their discovery method - i.e. via a specified namespace instead of a specified class. That's a different matter though :)
I'm not suggesting that you put in extension methods arbitrarily, but I would seriously consider how often you need to know how every expression in a method works vs skimming through it to see what it does in broader terms.
EDIT: Your use of terminology may be misleading you slightly. There's no such thing as an "extension object" - there are only "extension methods" and they have to exist in static types. So you may need to introduce a new *type* but you're not creating any more *objects*. | [OP] Definetely a handy way to go, but is it really worth the overhead of another class object?
No extra class object is created in this scenario. Under the hood, extension methods are called no differently than a static method. There is an extra metadata entry for the extension method container but that is pretty minimal.
[OP] And what happens if someone wants to reuse my code snippet but doesn't understand Extension Objects?
Then it would be a good time to educate them :). Yes, there is the risk that a new developer may not be comfortable with extension methods to start. But this is hardly an isolated feature. It's being used more and more in all of the code samples I'm seeing internally and on the web. It's something that is definitely worth while for a developer to learn. I don't think it fits into the category of "to esoteric to expect people to know" | Using Extensions: Weighing The Pros vs Cons | [
"",
"c#",
"extension-methods",
""
] |
What is wrong with using `delete` instead of `delete[]`?
Is there something special happening under the covers for allocating and freeing arrays?
Why would it be different from `malloc` and free? | Objects created with `new[]` must use `delete[]`. Using `delete` is undefined on arrays.
With malloc and free you have a more simple situation. There is only 1 function that frees the data you allocate, there is no concept of a destructor being called either. The confusion just comes in because `delete[]` and delete look similar. Actually they are 2 completely different functions.
Using delete won't call the correct function to delete the memory. It should call `delete[](void*)` but instead it calls `delete(void*)`. For this reason you can't rely on using `delete` for memory allocated with `new[]`
[See this C++ FAQ](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13)
> [16.13] Can I drop the `[]` when
> deleteing array of some built-in type
> (char, int, etc)?
>
> No!
>
> Sometimes programmers think that the
> `[]` in the `delete[] p` only exists so
> the compiler will call the appropriate
> destructors for all elements in the
> array. Because of this reasoning, they
> assume that an array of some built-in
> type such as `char` or `int` can be
> `delete`d without the `[]`. E.g., they
> assume the following is valid code:
>
> ```
> void userCode(int n) {
> char* p = new char[n];
> ...
> delete p; // ← ERROR! Should be delete[] p !
> }
> ```
>
> But the above code is wrong, and it
> can cause a disaster at runtime. In
> particular, the code that's called for
> `delete p` is `operator delete(void*)`,
> but the code that's called for
> `delete[] p` is `operator
> delete[](void*)`. The default behavior
> for the latter is to call the former,
> but users are allowed to replace the
> latter with a different behavior (in
> which case they would normally also
> replace the corresponding new code in
> operator `new[](size_t)`). If they
> replaced the `delete[]` code so it
> wasn't compatible with the delete
> code, and you called the wrong one
> (i.e., if you said `delete p` rather
> than `delete[] p`), you could end up
> with a disaster at runtime.
**Why does `delete[]` exist in the first place?**
Whether you do x or y:
```
char * x = new char[100];
char * y = new char;
```
Both are stored in `char *` typed variables.
I think the reason for the decision of `delete`, and `delete[]` goes along with a long list of decisions that are in favor of efficiency in C++. It is so that there is no enforced price to do a lookup of how much needs to be deleted for a normal delete operation.
Having 2 `new` and `new[]` seems only logical to have `delete` and `delete[]` anyway for symmetry. | The difference is that `delete` will only delete the entire memory range, but will only call the destructor for 1 object. `delete[]` will both delete the memory and call the destructor for every single object. If you do not use `delete[]` for arrays, it's only a matter of time before you introduce a resource leak into your application.
**EDIT** Update
According to the standard, passing an object allocated with `new[]` to `delete` is undefined. The **likely** behavior is that it will act as I described. | Why is there a special new and delete for arrays? | [
"",
"c++",
"arrays",
"memory-management",
"new-operator",
""
] |
I'm writing a test for a piece of code that has an IOException catch in it that I'm trying to cover. The try/catch looks something like this:
```
try {
oos = new ObjectOutputStream(new FileOutputStream(cacheFileName));
} catch (IOException e) {
LOGGER.error("Bad news!", e);
} finally {
```
The easiest way seems to make FileOutputStream throw a FileNotFoundException, but perhaps I'm going about this all the wrong way.
Anyone out there have any tips? | From your comment:
> Yes, I suppose the question should
> really have been "How do I create a
> file that does not exist on both Linux
> and Windows?" On windows, I can use
> 'new File("X:/")', where X: is a drive
> letter that does not exist. On Linux,
> this does not work because that is a
> valid file name.
Look at java.io.File.createTempFile. Use it to create the file and then delete it.
Probably pass it something like:
```
File tempFile;
tempFile = createTempFile(getClass().getName(),
Long.toString(System.currentTimeMillis());
tempFile.delete();
```
That should give you a unique name in a platform indendent manner that you can safely use without (much) fear of it existing. | You could set `cacheFileName` to an invalid name or to one you know doesn't exist. | Forcing FileNotFoundException | [
"",
"java",
"junit",
"testing",
"ioexception",
"filenotfoundexception",
""
] |
I'm trying to write an encrpytion using the OTP method. In keeping with the security theories I need the plain text documents to be stored only in memory and never ever written to a physical drive. The tmpnam command appears to be what I need, but from what I can see it saves the file on the disk and not the RAM.
Using C++ is there any (platform independent) method that allows a file to exist only in RAM? I would like to avoid using a RAM disk method if possible.
Thanks
Edit:
Thanks, its more just a learning thing for me, I'm new to encryption and just working through different methods, I don't actually plan on using many of them (esspecially OTP due to doubling the original file size because of the "pad").
If I'm totally honest, I'm a Linux user so ditching Windows wouldn't be too bad, I'm looking into using RAM disks for now as FUSE seems a bit overkill for a "learning" thing. | The simple answer is: no, there is no platform independent way. Even keeping the data only in memory, it will still risk being swapped out to disk by the virtual memory manager.
On Windows, you can use **VirtualLock()** to force the memory to stay in RAM. You can also use **CryptProtectMemory()** to prevent other processes from reading it.
On POSIX systems (e.g. BSD, Linux) you can use `mlock()` to lock memory in RAM. | Not really unless you count in-memory streams (like stringstream).
No especially and specifically for security purposes: any piece of data can be swapped to disk on virtual memory systems.
Generally, if you are concerned about security, you have to use platform-specific methods for controlling access: What good is keeping your data in RAM if everyone can read it? | Temp file that exists only in RAM? | [
"",
"c++",
"temporary-files",
"ram",
"one-time-password",
""
] |
I am trying to create a graphical spectrum analyzer in python.
I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.
I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents. This is what the array looks like after I preform an fft on my array using numpy:
```
[ -3.37260500e+05 +0.00000000e+00j 7.11787022e+05 +1.70667403e+04j
4.10040193e+05 +3.28653370e+05j 9.90933073e+04 +1.60555003e+05j
2.28787050e+05 +3.24141951e+05j 2.09781047e+04 +2.31063376e+05j
-2.15941453e+05 +1.63773851e+05j -7.07833051e+04 +1.52467334e+05j
-1.37440802e+05 +6.28107674e+04j -7.07536614e+03 +5.55634993e+03j
-4.31009964e+04 -1.74891657e+05j 1.39384348e+05 +1.95956947e+04j
1.73613033e+05 +1.16883207e+05j 1.15610357e+05 -2.62619884e+04j
-2.05469722e+05 +1.71343186e+05j -1.56779748e+04 +1.51258101e+05j
-2.08639913e+05 +6.07372799e+04j -2.90623668e+05 -2.79550838e+05j
-1.68112214e+05 +4.47877871e+04j -1.21289916e+03 +1.18397979e+05j
-1.55779104e+05 +5.06852464e+04j 1.95309737e+05 +1.93876325e+04j
-2.80400414e+05 +6.90079265e+04j 1.25892113e+04 -1.39293422e+05j
3.10709174e+04 -1.35248953e+05j 1.31003438e+05 +1.90799303e+05j...
```
I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars. Also, should I be averaging the 2 channels together? | The array you are showing is the Fourier Transform coefficients of the audio signal. These coefficients can be used to get the frequency content of the audio. The FFT is defined for complex valued input functions, so the coefficients you get out will be imaginary numbers even though your input is all real values. In order to get the amount of power in each frequency, you need to calculate the magnitude of the FFT coefficient for each frequency. This is **not** just the real component of the coefficient, you need to calculate the square root of the sum of the square of its real and imaginary components. That is, if your coefficient is a + b\*j, then its magnitude is sqrt(a^2 + b^2).
Once you have calculated the magnitude of each FFT coefficient, you need to figure out which audio frequency each FFT coefficient belongs to. An N point FFT will give you the frequency content of your signal at N equally spaced frequencies, starting at 0. Because your sampling frequency is 44100 samples / sec. and the number of points in your FFT is 256, your frequency spacing is 44100 / 256 = 172 Hz (approximately)
The first coefficient in your array will be the 0 frequency coefficient. That is basically the average power level for all frequencies. The rest of your coefficients will count up from 0 in multiples of 172 Hz until you get to 128. In an FFT, you only can measure frequencies up to half your sample points. Read these links on the [Nyquist Frequency](http://mathworld.wolfram.com/NyquistFrequency.html "MathWorld: Nyquist Frequency") and [Nyquist-Shannon Sampling Theorem](http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem "Wikipedia: Nyquist-Shannon Sampling Theorem") if you are a glutton for punishment and need to know why, but the basic result is that your lower frequencies are going to be replicated or [aliased](http://en.wikipedia.org/wiki/Aliasing "Wikipedia: Aliasing") in the higher frequency buckets. So the frequencies will start from 0, increase by 172 Hz for each coefficient up to the N/2 coefficient, then decrease by 172 Hz until the N - 1 coefficient.
That should be enough information to get you started. If you would like a much more approachable introduction to FFTs than is given on Wikipedia, you could try [Understanding Digital Signal Processing: 2nd Ed.](https://rads.stackoverflow.com/amzn/click/com/0131089897 "Amazon: Understanding Digital Signal Processing: 2nd Ed."). It was very helpful for me.
So that is what those numbers represent. Converting to a percentage of height could be done by scaling each frequency component magnitude by the sum of all component magnitudes. Although, that would only give you a representation of the relative frequency distribution, and not the actual power for each frequency. You could try scaling by the maximum magnitude possible for a frequency component, but I'm not sure that that would display very well. The quickest way to find a workable scaling factor would be to experiment on loud and soft audio signals to find the right setting.
Finally, you should be averaging the two channels together if you want to show the frequency content of the entire audio signal as a whole. You are mixing the stereo audio into mono audio and showing the combined frequencies. If you want two separate displays for right and left frequencies, then you will need to perform the Fourier Transform on each channel separately. | Although this thread is years old, I found it very helpful. I just wanted to give my input to anyone who finds this and are trying to create something similar.
As for the division into bars this should not be done as antti suggest, by dividing the data equally based on the number of bars. The most useful would be to divide the data into octave parts, each octave being double the frequency of the previous. (ie. 100hz is one octave above 50hz, which is one octave above 25hz).
Depending on how many bars you want, you divide the whole range into 1/X octave ranges.
Based on a given center frequency of A on the bar, you get the upper and lower limits of the bar from:
```
upper limit = A * 2 ^ ( 1 / 2X )
lower limit = A / 2 ^ ( 1 / 2X )
```
To calculate the next adjoining center frequency you use a similar calculation:
```
next lower = A / 2 ^ ( 1 / X )
next higher = A * 2 ^ ( 1 / X )
```
You then average the data that fits into these ranges to get the amplitude for each bar.
For example:
We want to divide into 1/3 octaves ranges and we start with a center frequency of 1khz.
```
Upper limit = 1000 * 2 ^ ( 1 / ( 2 * 3 ) ) = 1122.5
Lower limit = 1000 / 2 ^ ( 1 / ( 2 * 3 ) ) = 890.9
```
Given 44100hz and 1024 samples (43hz between each data point) we should average out values 21 through 26. ( 890.9 / 43 = 20.72 ~ 21 and 1122.5 / 43 = 26.10 ~ 26 )
(1/3 octave bars would get you around 30 bars between ~40hz and ~20khz).
As you can figure out by now, as we go higher we will average a larger range of numbers. Low bars typically only include 1 or a small number of data points. While the higher bars can be the average of hundreds of points. The reason being that 86hz is an octave above 43hz... while 10086hz sounds almost the same as 10043hz. | Analyze audio using Fast Fourier Transform | [
"",
"python",
"audio",
"signal-processing",
"fft",
"spectrum",
""
] |
I have a script where I need to get three parts out of a text string, and return them in an array. After a couple of trying and failing I couldn't get it to work.
The text strings can look like this:
```
Some place
Some place (often text in parenthesis)
Some place (often text in parenthesis) [even text in brackets sometimes]
```
I need to split these strings into three:
```
{Some place} ({often text in parenthesis}) [{even text i brackets sometimes}]
```
Which should return:
```
1: Some place
2: often text in parenthesis
3: even text in brackets sometimes
```
I know this should be an easy task, but I couldn't solve the correct regular expression. This is to be used in PHP.
Thanks in advance! | Try something like this:
```
$result = preg_match('/
^ ([^(]+?)
(\s* \( ([^)]++) \))?
(\s* \[ ([^\]]++) \])?
\s*
$/x', $mystring, $matches);
print_r($matches);
```
Note that in this example, you will probably be most interested in $matches[1], $matches[3], and $matches[5]. | Split the problem into three regular expressions. After the first one, where you get every character before the first parenthesis, save your position - the same as the length of the string you just extracted.
Then in step two, do the same, but grab everything up to the closing parenthesis. (Nested parentheses make this a little more complicated but not too much.) Again, save a pointer to the end of the second string.
Getting the third string is then trivial. | Match words then match potentially parenthetical string, then match potential square braced string | [
"",
"php",
"regex",
""
] |
I have a class Request.cs
It has an abstract method:
```
public abstract Response CreateResponse(XmlReader reader);
```
and there's also a method:
```
public Response SendRequest(string requestURI)
{
...
XmlReader reader = XmlReader.Create(responseStream);
return CreateResponse(reader);
}
```
The `CreateResponse method` is implemented in a subclass that extends `Request`. And that implementation returns response.
I don't understand how you can return a method like this that's an abstract method but the value returned is actually in the implementation of the method from the subclass. Is this an example of the [Template Method pattern](http://en.wikipedia.org/wiki/Template_pattern) or just simple polymorphism, or is this "tricky or too savvy" code or even messy? I'm trying to figure out how this can even be done (is this basic OOP principal or design pattern) and is this a good practice or good use of OOP? | Yes, this is template method. Since the Response class is abstract, you are forced to implement CreateResponse before you can call SendRequest. This way, the common logic is encapsulated in the base class and the rest of the logic can vary as needed (by creating multiple implementations of the base class). | This is a very standard approach. In fact it's often recommended. The `CreateResponse` method is like a blank that has to be filled in by the derived class. | What is this? Template method or what? | [
"",
"c#",
"design-patterns",
"oop",
""
] |
I have a textarea html element on my page that gets reloaded via ajax. The whole textarea is returned each time not just its content, and the content grows over time. Along with the textarea i return the following piece of javascript:
```
<script type="text/javascript" >
var textArea = document.getElementById('outputTextResultsArea');
textArea.scrollTop = textArea.scrollHeight;
</script>
```
In firefox 3.0.7 this places the scroll bar at the bottom of the textArea, allowing me to see the latest of the output. However in IE 7 i see different behaviour. The scrollbar moves down with the content as intended, but once the content is greater then the textarea height the scroll bar no longer moves down. It seems as if IE is remembering the original scroll height of the element, not the new height.
I am using the xhtml transitional doctype if that helps. Also if this can be achieved with jQuery that would be fine as I have access to that.
Thanks in advance
Neil | As a quick hack you can just do this:
```
textArea.scrollTop = 99999;
```
Another option is to try it in a timer:
```
setTimeout(function()
{
var textArea = document.getElementById('outputTextResultsArea');
textArea.scrollTop = textArea.scrollHeight;
}, 10);
``` | Using jQuery, $("textarea").scrollHeight(99999) works great on Firefox and Chrome but not on IE. It appears to set it to the max number of lines in the textarea, whereas scrollHeight is supposed to be the number of pixels. (Awesome show great job IE). This appears to work though:
```
$("textarea").scrollTop(99999)
$("textarea").scrollTop($("textarea").scrollTop()*12)
```
I think this assumes a 12px font-height. I would love to find a more robust/straightforward way to do this. | Dynamically Scrolling a Textarea | [
"",
"javascript",
"ajax",
"xhtml",
"textarea",
""
] |
I'm using Visual Studio 2008 Professional Edition.
I wrote an application for Windows Mobile and I would like to create the installer for this application. How does it do? | You'll need to package your application up in a CAB file.
To do this is quite easy - you just create a new "Smart Device CAB Project" (New Projet->Other project types->Setup and Deployment).
To start with - specify that you want the output from your application's exe project to go in the Application Directory, along with any other dependent dlls.
You may also want to create an icon for your application by right clicking File System On Target Machine, selecting Add Special Folder->Start Menu Folder, then right clicking again in the Start Menu Folder and selecting Create New Shortcut. Now point this shortcut at the exe for your application.
Depending on the requirements of your project, it may also be desirable to create a desktop installer (msi file) that your users can run directly on their Windows PC, which instructs ActiveSync to install your cab file automatically when the Windows Mobile device is next plugged in. Basically this is done by calling ActiveSync (CeAppMgr.exe) from the command line and passing it an ini file referencing your cab file.
If you need to do anything else more complex during your installation, it is also possible to write a "custom action" where the cab file calls out to another dll (written by you) to execute any additional steps that need to happen during the install.
A comprehensive guide to all the above is available [here](http://msdn.microsoft.com/en-us/library/aa446504.aspx) | A tool like [Mobile Packager](http://www.mobilepackager.com) (www.MobilePackager.com) can also be used to create installation packages for Windows Mobile. It allows you to create very slick installers for installation via desktop or on device installation.
[](https://i.stack.imgur.com/xeIR9.jpg)
(source: [mobilepackager.com](http://www.mobilepackager.com/images/Screen_Device.jpg))
Check it out | VS2008, Windows Mobile Installer project | [
"",
"c#",
".net-3.5",
"windows-mobile",
"installation",
""
] |
Say I have a string coming in, `"2007-02-28"`, what's the simplest code I could write to turn that into `"2007-03-01"`? Right now I'm just using `strtotime()`, then adding `24*60*60`, then using `date()`, but just wondering if there is a cleaner, simpler, or more clever way of doing it. | A clean way **is** to use `strtotime()`
```
$date = strtotime("+1 day", strtotime("2007-02-28"));
echo date("Y-m-d", $date);
```
Will give you the 2007-03-01 | It's cleaner and simpler to add 86400. :)
The high-tech way is to do:
```
$date = new DateTime($input_date);
$date->modify('+1 day');
echo $date->format('Y-m-d');
```
but that's really only remotely worthwhile if you're doing, say, a sequence of transformations on the date, rather than just finding tomorrow. | Simplest way to increment a date in PHP? | [
"",
"php",
"datetime",
"date",
"strtotime",
"date-manipulation",
""
] |
Help me to implement an event, which handler can cancel it.
```
public class BuildStartEventArgs : EventArgs
{
public bool Cancel { get; set; }
}
class Foo
{
public event EventHandler<BuildStartEventArgs> BuildStart;
private void Bar()
{
// build started
OnBuildStart(new BuildStartEventArgs());
// how to catch cancellation?
}
private void OnBuildStart(BuildStartEventArgs e)
{
if (this.BuildStart != null)
{
this.BuildStart(this, e);
}
}
}
``` | You need to modify this code:
```
private void Bar()
{
// build started
OnBuildStart(new BuildStartEventArgs());
// how to catch cancellation?
}
```
to something like this:
```
private void Bar()
{
var e = new BuildStartEventArgs();
OnBuildStart(e);
if (!e.Cancel) {
// Do build
}
}
```
Classes in .NET have reference semantics, so you can see any changes made to the object the parameter of the event references. | Your `BuildStartEventArgs` are redundant, the framework already offers the [`CancelEventArgs`](http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.aspx) class – consider using it. | How to implement an event which can be canceled? | [
"",
"c#",
".net",
"events",
""
] |
What the question title says. With a query such as `SELECT @@IDENTITY AS ins_id`, do I need to supply the table name or any other info to specify which table/database i'm talking about? | [`@@IDENTITY`](http://msdn.microsoft.com/en-us/library/ms187342.aspx) returns the most recent identity generated in the current session. In most cases you'll probably want to use [`SCOPE_IDENTITY`](http://msdn.microsoft.com/en-us/library/ms190315.aspx) instead, which returns the most recent identity generated in the current scope.
For example, if you insert a row into *table1*, but that insert fires a trigger which inserts a row into *table2*, then `@@IDENTITY` will return the identity from *table2* whereas `SCOPE_IDENTITY` will return the identity from *table1*.
```
INSERT INTO my_table (my_column) VALUES ('test')
-- return the identity of the row you just inserted into my_table
-- regardless of any other inserts made by triggers etc
SELECT SCOPE_IDENTITY() AS ins_id
``` | No; it works much like SELECT LAST\_INSERT\_ID() in mysql, retrieving the last identity value inserted. You may want to take a look at [this in-depth examination](http://www.kamath.com/tutorials/tut007_identity.asp) for more on what you might want to be concerned about with it. | How to get Insert id in MSSQL in PHP? | [
"",
"php",
"sql-server",
""
] |
I am using Environment.GetLogicalDrives(); to get a list of drives. I remember in c++ i could use GetDriveType to find if the device was CD, removable, flash, etc and i am thinking i want to put a filter in my app to only show CD and removable on default. What is the GetDriveType equivalent in C#? google only showed me hacks to use the c++ call. | Yes, the framework includes a [DriveType](http://msdn.microsoft.com/en-us/library/system.io.drivetype.aspx) enumeration used by the [DriveInfo](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx) class. Have a look at the [GetDrives()](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives.aspx) method on MSDN. | You can use the [DriveInfo type](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx) to retrieve a list of the drives. You need to check the [DriveType property](http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx) (enum)
```
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(drive.Name);
}
}
```
You can also use LINQ-to-Objects to query the drives:
```
var drives = from drive in DriveInfo.GetDrives()
where drive.DriveType == DriveType.Removable
select drive;
foreach(var drive in drives)
{
Console.WriteLine(drive.Name);
}
```
Like the @TheCodeKing mentioned you can also use WMI to query drive information.
For example, you can query for USB sticks in the following manner:
```
ManagementObjectCollection drives = new ManagementObjectSearcher(
"SELECT Caption, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"
).Get();
```
Add a reference to the System.Management assembly if you are going to use WMI.
If you want to fill a ComboBox in a Windows Forms application with this data you need to bind the results to the ComboBox control.
For example:
```
private void Form1_Load(object sender, EventArgs e)
{
var drives = from drive in DriveInfo.GetDrives()
where drive.DriveType == DriveType.Removable
select drive;
comboBox1.DataSource = drives.ToList();
}
```
To recapitulate:
1. Add a ComboBox control to the Windows Form (drag & drop it on the form from the Toolbox)
2. Query the removable drives.
3. Bind the results to the ComboBox. | GetDriveType in C#? or find out if my drive is removable? | [
"",
"c#",
"removable-storage",
"getdrivetype",
""
] |
I have found out (in a hard way) that a collection that is being enumerated cannot be modified within "Foreach" statement
> "Collection was modified; enumeration operation may not execute."
Now, the solution I came up with is to create a dummy collection of the same size that contains a dictionary key and enumerate over it to modify collection in question.
```
private void InvalidateAuthenticatedNodes()
{
var dummy = new Dictionary<int, bool>(_AuthenticatedNodes.Count);
foreach (var nodeId in _AuthenticatedNodes.Keys)
dummy[nodeId] = false;
foreach (var nodeId in dummy.Keys)
_AuthenticatedNodes[nodeId] = false;
ClearAuthenticatedDateTime();
}
```
Above code worked fine; I was in process of refactoring above code to use a Func delegate to return a copy of keys as following
```
private void InvalidateAuthenticatedNodes()
{
var getNodeIds =
new Func<Dictionary<int, bool>, IEnumerable<int>>(
nodes => nodes.Select(node => node.Key));
foreach (var nodeId in getNodeIds(_AuthenticatedNodes))
{
_AuthenticatedNodes[nodeId] = false;
}
ClearAuthenticatedDateTime();
}
```
Unlike what I have expected, *getNodeIds* does not return a copy.
Is there a way to return a copy instead?
**\*EDIT**: Temporary Result before [JaredPar's answer](https://stackoverflow.com/questions/615310/how-do-you-return-a-copy-of-original-listt-from-funct-tresult/615314#615314)
Similar to JaredPar's answer but his was more concise and I went with his answer.
But here is the similar result I came up with to share.
```
private void InvalidateAuthenticatedNodes()
{
var getNodeIds =
new Func<Dictionary<int, bool>, IEnumerable<int>>(nodes =>
nodes.Select(node => node.Key));
foreach (var nodeId in getNodeIds(_AuthenticatedNodes).ToList())
{
_AuthenticatedNodes[nodeId] = false;
}
ClearAuthenticatedDateTime();
}
```
**\*EDIT**: Final Result (refined)
```
_AuthenticatedNodes.Keys.ToList().ForEach(
nodeId => _AuthenticatedNodes[nodeId] = false);
``` | Just add a .ToList() to the end of the collection and it will automagically return a complete copy of the list.
```
foreach (var nodeId in _AuthenticatedNodes.Keys.ToList())
...
``` | Instead of using a foreach, you could use a normal for. However, be careful when adding/removing items, it changes the indexes of the elements inside the collection. | How do you return a copy of original List<T> from Func<T, TResult>? | [
"",
"c#",
"linq",
"delegates",
".net-3.5",
"c#-3.0",
""
] |
I've been struggling with doing some relatively straightforward regular expression matching in Java 1.4.2. I'm much more comfortable with the Perl way of doing things. Here's what's going on:
I am attempting to match /^<foo>/ from "<foo><bar>"
I try:
```
Pattern myPattern= Pattern.compile("^<foo>");
Matcher myMatcher= myPattern.matcher("<foo><bar>");
System.out.println(myMatcher.matches());
```
And I get "false"
I am used to saying:
```
print "<foo><bar>" =~ /^<foo>/;
```
which does indeed return true.
After much searching and experimentation, I discovered [this](http://book.javanb.com/java-regular-expressions-taming-the-java-util-regex-engine/LiB0055.html) which said:
"The String method further optimizes its search criteria by placing an invisible ^ before the pattern and a $ after it."
When I tried:
```
Pattern myPattern= Pattern.compile("^<foo>.*");
Matcher myMatcher= myPattern.matcher("<foo><bar>");
System.out.println(myMatcher.matches());
```
then it returns the expected true. I do not want that pattern though. The terminating .\* should not be necessary.
Then I discovered the Matcher.useAnchoringBounds(boolean) method. I thought that expressly telling it to not use the anchoring bounds would work. It did not. I tried issuing a
```
myMatcher.reset();
```
in case I needed to flush it after turning the attribute off. No luck. Subsequently calling .matches() still returns false.
What have I overlooked?
Edit:
Well, that was easy, thanks. | Use the Matcher [find](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#find()) method (instead of the [matches](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#matches()) method) | [`Matcher.useAnchoringBounds()`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#useAnchoringBounds(boolean)) was added in JDK1.5 so if you are using 1.4, I'm not sure that it would help you even if it did work (notice the `@since 1.5` in the Javadocs).
The Javadocs for `Matcher` also state that [the `match()` method](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#matches()):
> Attempts to match the **entire** region against the pattern.
(emphasis mine)
Which explains why you only got `.matches() == true` when you changed the pattern to end with `.*`.
To match against the region starting at the beginning, but not necessarily requiring that the entire region be matched, use either the [`find()`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#find()) or [`lookingAt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#lookingAt()) methods. | How do I avoid the implicit "^" and "$" in Java regular expression matching? | [
"",
"java",
"regex",
""
] |
I have a datetime column in a MySQL table and I'd like to select records that have the same year, month, and day (but perhaps different hour and minutes). In other cases, I'd select ones with the same year and month. Is there a way to do that? | You can also do
`SELECT * FROM table WHERE datetime LIKE '2008-08-01%`'
or
```
SELECT * FROM table WHERE datetime LIKE '2007-05%'
``` | The fastest way to do this is using `BETWEEN`, for example:
```
SELECT fields FROM table WHERE
datecolumn BETWEEN '2001-01-01 00:00:00' AND '2001-12-31 23:59:59';
``` | Is there a way to SELECT by a part of a date in SQL? | [
"",
"sql",
"mysql",
""
] |
How do I add/remove a class from a div when it already has one or more classes?
```
<div class="class1 class2" id="id1">some text</div>
$("#id1").toggleClass("class3"); // doesn't work
$("#id1").toggleClass(" class3"); // doesn't work
```
Do I have to parse the string? | Your code should definitely work. In fact, the [`toggleClass` example](http://docs.jquery.com/Attributes/toggleClass) *uses* multiple class names! | Have you tried $("#id1").addClass("classname") and $("#id1").removeClass("classname")? | How do I add/remove a class in a <div> when it already has classes | [
"",
"javascript",
"jquery",
""
] |
When using the following configure flags below, the following error is reported, why is this? Obviously the directory exists. This is a PHP 5.2.9 install on a 64bit CentOS 5.2 OS.
./phpconfig.scr: line 11: --bindir=/usr/bin: No such file or directory
'./configure' \
'--host=x86\_64-redhat-linux-gnu' \
'--build=x86\_64-redhat-linux-gnu' \
'--target=x86\_64-redhat-linux' \
'--program-prefix=' \
'--prefix=/usr' \
'--exec-prefix=/usr' \
'--bindir=/usr/bin' \
'--sbindir=/usr/sbin' \
'--sysconfdir=/etc' \
'--datadir=/usr/share' \
'--includedir=/usr/include' \
'--libdir=/usr/lib64' \
'--libexecdir=/usr/libexec' \
'--localstatedir=/var' \
'--sharedstatedir=/usr/com' \
'--mandir=/usr/share/man' \
'--infodir=/usr/share/info' \
'--cache-file=../config.cache' \
'--with-libdir=lib64' \
'--with-config-file-path=/etc' \
'--with-config-file-scan-dir=/etc/php.d' \
'--disable-debug' \
'--with-pic' \
'--disable-rpath' \
'--without-pear' \
'--with-bz2' \
'--with-curl' \
'--with-exec-dir=/usr/bin' \
'--with-freetype-dir=/usr' \
'--with-png-dir=/usr' \
'--enable-gd-native-ttf' \
'--without-gdbm' \
'--with-gettext' \
'--with-gmp' \
'--with-iconv' \
'--with-jpeg-dir=/usr' \
'--with-openssl' \
'--with-png' \
'--with-pspell' \
'--with-expat-dir=/usr' \
'--with-pcre-regex=/usr' \
'--with-zlib' \
'--with-layout=GNU' \
'--enable-exif' \
'--enable-ftp' \
'--enable-magic-quotes' \
'--enable-sockets' \
'--enable-sysvsem' \
'--enable-sysvshm' \
'--enable-sysvmsg' \
'--enable-track-vars' \
'--enable-trans-sid' \
'--enable-yp' \
'--enable-wddx' \
'--with-kerberos' \
'--enable-ucd-snmp-hack' \
'--with-unixODBC=shared,/usr' \
'--enable-memory-limit' \
'--enable-shmop' \
'--enable-calendar' \
'--enable-dbx' \
'--enable-dio' \
'--without-mime-magic' \
'--without-sqlite' \
'--with-libxml-dir=/usr' \
'--with-xml' \
'--with-apxs2=/usr/sbin/apxs' \
'--without-mysql' \
'--without-gd' \
'--without-odbc' \
'--disable-dom' \
'--disable-dba' \
'--without-unixODBC' \
'--disable-pdo' \
'--disable-xmlreader' \
'--disable-xmlwriter' \
'--disable-json' | Thanks for the responses. As it turns out the issue was with the script that was used to actually call ./configure. Within the script itself there was an extra space above the bindir config flag. So...
'--exec-prefix=/usr' \\_<-The extra space indicated by the underscore.
'--bindir=/usr/bin' \
So the escape character was escaping a space and not a return.
ERRR.
Hopefully this will help someone else from loosing a afternoon trying to dig deeper than the obvious. | Are you installing with correct permissions? Trying using sudo. | PHP Config --bindir | [
"",
"php",
""
] |
I am looking for a way to accomplish the following: A user programs some drum loops in flash and is somehow able to download or save an mp3 of the loop.
I thought that the pattern could be composted on the server side. Then a link to the file is sent to the user.
I had thought there might be something like imageGD or imageMagick for sound out there?
Also, if it is possible for flash to generate something that the user could save on the fly? That would work too, but I am unaware of any such functionality in flash.
I suppose something could be done in processing, but I am totally unfamiliar with that.
How might this sort of thing might be accomplished? | Take a look at [SoX](http://sox.sourceforge.net/).
SoX is a cross-platform (Windows, Linux, MacOS X, etc.) command line utility that can convert various formats of computer audio files in to other formats. It can also apply various effects to these sound files, and, as an added bonus, SoX can play and record audio files on most platforms. | If you have control over your server environment, I suppose you could use [ffmpeg](http://ffmpeg.org/ffmpeg-doc.html) to do the job.
In your PHP code:
```
exec(escapeshellcmd("/path/to/ffmpeg -i /path/to/audiofile1.mp3 -i /path/to/audiofile2.mp3 -itsoffset 10 -i /path/to/audiofile3.mp3 -itsoffset 20 -acodec mp3 /path/to/outputfile.mp3"),$output,$status);
```
Notice that -itsoffset is the offset in seconds you want the audio file to be placed in. So this is not ideal if you want very minute control over the timing, but I don't know if you need that. | automatically composite sound - php or something like that - GD library for sound? | [
"",
"php",
"audio",
"server-side",
"compositing",
""
] |
I am looking for a disassembler or better, a decompiler for .net. The situation is that the source code for an assembly written by one of my predecessors is lost and I'd like to take a look to see what it's doing.
I know that ildasm comes with the Visual Studio installation so I can get at the MSIL, but I was hoping there was a program clever enough to work back to the C# code (or best approximation).
Are there any tools for this out there?
(If not, I suppose it'll be a good excuse for me to sit down and start to learn MSIL) | Have you looked at Reflector?
<http://www.red-gate.com/products/reflector/> | Now that Red Gate have started charging for the .NET Reflector tool you might want to check out these free alternatives instead...
[Telerik JustDecompile](http://www.telerik.com/products/decompiling.aspx)
[JetBrains dotPeek](http://www.jetbrains.com/decompiler/)
[(Open Source) ILSpy](http://wiki.sharpdevelop.net/ilspy.ashx) | A .net disassembler/decompiler | [
"",
"c#",
".net",
"cil",
""
] |
> **Possible Duplicate:**
> [Why is it important to override GetHashCode when Equals method is overridden?](https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden)
In C#, what specifically can go wrong if one fails to override GetHashCode() when overriding Equals()? | The most visible way is for mapping structures.
Any class which does this will have unpredictable behavior when used as the Key for a Dictionary or HashTable. The reason being is that the implementation uses both GetHashCode and Equals to properly find a value in the table. The short version of the algorithm is the following
1. Take the modulus of the HashCode by the number of buckets and that's the bucket index
2. Call .Equals() for the specified Key and every Key in the particular bucket.
3. If there is a match that is the value, no match = no value.
Failing to keep GetHashCode and Equals in sync will completely break this algorithm (and numerous others). | Think of a hash / dictionary structure as a collection of numbered buckets. If you always put things in the bucket corresponding to their GetHashCode(), then you only have to search one bucket (using Equals()) to see if something is there. This works, provided you're looking in the right bucket.
So the rule is: if Equals() says two objects are Equal(), they *must* have the same GetHashCode(). | What can go wrong if one fails to override GetHashCode() when overriding Equals()? | [
"",
"c#",
".net",
""
] |
How do I change the global alpha value of a BufferedImage in Java? (I.E. make every pixel in the image that has a alpha value of 100 have a alpha value of 80) | I don't believe there's a single simple command to do this. A few options:
* copy into another image with an [AlphaComposite](http://java.sun.com/javase/6/docs/api/java/awt/AlphaComposite.html) specified (downside: not converted in place)
* directly manipulate the [raster](http://java.sun.com/javase/6/docs/api/java/awt/image/WritableRaster.html) (downside: can lead to [unmanaged images](http://javagraphics.blogspot.com/2007/04/managed-images.html))
* use a filter or [BufferedImageOp](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImageOp.html)
The first is the simplest to implement, IMO. | @Neil Coffey:
Thanks, I've been looking for this too; however, Your code didn't work very well for me (white background became black).
I coded something like this and it works perfectly:
```
public void setAlpha(byte alpha) {
alpha %= 0xff;
for (int cx=0;cx<obj_img.getWidth();cx++) {
for (int cy=0;cy<obj_img.getHeight();cy++) {
int color = obj_img.getRGB(cx, cy);
int mc = (alpha << 24) | 0x00ffffff;
int newcolor = color & mc;
obj_img.setRGB(cx, cy, newcolor);
}
}
}
```
Where obj\_img is BufferedImage.TYPE\_INT\_ARGB.
I change alpha with setAlpha((byte)125); alpha range is now 0-255.
Hope someone finds this useful. | Change the alpha value of a BufferedImage? | [
"",
"java",
"graphics",
"bufferedimage",
""
] |
I'm working a a project for a new web app. I'm identifying the key points of functionality, and one thing that I clearly don't know how to approach is as follows:
Once per minute the server needs to run a series of calcs on its data, and post new derived summaries.
So in essence what I need is a way to run a server side script once per minute, reliably, even when users aren't active.
I'm using ASP.NET 3.5, C# for the web interface. Using SQL 2005 for the data back end.
I suppose all the data thats being changed is SQL side, so the script could function completely there if thats more workable.
Thanks for any suggestions. | There are two options for "background" processing on a web site. You could not do it as part of the site, but rather do it in a windows service (can use the same business objects an everything) or you can do it in a background thread started in the web app. We've used both with success, different ones in different places. In our Application\_Start we do:
```
//Submit background thread to update time left hospital
System.Threading.Thread checkoutThread =
new System.Threading.Thread(BackgroundThread.CheckoutUpdate);
checkoutThread.IsBackground = true;
checkoutThread.Priority = System.Threading.ThreadPriority.BelowNormal;
checkoutThread.Start();
```
Where BackgroundThread.CheckoutUpdate is defined as `public static void CheckoutUpdate()` | Place an item in the cache with a minutes expiry. Make sure you assign it a call back method for when the item is dropped. After a minute the item is removed your call back runs. Do you stuff there then add the item to the cache again. | How do I create a server side timed event? | [
"",
"c#",
".net-3.5",
""
] |
We are facing an issue where the following check fails intermittently in IE:
pseudocode:
```
setCookie("name","value", "1d");
if(getCookie("name") === "value"){
return SUCCESS;
} else {
return FAILURE;
}
```
this little routine checks if the user has cookies enabled. it shouldnt fail but it does.
is it because IE can only handle a certain amount of cookies? (we set lots of cookies).
is there some other way to do a cookie check that is more reliable? | Yes, IE has a preset cookie limit per host. After that the program begins discarding cookies. Check [here](http://www.enhanceie.com/ie/bugs.asp) for more info...
I'd recommend you use use cookies only to track the userid, for everything else you should use something like "Session State". | As bastos.sergio said, use session.
That said, if you have load balanced web servers, ignore session and pull the data straight from the database server when you need it.
If it is a single web server, then use session.
Regardless, take a look at the data you are storing. ALL cookies for a domain are sent back on every web request. All session data is also loaded up for every single web request.
If you don't need the data for every web page, then you shouldn't cache it in cookies or session as it actually causes a greater performance penalty than just pulling it when you need to.
This is why the only things that are typically stored in cookies or session are simple items like the user id.
Also, I believe IE limits the site to 20 separate cookies for a total of 4KB of data.
See <http://support.microsoft.com/kb/306070>
**UPDATE**: Scratch the limit of 20. IE 5,6, and 7 support up to 50 cookies provided a particular update from August 2007 was applied. <http://support.microsoft.com/kb/941495> However, the 4KB limit is still imposed.
And see [this blog entry](http://blogs.msdn.com/ie/archive/2007/08/29/update-to-internet-explorer-s-cookie-jar.aspx) which covers exactly why large amounts of cookies are a bad idea. | IE cookie quirks | [
"",
"javascript",
"internet-explorer",
"cookies",
""
] |
I want to parse a file and I want to use php and regex to strip:
* blank or empty lines
* single line comments
* multi line comments
basically I want to remove any line containing
```
/* text */
```
or multi line comments
```
/***
some
text
*****/
```
If possible, another regex to check if the line is empty (Remove blank lines)
Is that possible? can somebody post to me a regex that does just that?
Thanks a lot. | ```
$text = preg_replace('!/\*.*?\*/!s', '', $text);
$text = preg_replace('/\n\s*\n/', "\n", $text);
``` | Keep in mind that any regex you use will fail if the file you're parsing has a string containing something that matches these conditions. For example, it would turn this:
```
print "/* a comment */";
```
Into this:
```
print "";
```
Which is probably *not* what you want. But maybe it is, I don't know. Anyway, regexes technically can't parse data in a manner to avoid that problem. I say technically because modern PCRE regexes have tacked on a number of hacks to make them both capable of doing this and, more importantly, no longer *regular* expressions, but whatever. If you want to avoid stripping these things inside quotes or in other situations, there is no substitute for a full-blown parser (albeit it can still be pretty simple). | Regex to strip comments and multi-line comments and empty lines | [
"",
"php",
"regex",
"preg-replace",
""
] |
In Java, I use *log4J* that is a logging framework. In Log4j you can do something like this:
```
if (log.isDebug()) {
// do some expensive operation that should only be displayed if DEBUG is turned on
}
```
Reading some Symfony examples, I am unable to find a way to determine if DEBUG logging is activated in the current class context. Is there a way to do this?
```
if (--need something here--) {
$this->logMessage('Expensive operation return value: '.expensiveFunction(), 'debug');
}
``` | something like
```
$this->getLogger()->getLogLevel() == sfLogger::DEBUG
```
should do. | You should check the usage for [Monolog](http://symfony.com/doc/current/cookbook/logging/monolog.html) | Symfony Logging | [
"",
"php",
"logging",
"symfony1",
""
] |
I want to extract some queries to a CSV output format. Unfortunately, I can't use any fancy SQL client or any language to do it. I must use SQLPLUS.
How do I do it? | If you are using 12.2, you can simply say
```
set markup csv on
spool myfile.csv
``` | You could also use the following, although it does introduce spaces between fields.
```
set colsep , -- separate columns with a comma
set pagesize 0 -- No header rows
set trimspool on -- remove trailing blanks
set headsep off -- this may or may not be useful...depends on your headings.
set linesize X -- X should be the sum of the column widths
set numw X -- X should be the length you want for numbers (avoid scientific notation on IDs)
spool myfile.csv
select table_name, tablespace_name
from all_tables
where owner = 'SYS'
and tablespace_name is not null;
```
Output will be like:
```
TABLE_PRIVILEGE_MAP ,SYSTEM
SYSTEM_PRIVILEGE_MAP ,SYSTEM
STMT_AUDIT_OPTION_MAP ,SYSTEM
DUAL ,SYSTEM
...
```
This would be a lot less tedious than typing out all of the fields and concatenating them with the commas. You could follow up with a simple sed script to remove whitespace that appears before a comma, if you wanted.
Something like this might work...(my sed skills are very rusty, so this will likely need work)
```
sed 's/\s+,/,/' myfile.csv
``` | How do I spool to a CSV formatted file using SQLPLUS? | [
"",
"sql",
"oracle",
"csv",
"sqlplus",
""
] |
I have a PHP variable that contains a string which represents an XML structure. This string contains ilegal characters that dont let me build a new SimpleXMLElement object from the string. I dont have a way to ask the source of the content to modify their response, so I need to execute some cleaning on this string before I create a SimpleXMLElement object.
I believe the character causing the problem is a (0x00 (00) HEX) character, and its located within one of the Text Nodes of this string XML.
What is the best way to remove this character or other characters that could break the SimpleXMLElement object. | ```
$text = str_replace("\0", "", $text);
```
will replace all null characters in the `$text` string. You can also supply arrays for the first two arguments, if you want to do multiple replacements. | trim() will also remove null characters, from either end of the source string (but not within).
```
$text = trim($text);
```
I've found this useful for socket server communication, especially when passing JSON around, as a null character causes json\_decode() to return null. | How can I remove the NULL character from string | [
"",
"php",
""
] |
What is the recommended way of formatting `TimeSpan` objects into a string with a custom format? | **Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see [JohannesH's answer](https://stackoverflow.com/a/574894/39277).**
Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN [Custom TimeSpan Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings) page.
Here's an example timespan format string:
```
string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15
```
(**UPDATE**) and here is an example using C# 6 string interpolation:
```
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
```
You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN [Custom TimeSpan Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings) page explains about escaping the ":" and "." characters in a format string:
> The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes. | For .NET 3.5 and lower you could use:
```
string.Format ("{0:00}:{1:00}:{2:00}",
(int)myTimeSpan.TotalHours,
myTimeSpan.Minutes,
myTimeSpan.Seconds);
```
*Code taken from a Jon Skeet [answer](http://bytes.com/groups/net-c/520177-string-format-timespan) on bytes*
For .NET 4.0 and above, see DoctaJonez [answer](https://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net/4386305#4386305). | How can I String.Format a TimeSpan object with a custom format in .NET? | [
"",
"c#",
".net",
"string",
"time",
"formatting",
""
] |
What exactly is a module? What is the difference between a module, a class and a function? How can I access a module in C#?
I am asking this because I want to calculate a checksum of the IL code of only some particular functions, at runtime (without using code signing). | A module is a logical collection of code within an Assembly. You can have multiple modules inside an Assembly, and each module can be written in different .NET languages (VS, as far as I'm aware, doesn't support creation of multi-module assemblies).
Assemblies contain modules.
Modules contain classes.
Classes contain functions.
Yes you can access assemblies, modules, classes, functions, properties, fields etc all via reflection at runtime. | As an addition to the other answers:
The MSDN states that: "A module is a Microsoft intermediate language (MSIL) file that does not have an assembly manifest.".
Modules can be "linked" together by generating an assembly manifest using the Assembly Linker (al.exe) utility. If i remember it correctly the CLR can load individual modules for an assembly, so that only the neccessary modules get loaded.
EDIT: Found a [better description](https://learn.microsoft.com/en-us/archive/blogs/junfeng/netmodule-vs-assembly) of the Netmodules and why you would want them.
There is another [question](https://stackoverflow.com/questions/610758/calculating-the-checksum-of-the-code-at-runtime) here on SO that touches the checksum subject. The answers mentions using the GetILAsByteArray method for getting the IL. | What is a module in .NET? | [
"",
"c#",
".net",
"module",
""
] |
I'd like to know how you address the seemingly low productivity of Java EE-based web application development compared to other technology stacks ([Seaside](http://www.seaside.st/), [Ruby on Rails](http://rubyonrails.org/), etc).
The constraints are:
* The finished web application must be deployable on Java EE compliant application containers
* If possible, previous investment in Java-based solution should be preserved, i.e. native interoperability with Java-based systems and libraries should be possible
* Due to team structure, Java as implementation language is preferred, although less exotic JVM-based languages (i.e. Groovy) might be acceptable as well
* The resulting system needs to be architecturally sound
* The resulting system needs to be extensible and maintainable
To not let this dwindle into a philosophical discussion, I'm only interested in suggestions that are based on practical experience. Possible examples include domain specific languages, frameworks and MDSD.
If you point to an abstract class of solutions (like MDA / MDSD), please provide details on how you implemented it as well as information about common pitfalls and best practices.
If you disagree on the assumption that Java EE-based web application development implies inferior productivity, I'd like to hear your reasoning as well.
*EDIT:*
As there are a lot less answers than I expected, I'll accept accounts of abortive attempts as well, basically extending the question to "How (not) to improve productivity when developing Java EE based web applications?". | I believe the Java EE Java stack is actually very good. There are a few reasons explaining the low productivity of Java EE:
* Being “the enterprise stack”, it is often used to create [boring, ugly, “good enough”](https://blog.codinghorror.com/the-great-enterprise-software-swindle/) applications and, in general, [enterprises tend not to attract great developers](http://www.paulgraham.com/artistsship.html) who love programming, and think and care about what they do. The quality of software in the enterprise world is not great.
* Being the enterprise stack where the money is, software vendors try to sell something to them. They create huge, complex and expensive solutions not because they are good, but simply because they could sell them to enterprises.
* Enterprises are often very risk averse and everything they do better be “standardized”. Standards are created either *after* some technology proved to be successful or *before*. In both cases, it’s bad for enterprises (and Java). Enterprises end up using either good technology too late or a downright failed technology. The latter case is also very dangerous because it creates a false perception that a technology (otherwise a complete failure) must be good if it is standardized and everyone is using it.
* Historically, Java EE platform seemed to have attracted a lot of architecture astronauts and developers in big companies promoted to architects whose only purpose was to create more layers, more frameworks, more abstractions and more complexity.
It’s not that there are no good Java tools and frameworks; it’s that there are too many bad ones, too many over-engineered ones, too many bureaucratic processes and methodologies, too many useless standards.
In such a messy world it’s not just the particular selection of tools you choose that affects your productivity. It’s mainly about you, about your values, about how you can reject the majority of solutions proposed to you by the community, vendors, co-workers and managers. It’s about you going against the current, about *your* common sense, about *you* questioning every mainstream belief and “best practice”.
That said, tools alone are not going to change your productivity much, and conversely, the right people can be productive with inferior tools too.
My advice:
* Don’t use a technology only because it’s standard, because everyone uses it, or because it’s officially recommended by Sun. Use a technology only if you personally think it’s the best tool for your job. This way you may find yourself rejecting technologies such as JSF, JSP, Web services, JMS, EJB, JTA, OSGi, MDA.
* Keep it simple, use your common sense, question everything. Do you really need to publish your objects for remote access? Do you really need to create another abstraction layer so that you can switch from Hibernate to TopLink? Do you really need to convert your data to/from XML ten times every time you need them? Do you really need XML schema? Do you really need everything to be configurable are interchangeable? At runtime? By non-developers?
* Keep the process simple. Be [agile](http://agilemanifesto.org/). Do you really need that documentation? Do you really need to describe every screen in a huge table, have it approved, type it in to some home-made tool and then generate JSP? Do you have competent programmers or you design everything first and programmers only “translate” to Java?
* WYSIWYG design of HTML doesn’t work.
* Graphical programming in general doesn’t work. This includes [UML as blueprint](http://martinfowler.com/bliki/UmlAsBlueprint.html) and [UML as programming language](http://martinfowler.com/bliki/UmlAsProgrammingLanguage.html), MDA, drawing page flow diagrams. Code generation is bad.
* Never [design a framework prior to using it](http://martinfowler.com/bliki/FoundationFramework.html), always [harvest a framework](http://martinfowler.com/bliki/HarvestedFramework.html).
* Prefer frameworks that have only little XML configuration.
* Strive for low LOC count. Look at actual *characters* in your code. Is every character important? Think. What can you do to make your code smaller? Do you need that class? What does it do? Why do you need to do that?
* Testing is not sacred cow; you don’t need 100 % test coverage. Test only what makes sense. If it’s difficult to test, make it simpler; or don’t test it at all. Don’t test visual appearance.
And finally, some concrete Java recommendations:
* For presentation layer try [Tapestry](http://tapestry.apache.org/). Why do I love it? Because with Tapestry you can create beautiful code. It’s designed specifically for that, so that **your code can be beautiful**. *Your* code. By beautiful I mean everything that matters – it’s short, easy to change, easy to read, easy to create your abstractions, and still flexible, it doesn’t try to hide the fact that you are developing for the web. Of course, it’s still *you* who makes your code beautiful.
* Feel free to use Hibernate, especially for CRUD and large apps. Don’t bother with JPA. It’s not a silver bullet though, with ORM you are always going to trade one set of problems with another.
* Only a little Spring, you shouldn’t need much since you’ve carefully avoided all the Java EE traps. Use dependency injection sparingly.
* After all of that, you may find the Java language too verbose and not very helpful when abstracting away you copy/pasted code. If you want to experiment, try Scala. The problem is that the main selling point of Scala is that you get all the benefits of modern languages while still keeping type safety, and at the same time, there is no *solid* IDE support. Being used to super-cool Java IDEs, it doesn’t make much sense to switch to Scala unless there’s an IDE support that is stable and reliable. Stable enough is not enough. | Frameworks like [Spring](http://www.springsource.org/), [Hibernate](http://www.hibernate.org/), [Wicket](http://wicket.apache.org/) certainly help to simplify and accelerate web development as they provide a high degree of testability and integrate very well. But it's not enough to reach RoR productivity, even if you have a good set of development practices. There is still too much technical stuff and plumbing required.
[Grails](http://www.grails.org/Home) is maybe the missing piece in this picture to get closer to RoR. It's my next experimentation.
BTW, my MDA experiences are the contrary of a productivity improvement so I won't mention them (actually, MDA was killing our productivity). | How to improve productivity when developing Java EE based web applications | [
"",
"java",
"performance",
"jakarta-ee",
"web-applications",
""
] |
I have a solution with many Visual C++ projects, all using PCH, but some have particular compiler switches turned on for project-specific needs.
Most of these projects share the same set of headers in their respective stdafx.h (STL, boost, etc). I'm wondering if it's possible to share PCH between projects, so that instead of compiling every PCH per-project I could maybe have one common PCH that most projects in the solution could just use.
It seems possible to specify the location of the PCH as a shared location in the project settings, so I have a hunch this could work. I'm also assuming that all source files in all projects that use a shared PCH would have to have the same compiler settings, or else the compiler would complain about inconsistencies between the PCH and the source file being compiled.
Has anyone tried this? Does it work?
A related question: should such a shard PCH be overly inclusive, or would that hurt overall build time? For example, a shared PCH could include many STL headers that are widely used, but some projecst might only need `<string>` and `<vector>`. Would the time saved by using a shared PCH have to be paid back at a later point in the build process when the optimizer would have to discard all the unused stuff dragged into the project by the PCH? | Yes it is possible and I can assure you, the time savings are significant. When you compile your PCH, you have to copy the `.pdb` and `.idb` files from the project that is creating the PCH file. In my case, I have a simple two file project that is creating a PCH file. The header will be your PCH header and the source will be told to create the PCH under project settings - this is similar to what you would do normally in any project. As you mentioned, you have to have the same compile settings for each configuration otherwise a discrepancy will arise and the compiler will complain.
Copying the above mentioned files every time there is a rebuild or every time the PCH is recompiled is going to be a pain, so we will automate it. To automate copying, perform a pre-build event where the above mentioned files are copied over to the appropriate directory. For example, if you are compiling `Debug` and `Release` builds of your PCH, copy the files from `Debug` of your PCH project over to your dependent project's `Debug`. So a copy command would look like this
> copy PchPath\Debug\*.pdb Debug\ /-Y
Note the `/-Y` at the end. After the first build, each subsequent build is incrementally compiled, therefore if you replace the files again, Visual Studio will complain about corrupted symbols. If they do get corrupted, you can always perform a rebuild, which will copy the files again (this time it won't skip them as they no longer exist - the cleanup deletes the files).
I hope this helps. It took me quite some time to be able to do this, but it was worth it. I have several projects that depend on one big framework, and the PCH needs to be compiled only once. All the dependent projects now compile very quickly.
> EDIT: Along with several other people, I have tested this under VS2010
> and VS2012 and it does appear to work properly. | While this is an old question I want to give a new answer which works in Visual Studio 2017 and does not involve any copying. Only disadvantage: Edit and continue doesn't work anymore.
Basically you have to create a new project for the precompiled header and have all other project depend on it. Here is what I did:
Step by step:
1. Create a new project withnin your solution which includes the header (called pch.h from hereon) and a one line cpp file which includes pch.h. The project should create a static lib. Setup the new project to create a precompiled header. The output file needs to be accessible by all projects. for me this relative to IntDir, but for default settings it could be relative to $(SolutionDir). The pch project must only have defines all others projects have too.
[](https://i.stack.imgur.com/GZAOR.png)
2. Have all other projects depend on this new project. Otherwise the build order might be wrong.
[](https://i.stack.imgur.com/2zcEg.png)
3. Setup all other projects to use the pch.h. See, how the output file parameters are the same as in the pch project. Additional include directories also need to point to the pch.h directory. Optionally you can force include the pch file in every cpp (or you include it manually in the first line of every cpp file).
[](https://i.stack.imgur.com/2yZgl.png)
[](https://i.stack.imgur.com/ulvBe.png)
[](https://i.stack.imgur.com/Aq6TC.png)
4. Setup all projects (including the pch project) to use the same compiler symbol file (the linker symbol file is not affected). Again, in my example this is OutDir but in your solution this might vary. It has to point to the same file on disk. The Debug Information Format needs to be set to C7 (see screenshot above), otherwise Visual Studio will not be able to compile projects in parallel.
[](https://i.stack.imgur.com/oPNUr.png)
I hope I didn't forget anything. For my solution (130k loc, 160 projects) this lead to a compile time of ~2:30mins instead of ~3:30mins. | Sharing precompiled headers between projects in Visual Studio | [
"",
"c++",
"visual-c++",
"precompiled-headers",
"pch",
""
] |
Imagine I have a SearchService layer that has a method to search all cars starting with a certain string;
```
public static class Searcher{
public IAnInterface<Car> CarsStartingWith(string startWith){
//magic
}
}
```
What interface should my service use?
IQueryable can render for a nice fluid interface in the rest of my application.
IEnumerable has the lazy aspect going with it.
IList is just the most practical.
I would like to have all my services return the same interface for consistency makes the whole thing a lot easier.
ICollection could maybe be an option too, but it just offers so little... | If you want all your services to return the same interface then I would probably go for `IEnumerable<>`.
It'll be easy enough for your callers to convert to `IQueryable` or create a `List`, if necessary:
```
IEnumerable<Car> cars = Searcher.CarsStartingWith("L");
var carsList = cars.ToList();
var queryableCars = cars.AsQueryable();
``` | I would choose `IEnumerable` because it has a more central place in the framework, providing versatility for those that need it, while also providing familiarity to those who are yet to get stuck into things like LINQ. | What interface should my service return? IQueryable, IList, IEnumerable? | [
"",
"c#",
".net",
""
] |
```
Array $imagelist:
Array (
[additional] => Array (
[count] => 2
[image] => Array (
[nokia_e61_1.jpg] => Array (
[name_body] => nokia_e61_1
[name_ext] => jpg
)
[nokia_e61_2.jpg] => Array (
[name_body] => nokia_e61_2
[name_ext] => jpg
)
[nokia_e61_3.jpg] => Array (
[name_body] => nokia_e61_3
[name_ext] => jpg
)
[nokia_e61_4.jpg] => Array (
[name_body] => nokia_e61_4
[name_ext] => jpg
)
)
)
[main] => nokia_e61
)
```
The value `nokia_e61_1.jpg` is kept in `{$getvars.imagename}`.
I wrote `` {$imagelist.additional.image.`$getvars.imagename`.name_body} `` but it doesn't work.
Please help. | see if `{$imagelist.additional.image[$getvars.imagename].name_body}` works | I don't like smarty for this, nevertheless I use it.
Here's extract form documentation
```
{$foo.$bar} <-- display variable key value of an array, similar to PHP $foo[$bar]
```
To be able to do it, you have to
```
{assign var='key' value=$getvars.imagename}
{$imagelist.additional.image.$key.name_body}
```
Hope it helps | Smarty: How to reference to the associative array index | [
"",
"php",
"arrays",
"indexing",
"reference",
"smarty",
""
] |
In C++, declaration and definition of functions, variables and constants can be separated like so:
```
function someFunc();
function someFunc()
{
//Implementation.
}
```
In fact, in the definition of classes, this is often the case. A class is usually declared with it's members in a .h file, and these are then defined in a corresponding .C file.
What are the advantages & disadvantages of this approach? | Historically this was to help the compiler. You had to give it the list of names before it used them - whether this was the actual usage, or a forward declaration (C's default funcion prototype aside).
Modern compilers for modern languages show that this is no longer a necessity, so C & C++'s (as well as Objective-C, and probably others) syntax here is histotical baggage. In fact one this is one of the big problems with C++ that even the addition of a proper module system will not solve.
Disadvantages are: lots of heavily nested include files (I've traced include trees before, they are surprisingly huge) and redundancy between declaration and definition - all leading to longer coding times and longer compile times (ever compared the compile times between comparable C++ and C# projects? This is one of the reasons for the difference). Header files must be provided for users of any components you provide. Chances of ODR violations. Reliance on the pre-processor (many modern languages do not need a pre-processor step), which makes your code more fragile and harder for tools to parse.
Advantages: no much. You could argue that you get a list of function names grouped together in one place for documentation purposes - but most IDEs have some sort of code folding ability these days, and projects of any size should be using doc generators (such as doxygen) anyway. With a cleaner, pre-processor-less, module based syntax it is easier for tools to follow your code and provide this and more, so I think this "advantage" is just about moot. | It's an artefact of how C/C++ compilers work.
As a source file gets compiled, the preprocessor substitutes each #include-statement with the contents of the included file. Only afterwards does the compiler try to interpret the result of this concatenation.
The compiler then goes over that result from beginning to end, trying to validate each statement. If a line of code invokes a function that hasn't been defined previously, it'll give up.
There's a problem with that, though, when it comes to mutually recursive function calls:
```
void foo()
{
bar();
}
void bar()
{
foo();
}
```
Here, `foo` won't compile as `bar` is unknown. If you switch the two functions around, `bar` won't compile as `foo` is unknown.
If you separate declaration and definition, though, you can order the functions as you wish:
```
void foo();
void bar();
void foo()
{
bar();
}
void bar()
{
foo();
}
```
Here, when the compiler processes `foo` it already knows the signature of a function called `bar`, and is happy.
Of course compilers could work in a different way, but that's how they work in C, C++ and to some degree Objective-C.
Disadvantages:
None directly. If you're using C/C++ anyway, it's the best way to do things. If you've got a choice of language/compiler, then maybe you can pick one where this is not an issue. The only thing to consider with splitting declarations into header files is to avoid mutually recursive #include-statements - but that's what include guards are for.
Advantages:
* Compilation speed: As all included files are concatenated and then parsed, reducing the amount and complexity of code in included files *will* improve compilation time.
* Avoid code duplication/inlining: If you fully define a function in a header file, each object file that includes this header and references this function will contain it's own version of that function. As a side-note, if you *want* inlining, you need to put the full definition into the header file (on most compilers).
* Encapsulation/clarity: A well defined class/set of functions plus some documentation should be enough for other developers to use your code. There is (ideally) no need for them to understand how the code works - so why require them to sift through it? (The counter-argument that it's may be useful for them to access the implementation *when required* still stands, of course).
And of course, if you're not interested in exposing a function at all, you can usually still choose to define it fully in the implementation file rather than the header. | What are the advantages and disadvantages of separating declaration and definition as in C++? | [
"",
"c++",
"language-design",
"declaration",
"definition",
""
] |
Wouldn't this be overkill and only one of these necessary? I've searched and found different posts about Mutual Exclusion and locks in C# [here](https://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c) and [here](https://stackoverflow.com/questions/59590/lock-keyword-in-c).
Example:
In our app, we have a function that spins off multiple reconnection threads and inside this thread we use a `Mutex` and a `lock`. Wouldn't `lock` block access to this section of code and prevent `connect` from being updated by any other thread?
```
bool connect = false;
Mutex reconnectMutex = new Mutex(false, "Reconnect_" + key);
try
{
lock(site)
{
if(site.ContainsKey(key))
{
siteInfo = (SiteInfo)site[key];
if(reconnectMutex.WaitOne(100, true))
{
connect = true;
}
}
}
if (connect)
{
// Process thread logic
}
}
catch
{}
reconnectMutex.ReleaseMutex();
```
More Info:
This is in an ASP.NET WebService not running in a Web Garden. | That Mutex (because it has a name) will stop any process on the same machine accessing it as well, whereas lock will only stop other threads in the same process. I can't see from that code sample why you'd need both kinds of lock. It seems good practice to hold the simple lock for a short period of time - but then the much heavier interprocess mutex is locked for a probably longer (though overlapping) period! Would be simpler to just use the mutex. And perhaps to find out whether an interprocess lock is really necessary.
By the way, `catch {}` is absolutely the wrong thing to use in that scenario. You should use `finally { /* release mutex */ }`. They are very different. The catch will swallow far more kinds of exception than it should, and will also cause nested finally handlers to execute in response to low-level exceptions such as memory corruption, access violation, etc. So instead of:
```
try
{
// something
}
catch
{}
// cleanup
```
You should have:
```
try
{
// something
}
finally
{
// cleanup
}
```
And if there are specific exceptions you can recover from, you could catch them:
```
try
{
// something
}
catch (DatabaseConfigurationError x)
{
// tell the user to configure the database properly
}
finally
{
// cleanup
}
``` | "lock" is basically just a syntactic sugar for Montor.Enter/Exit. Mutex is a multi-process lock.
They have very different behavior. There is nothing wrong with using both in the same application or methods, since they're designed to block different things.
However, in your case, I think you may be better off looking into Semaphore and Monitor. It doesn't sound like you need to lock across processes, so they are probably a better choice in this situation. | Should Locks and Mutexes in C# be used together | [
"",
"c#",
"locking",
"mutex",
""
] |
I use the following to implant a script into random websites:
(added by webmasters just before /body )
```
<script type="text/javascript">
var xHost = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + xHost + "domain/script.js.php?u="+encodeURIComponent(window.location.host)+"' type='text/javascript'%3E%3C/script%3E"));
</script>
```
It is an extension of the way google analytics works.
I have it installed on a specific website in which the html above it is not perfectly formed.
It works great on all browsers besides IE6. On IE6 the script never runs. **Unless I run fiddler2 in which case it runs perfectly**.
Question: How can I make it run on IE6. Any idea why it behaves well when fiddler is in the way and not so well when fiddler isn't?
Notes: I have no control over the web sites that have already integrated this code. When I copied the website page code to my server and run it from there it did run OK. | It turns out an add on named activationmanager.dll was causing the problem. Its a spyware. (IE6 is on my 5.5 years old boy computer). Thanks for the help! | Ah, I see you're using https here. When fiddler gets in the middle of your code when running https, fiddler uses its OWN certificate to talk to your browser. Maybe your copy of IE6 trusts Fiddler's certificate, but for some reason does not trust the certificate of the site you're referencing? | Seeing strange behavior on IE6 - I'm clueless | [
"",
"javascript",
"internet-explorer-6",
""
] |
By default error page in ZF looks like this:
```
Fatal error: Uncaught exception 'Zend_Form_Exception' with message 'Method setDeault does not exist' in /usr/home/.../library/Zend/Form.php:2838
Stack trace:
#0 [internal function]: Zend_Form->__call('setDeault', Array)
#1 /usr/home/.../application/admin/controllers/TagsController.php(40): Web_Form_Admintags->setDeault('tagstext', '....')
#2 /usr/home/.../library/Zend/
```
Is there any ways to change this messy error description to more clearly form (something like Django error page)? | This is not an error page but a standard PHP output for uncaught exceptions. As far as I know there is no default error page in Zend Framework -- you will have to create your own by creating an appropriate view for the ErrorController. | AFAICR this is using the Error controller right? That message is basically the dump of the [exception object](http://www.php.net/exception). You can split this up by calling different parts individually rather than dumping the whole lot as a string. See the manual page I linked to.
Make sure you're only providing exception information when the `APPLICATION_ENVIRONMENT` is set to `development` as well. | How to make Zend Framework error page to look more clearly and beautifully? | [
"",
"php",
"zend-framework",
""
] |
My first post so please go easy on me!
I know that there's no real difference between structs and classes in C++, but a lot of people including me use a struct or class to show intent - structs for grouping "plain old data" and classes for encapsulated data that has meaningful operations.
Now, that's fine but at what point do you start to think that something isn't just a struct anymore and should become a class?
Things I think are reasonable for structs to have:
1. constructors with simple initialisation code only.
2. serialization code such as stream insertion / extraction operators.
Things I'm not so sure about, but would probably do:
1. comparison operators
2. Simple transformation functions - for example byteswapping all the members after receiving data from an external source.
I don't think structs should have:
1. dynamic memory allocation.
2. destructor.
3. complex member functions.
Where do the boundaries lie???
Also, is it reasonable to have class instances as members of a struct? e.g.
```
class C {private: int hiddenData; public: void DoSomething();};
struct S {int a; float b; C c; };
S s; s.c.DoSomething();
```
Remember, I'm not on about what you CAN do with C++, I'm interested in what you SHOULD do when designing good software.
Thoughts? | **Class vs. struct**
Using class or struct keyword is a matter of taste together with the '*feeling*' it produces on the reader. Technically they are equivalent, but readability is better if structs are used for PODs and C-struct types and classes for anything else.
Basic things that should go in a C++ struct: constructor that initializes the data (I dislike using memset, and it can later bite back if the POD evolves into something different) or construction from other types but not copy constructor.
If you need to define a copy constructor or assignment operator because the compiler generated is not good enough, make it a class.
It is common to use structs also for functors that will be passed to STL algorithms and template metaprogramming, as in
```
struct square_int {
int operator()( int value )
{
return value*value;
}
};
std::transform( v.begin(), v.end(), v.begin(), square_int() );
```
or
```
// off the top of my head
template <typename T>
struct is_pointer { enum { value = false } };
template <typename T>
struct is_pointer<T*> { enum { value = true } };
```
**Member methods vs. free functions**
Besides what I have said before, that do not add to what others already answered, I wanted to put some focus on other types of functions that you comment in your post, as comparison operators and the like.
Operators that are meant to be symmetric (comparison, arithmetic), insertion and deletion operators and transformations are usually better implemented as free functions regardless of whether you declare it as a class or struct.
Symmetric operators (with regard to data types) are not symmetric if they are implemented as member functions. The lookup rules won't cast the left hand side to call a member function, but it will apply the same cast to match a free function.
```
// Example of symmetry with free functions where method would be asymmetric
int main()
{
std::string( "Hello " ) + "world"; // compiles as free / member function
"Hello " + std::string( "world" ); // compiles with free function, fails with member function definition of +
}
```
In the code above, if operator+ were a member method of std::string the compiler would fail to compile as it cannot cast the const char\* literal into a std::string to use the member method.
Insertion and extraction from streams must always be implemented as free functions as the stream is always the left hand side of the operation.
Keeping transformations as free functions decouple the two different types. If A and A' can be converted into one another and you decide to implement transformations as members of A, then A must know A' and all uses of A will depend on A' whether you use it or not. If you define the transformation as a free function, A is complete without A' and the coupling between the two classes/structs will be smaller. The same goes for transformations to/from network, serialization and deserialization. When you implement them inside the class/struct you are forcing all users to know about those transforms. | I think there are three major, coherent schools of thought:
1. People that don't care either way and use `struct` and `class` interchangeably.
2. People that use `struct`s only to represent small POD.
3. People who use `struct`s as records.
I can't make a conclusive argument for either of these strategies. I tend to follow path 2 but I also use structs for non-POD types when I see it fitting, especially for function objects (even if these may not fulfil POD requirements).
(Incidentally, the C++ FAQ lite has a pretty good definition of [POD](http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.7)).
**EDIT** I didn't touch template metaprogramming techniques, such as using `struct` for placeholders (type tags) or to implement metafunctions. I guess there's absolutely no controversy in these cases: since they never contain methods (or even data), always use `struct`). | How much functionality is "acceptable" for a C++ struct? | [
"",
"c++",
"oop",
"struct",
""
] |
This is almost certainly something really silly that I've overlooked but I'm stumped. The following C# style expression is supposed to match phones numbers (a limited subset of them, but this is just testing...):
```
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
```
The search string is as follows:
```
978-454-0586\r\nother junk\r\nmore junk\r\nhttp://www.google.com\r\n
```
The expression matches the phone number when in isolation, however not when next to other stuff. For example, if I lop off everything after the phone it works just great.
How can I modify the expression so that it matches the phone number and doesn't get hung up on the rest of the junk?
Thanks! | The ^ and $ symbols mean "beginning of line" and "end of line" respectively. Get rid of them if you want to match in the middle of a line. | "$" in a regular expression matches the end of a line. If you remove that, the regexp should work correctly, though if you have "Foo978-454-0586", it won't work, since "^" matches the start of a line. | What's wrong with this regular expression? | [
"",
"c#",
"regex",
""
] |
Few questions on ORM mappers like nhibernate (for .net/c# environment).
1. When queries are run against a sqlserver database, does it use parameter sizes internally?
paramaters.Add("@column1", SqlDataType.Int, 4)
2. Do they all use reflection at runtime? i.e. hand coding is always a tad faster?
3. does it support temp tables, table variables? | ORM World is powerfull and full featured one, I think today obstacles are peoples theirself, this to say that using ORM's needs to take changes in mind, in the way of thinkng applications, architectures and patterns.
To answer you questions:
1. Query execution depends on more factors, it's possible to fully customize the engine/environment to take advantages of various features like, deffered execution, future queries (queries executed in a future moment), multiple queries, and last but not least, session management involves in this area:
1. Deferred execution is based on concepts like lazy-loading and lazy execution, this means that queries are executed against the database just qhen you perform some actions, like accessing to methods of the NHibernate Session like **ToList()**, another example of deferred execution is with using of LinqToNhibernate, where just when you access to certain objects, queries are executed
2. Future queries are as I said beforre queries executed in a future moment, Ayende speaks well about that
3. Multiple queries are queries that can be "packed" together and executed in one time avoiding multiple roundtrips to the DB, and this could be a very cool feature
4. Session Management, this is another chapter to mention... but take in mind that if you manage well your session, or better, let NHibernate engine to manage well the session, sometime it's not needed to go to the DN to obtain data
in all the cases, tools like NHibernate generates queries for you, and parametrized queries are managed well with parameters even depending on the underlying DB engine and conseguently DB Dialect you choose!
1. It's clear that frameworks like NHibernate, most of the time, use reflection at runtime, but it's needed to mention the multiple Reflection optimization are used, see for example **Dynamic Proxies**... It's clear that somethime, or maybe all the time direct code could be faster, but just in the unit, in the big picture this could involve in more mistakes and bottlenecks
2. Talking about NHibernate, or better saying, It's usefull to understand what you mean when talk about Temp Tables and temp data.. In terms as are, NHibernate, as I know, doesn't support natively Temp Tables, in the sense of Runtime tables, but this could be done because NHibernate permit to create object mapping at runtime, so a mechanism of Temp data could be implemented using that api
I hope I provided an usefull answer!
...and oops, sorry for my bad english! | nhiberate uses an optimised form of reflection that creates proxy objects on startup that perform better than plain reflection, as it only incurs a one time cost. You have the option of disabling this feature as well which has nhibernate behave in a more typical manner, with the permanent use of reflection.
This feature is set with the following key:
```
<add key="hibernate.use_reflection_optimizer" value="true" />
```
Nhibernate can be used with variable table names. See [this SO thread](https://stackoverflow.com/questions/515985/how-to-use-nhibernate-with-variable-or-dynamic-table-names-like-jan08tran-feb08tr) for a good solution. | questions about ORM mappers like nhibernate etc | [
"",
"c#",
".net",
"orm",
""
] |
I have an application built with .NET 3.5. If a user runs it without having .NET 3.5 installed, I want to have control of what they see and perhaps provide a message that they can understand (with a link to .NET 3.5) versus unhandled exception stack traces. But if they don't actually have .NET 3.5 how can my application control anything? | Better yet, you could use an installer technology, such as Wix or a Visual Stuido setup project, that checks during installation that all the prerequisites for you software, such as a particular .NET framework runtime exist. If not, it will install them, or at least tell the user where to get them and what to do next | Are you assuming that at least SOME version of .NET is installed?
You could write a small loader to be compatible with all versions to do the check.
Or if .NET is not installed, found a simple batch program (though this could easily be done in C++ if you prefer).
```
@ECHO OFF
SET FileName=%windir%\Microsoft.NET\Framework\v1.1.4322
IF EXIST %FileName% GOTO Skip
ECHO.You currently do not have the Microsoft® .NET Framework 1.1 installed.
ECHO.This is required by the setup program for MyApplication.
ECHO.
ECHO.The Microsoft® .NET Framework 1.1 will now be installed on you system.
ECHO.After completion setup will continue to install MyApplication on your system.
ECHO.
Pause
SET FileName=
Start /WAIT .\dotnetfx.exe
Start .\Setup.exe
ECHO ON
Exit
Tongue Tiedkip
SET FileName=
Start .\Setup.exe
ECHO ON
Exit
```
[This](http://msdn.microsoft.com/en-us/kb/kb00318785.aspx) might also help. | How to safely check .NET Framework version using a .NET Framework version that may not exist? | [
"",
"c#",
".net",
""
] |
I'm trying to find all the files and folders under a specified directory
For example I have /home/user/stuff
I want to return
```
/home/user/stuff/folder1/image1.jpg
/home/user/stuff/folder1/image2.jpg
/home/user/stuff/folder2/subfolder1/image1.jpg
/home/user/stuff/image1.jpg
```
Hopefully that makes sense! | ```
function dir_contents_recursive($dir) {
// open handler for the directory
$iter = new DirectoryIterator($dir);
foreach( $iter as $item ) {
// make sure you don't try to access the current dir or the parent
if ($item != '.' && $item != '..') {
if( $item->isDir() ) {
// call the function on the folder
dir_contents_recursive("$dir/$item");
} else {
// print files
echo $dir . "/" .$item->getFilename() . "<br>";
}
}
}
}
``` | ```
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $f) {
echo "$f \r\n";
}
``` | Get the hierarchy of a directory with PHP | [
"",
"php",
"file",
"filesystems",
"directory",
""
] |
If I have a string variable that has:
```
"C:\temp\temp2\foo\bar.txt"
```
and I want to get
**"foo"**
what is the best way to do this? | Use:
```
new FileInfo(@"C:\temp\temp2\foo\bar.txt").Directory.Name
``` | Far be it for me to disagree with the Skeet, but I've always used
```
Path.GetFileNameWithoutExtension(@"C:\temp\temp2\foo\bar.txt")
```
I suspect that FileInfo actually touches the file system to get it's info, where as I'd expect that GetFileNameWithoutExtension is only string operations - so performance of one over the other might be better. | Parse directory name from a full filepath in C# | [
"",
"c#",
"file",
""
] |
How do I implement Auto-Scrolling (e.g. the ListView scrolls when you near the top or bottom) in a Winforms ListView? I've hunted around on google with little luck. I can't believe this doesn't work out of the box!
Thanks in advance
Dave | Scrolling can be accomplished with the [ListViewItem.EnsureVisible](https://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.ensurevisible(v=vs.110).aspx) method.
You need to determine if the item you are currently dragging over is at the visible boundary of the list view and is not the first/last.
```
private static void RevealMoreItems(object sender, DragEventArgs e)
{
var listView = (ListView)sender;
var point = listView.PointToClient(new Point(e.X, e.Y));
var item = listView.GetItemAt(point.X, point.Y);
if (item == null)
return;
var index = item.Index;
var maxIndex = listView.Items.Count;
var scrollZoneHeight = listView.Font.Height;
if (index > 0 && point.Y < scrollZoneHeight)
{
listView.Items[index - 1].EnsureVisible();
}
else if (index < maxIndex && point.Y > listView.Height - scrollZoneHeight)
{
listView.Items[index + 1].EnsureVisible();
}
}
```
Then wire this method to the DragOver event.
```
targetListView.DragOver += RevealMoreItems;
targetListView.DragOver += (sender, e) =>
{
e.Effect = DragDropEffects.Move;
};
``` | Thanks for the link (<http://www.knowdotnet.com/articles/listviewdragdropscroll.html>), I C#ised it
```
class ListViewBase:ListView
{
private Timer tmrLVScroll;
private System.ComponentModel.IContainer components;
private int mintScrollDirection;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
const int WM_VSCROLL = 277; // Vertical scroll
const int SB_LINEUP = 0; // Scrolls one line up
const int SB_LINEDOWN = 1; // Scrolls one line down
public ListViewBase()
{
InitializeComponent();
}
protected void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tmrLVScroll = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// tmrLVScroll
//
this.tmrLVScroll.Tick += new System.EventHandler(this.tmrLVScroll_Tick);
//
// ListViewBase
//
this.DragOver += new System.Windows.Forms.DragEventHandler(this.ListViewBase_DragOver);
this.ResumeLayout(false);
}
protected void ListViewBase_DragOver(object sender, DragEventArgs e)
{
Point position = PointToClient(new Point(e.X, e.Y));
if (position.Y <= (Font.Height / 2))
{
// getting close to top, ensure previous item is visible
mintScrollDirection = SB_LINEUP;
tmrLVScroll.Enabled = true;
}else if (position.Y >= ClientSize.Height - Font.Height / 2)
{
// getting close to bottom, ensure next item is visible
mintScrollDirection = SB_LINEDOWN;
tmrLVScroll.Enabled = true;
}else{
tmrLVScroll.Enabled = false;
}
}
private void tmrLVScroll_Tick(object sender, EventArgs e)
{
SendMessage(Handle, WM_VSCROLL, (IntPtr)mintScrollDirection, IntPtr.Zero);
}
}
``` | C# Implementing Auto-Scroll in a ListView while Drag & Dropping | [
"",
"c#",
"winforms",
"listview",
"drag-and-drop",
"scroll",
""
] |
I'm looping a two-dimensional array like this:
```
if (!empty($aka)) {
foreach ($aka as $ak) {
if($ak["lang"]=="es") {
$sptitle=$ak["title"];
}
}
}
```
Pretty simple. If the array ($aka) is not empty I loop trough it and when it finds that the "lang" index is equal to "es" I just save the "title" value for that index in $sptitle.
The problem is that the array ($aka) contains a lot of information and sometimes there is no "lang" index... and I get this error: Notice: Undefined index: lang.
How can I fix this???
This is a extract of the array to help you understand. Notice that [1] doesn't have a [lang] index but [2] does have:
```
[1] => Array
(
[title] => "The Lord of the Rings: The Motion Picture"
[year] => ""
[country] => "USA"
[comment] => "promotional title"
)
[2] => Array
(
[title] => "Señor de los anillos: La comunidad del anillo, El"
[year] => ""
[country] => "Argentina"
[comment] => "Chile, Mexico, Peru, Spain"
[lang] => "es"
)
```
Thanks! | Just test for it with [isset](http://php.net/isset), e.g.
```
if (!empty($aka)) {
foreach ($aka as $ak) {
if(isset($ak["lang"]) && ($ak["lang"]=="es")) {
$sptitle=$ak["title"];
}
}
}
```
If you're unaware of how a boolean operator like && can be short circuited, if the first operand is false, then the second operand won't be evaluated. You'll often see this idiom employed in checking for the availablilty of something before acting on it in the second operand.
You could also use [array\_key\_exists](http://php.net/array_key_exists)('lang', $aka) instead of isset, it has slightly different semantics though - it will return true if an element is set to `null`, whereis isset would return false.
Interestingly, [isset is at least twice as fast as array\_key\_exists](http://us.php.net/manual/en/function.array-key-exists.php#82867), possibly due to the fact that it is a language construct rather than a regular function call. | would it be wrong to use:
```
if (@$ak['lang'])
```
i really miss the fact that we can't still do the 2 checks in 1 like so
```
if ($ak['lang'])
```
it was one of the beautiful things about PHP and I just don't see the purpose of warning whether an array key is initialised in a transient scripting language like PHP.
i'm not sure where the developers of PHP are going with this. personally, i'm a bit worried that they're morphing PHP into something else. just leave it alone. it was great. | PHP Notice: Undefined index when looping array | [
"",
"php",
"arrays",
""
] |
How do I get the next element in HTML using JavaScript?
Suppose I have three `<div>`s and I get a reference to one in JavaScript code, I want to get which is the next `<div>` and which is the previous. | Well in pure javascript my thinking is that you would first have to collate them inside a collection.
```
var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");
```
So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds
```
for(var i = 0; i < divs.length;i++)
{
if(divs[i] == selectionDiv)
{
var previous = divs[i - 1];
var next = divs[i + 1];
}
}
```
Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.
This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the **tagName** property. | use the [`nextSibling`](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling) and [`previousSibling`](https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling) properties:
```
<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>
document.getElementById('foo2').nextSibling; // #foo3
document.getElementById('foo2').previousSibling; // #foo1
```
However in some browsers (I forget which) you also need to check for whitespace and comment nodes:
```
var div = document.getElementById('foo2');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling
}
```
Libraries like jQuery handle all these cross-browser checks for you out of the box. | Get next / previous element using JavaScript? | [
"",
"javascript",
"html",
"dom",
""
] |
I need to start an external process from my web application. This means using *System.Diagnostics.ProcessStartInfo* to call out and execute a console app (exe). But I then need to somehow ***make sure nothing went wrong*** during its execution **and know when the application completed** its work.
**What's the best way to both catch all possible errors and find out when it's completed?** | I sure hope you have control of the code for the external application or you are in for a lot of headaches. The MOST important thing to do is make sure there is no way for that application to hang and not terminate.
You can then use the WaitForExit(), ExitCode, StandardError, StandardOut to "catch all possible errors and find out when it's completed" | It's not so hard with the Process class. Though, the prior poster was correct - you need to be concerned about permissions.
```
private string RunProcess(string cmd)
{
System.Diagnostics.Process p;
p= new System.Diagnostics.Process();
if (cmd== null || cmd=="") {
return "no command given.";
}
string[] args= cmd.Split(new char[]{' '});
if (args== null || args.Length==0 || args[0].Length==0) {
return "no command provided.";
}
p.StartInfo.FileName= args[0];
if (args.Length>1) {
int startPoint= cmd.IndexOf(' ');
string s= cmd.Substring(startPoint, cmd.Length-startPoint);
p.StartInfo.Arguments= s;
}
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
// must have the readToEnd BEFORE the WaitForExit(), to avoid a deadlock condition
string output= p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
``` | Starting external process from ASP.NET | [
"",
"c#",
".net",
"asp.net",
""
] |
I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:
```
@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
```
The argument to the decorator is completely separate from the argument to the function it's wrapping. I've looked at quite a few examples but I'm not quite getting how to do this - is it possible to have an argument for the decorator that's unrelated to and not passed to the wrapped function? | The idea is that your decorator is a function returning a decorator.
**FIRST** Write your decorator as if you knew your argument was a global variable. Let's say something like:
-
```
def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if cache.iscached(*args,**kwargs):
...
else:
res = f(*args,**kwargs)
cache.store((*args,**kwargs), res)
return res
return decorated
```
**THEN** Write a function that takes cachepath as an arg and return your decorator.
-
```
def cache(filepath)
def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if cache.iscached(*args,**kwargs):
...
else:
res = f(*args,**kwargs)
cache.store((*args,**kwargs), res)
return res
return decorated
return decorator
``` | Yes it is. As you know, a decorator is a function. When written in the form:
```
def mydecorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@mydecorator
def foo(a, b, c):
pass
```
the argument passed to `mydecorator` is the function `foo` itself.
When the decorator accepts an argument, the call `@mydecorator('/path/to')` is actually going to call the mydecorator function with '/path/to' first. Then the result of the call to `mydecorator(path)` will be called to receive the function `foo`. You're effectively defining a dynamic wrapper function.
In a nutshell, you need another layer of decorator functions.
Here is this slightly silly example:
```
def addint(val):
def decorator(func):
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
return result + val
return wrapped # returns the decorated function "add_together"
return decorator # returns the definition of the decorator "addint"
# specifically built to return an extra 5 to the sum
@addint(5)
def add_together(a, b):
return a + b
print add_together(1, 2)
# prints 8, not 3
``` | Python: decorator specific argument (unrelated to wrapped function)? | [
"",
"python",
"decorator",
""
] |
I want to be able to store, retrieve, and modify a small amount of textual data (< 2 mb) as a CSV online. What service should I use to be able to do this programatically (in Java)? | Try Google Spreadsheets ([Java API Reference](http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_java.html)). You can [upload a CSV](http://code.google.com/apis/documents/docs/2.0/developers_guide_java.html#UploadingSpreadsheet) which gets automatically converted to a spreadsheet, then you can [query](http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_java.html#SendingStructuredQueries) or edit it programmatically, or [manipulate it online](http://docs.google.com/), then if you need to get it as CSV you can [export it](http://code.google.com/apis/documents/docs/2.0/developers_guide_protocol.html#DownloadingSpreadsheets). | You can try Google's App Engine. <http://code.google.com/appengine/docs/whatisgoogleappengine.html>
Also there is Amazon S3. <http://aws.amazon.com/s3/>
I know a few Open Source people using these tools to store online persistent data to useful effect. | What is the best place to read/write/store a small amount of data online? | [
"",
"java",
"csv",
"storage",
""
] |
Here's my reqiurements:
1. Supports C#
2. Supports Oracle
3. Supports LINQ
4. Has ability to map business objects to database tables (not necessarily a 1-to-1 mapping)
I know an Oracle Entity Framework provider would support all these, but I've been told that making the custom mappings is not very easy.
What would you suggest? | I'd use nHibernate. The linq support is coming. Not sure if its in their latest build or not but they just released a beta of their next release. It supports the rest of your requirements. | If you want something that has native linq support as well as supporting all the features above, I'd have a look at [llblgen pro](http://www.llblgen.com/defaultgeneric.aspx) or there's a new player called [Genome](http://www.genom-e.com/).
llblgen pro has been around for a long time and having used it on previous projects would recommend you check it out. | What ORM would you recommend? | [
"",
"c#",
"linq",
"oracle",
"orm",
""
] |
I'm developing a website with Ruby on Rails and I have a div with some content. After clicking a link I want that content to get replaced with some other stuff. This works fine with replace\_html and rjs.
However, I'd prefer there to be a slight fade/appear (crossfade?) transition between the old and new content. Also the div will be resized a bit so it'd be cooler if this did a grow/shrink effect. I was thinking Scriptaculous must have something like this built in, but I sure can't find it if they do.
By the way there is a great example of this if you have a Basecamp account: login and click "All people" then "Add a new company" to see the effect in action.
Anyone know how to do this? Thanks!
Brian | To crossfade, you need to position your new content absolutely, and with the same x/y coordinates as the old content. Here's a tested example:
```
page.insert_html :after, 'old-content', content_tag('p', '[new content]', :id => 'new-content', :style => 'display:none')
page << <<-JS
var oldOffset = $('old-content').cumulativeOffset();
$('new-content').setStyle({
position: 'absolute',
left: oldOffset.left + 'px',
top: oldOffset.top + 'px'
});
JS
page['old-content'].fade :duration => 3
page['new-content'].appear :duration => 3
```
Note the big block in the middle—some things are easier in Prototype than in RJS. | A strategy could be to put the element in a wrapping div, fade out that wrapping div, replace the HTML in the element, and then fade in the wrapping div again.
I'm not a RJS/scriptaculous user myself, so I'm not sure what the code is, but I'm pretty sure that strategy will work. | Can you combine replace_html with a visual_effect in Rails RJS? | [
"",
"javascript",
"ruby-on-rails",
"ajax",
"scriptaculous",
""
] |
Why are so many people still writing crappy versions of things in standard libraries? Not to go after PHP developers, but guys go read the [PHP SPL](https://www.php.net/spl) | **Better search techniques.** and **Domain Specific Familiarity**
How does a developer check for a function they dont know the name of? Or perhaps there isnt an EXACT built in function to do what they want, but something they can use to save a lot of code. You need to be able to find the right terminology for the problem at hand, and from there you know what to search for. This is best achived by reading topics specific to your problem domain. Get away from coding specific resources and spend sometime in the field which you are coding for... wether it be retail, medical, insurance, etc. | Peer review can help catch that kind of thing. If you have another developer looking at the code, and they continually find implementations of standard library methods, it should fail the review unless there's a good reason for reinventing the wheel. | How do we get coders to look up existing functions before writing their own? | [
"",
"php",
"spl",
""
] |
I need to build a URL with a query string in C#. What is the best approach to doing this? Right now, I'm using something like,
```
string url = String.Format("foo.aspx?{0}={1}&{2}={3}", "a", 123, "b", 456);
```
Is there a better, preferred approach? | I think that is a good method if it's always know what parameters you have, if this is unknown at the time you could always keep a List<KeyValuePair<string,string>> with the key being the name and value being the value, then build the query string using a foreach loop like
```
StringBuilder sb = new StringBuilder();
foreach(KeyValuePair<string,string> q in theList)
{
// build the query string here.
sb.Append(string.format("{0}={1}&", q.Key, q.Value);
}
```
note: the code is not tested and has not been compiled, so it may not work exactly as is. | I think you should be using Server.UrlEncode on each of the arguments so that you don't send any bad characters in the URL. | url building in C# | [
"",
"c#",
"url",
""
] |
Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds? | It looks like a timespan. So simple parse the text and get the seconds.
```
string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;
``` | You can use the parse method on aTimeSpan.
<http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx>
```
TimeSpan ts = TimeSpan.Parse( "10:20:30" );
double totalSeconds = ts.TotalSeconds;
```
The TotalSeconds property returns the total seconds if you just want the seconds then use the seconds property
```
int seconds = ts.Seconds;
```
Seconds return '30'.
TotalSeconds return 10 \* 3600 + 20 \* 60 + 30 | How do i convert HH:MM:SS into just seconds using C#.net? | [
"",
"c#",
".net",
"datetime",
""
] |
Can JavaScript load an RSS XML feed from [Yahoo](http://finance.yahoo.com/rss/topstories)?
Is client-side JS allowed to access 3rd-party domains? | You can use the technique outlined in my blog post [Unwritten guide to Yahoo Query Langauge](http://jawtek.blogspot.com/2009/03/unwritten-guide-to-yahoo-query-langauge.html)
You would query the XML data table with a yql statment like this:
```` ```
select * from xml
where url="http://path/to/xml
``` ````
Then you would add a script tag to your html (can be done with document.createElement('script')) with a src http://query.yahooapis.com/v1/public/yql?q={your yql here}&format=json&callback={your function here} where {your yql here} is replace with a URI Encoded version of you yql statment. | An easy way to do this is to proxy the request through the server that your page resides on. Steps are:
1. Write a server side script performs an http request on the rss feed, when that script itself is request (i.e. via get or post)
2. Use ajax to request the server side script, or just call it from the main script for that page.
3. The server side script then returns the feed source in some displayable form.
4. Profit!
On IE 8 and FF 3.1(not certain), it is possible to make these requests through specialized cross site calls, but the last generation of browsers will still cause problems. See:
<http://dannythorpe.com/2009/01/15/ie8-cross-domain-request-support-demo/>
<http://ejohn.org/blog/cross-site-xmlhttprequest/> Feature is restricted in FF 3.0, unclear if it will be back in 3.1
However, the steps above are guaranteed not to run afoul of any browser CSS security, at the expense of some lag and extra hw load on your server. | Can JavaScript load XML data from a third-party domain? | [
"",
"javascript",
"rss",
"cross-domain",
""
] |
**2013 Edit:** `async` and `await` now make this trivial! :-)
---
I've got some code that screen scrapes a website (**for illustrative purposes only**!)
```
public System.Drawing.Image GetDilbert()
{
var dilbertUrl = new Uri(@"http://dilbert.com");
var request = WebRequest.CreateDefault(dilbertUrl);
string html;
using (var webResponse = request.GetResponse())
using (var receiveStream = webResponse.GetResponseStream())
using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
html = readStream.ReadToEnd();
var regex = new Regex(@"dyn/str_strip/[0-9/]+/[0-9]*\.strip\.gif");
var match = regex.Match(html);
if (!match.Success) return null;
string s = match.Value;
var groups = match.Groups;
if (groups.Count > 0)
s = groups[groups.Count - 1].ToString(); // the last group is the one we care about
var imageUrl = new Uri(dilbertUrl, s);
var imageRequest = WebRequest.CreateDefault(imageUrl);
using (var imageResponse = imageRequest.GetResponse())
using (var imageStream = imageResponse.GetResponseStream())
{
System.Drawing.Image image_ = System.Drawing.Image.FromStream(imageStream, true /*useEmbeddedColorManagement*/, true /*validateImageData*/);
return (System.Drawing.Image)image_.Clone(); // "You must keep the stream open for the lifetime of the Image."
}
}
```
Now, I would like to call GetDilbert() asynchronously. The easy way to use a delegate:
```
Func<System.Drawing.Image> getDilbert;
IAsyncResult BeginGetDilbert(AsyncCallback callback, object state)
{
getDilbert = GetDilbert;
return getDilbert.BeginInvoke(callback, state);
}
System.Drawing.Image EndGetDilbert(IAsyncResult result)
{
return getDilbert.EndInvoke(result);
}
```
While that certainly works, it isn't very efficient as the delegate thread will spend most of its time waiting for the two I/O operations.
What I would like to do is to call `request.BeginGetResponse()`, do the regex match, and then call `imageRequest.BeginGetResponse()`. All while using the standard async call pattern and preserving the signatures of *BeginGetDilbert()* and *EndGetDilbert()*.
I've tried several approaches and haven't been completely satisfied with any of them; this seems to be a royal pain. Hence, the question. :-)
---
EDIT: Its seems that the approaches using iterators are [frowned on by the C# compiler team](http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx#8870195).
> A plea from the compiler team:
>
> Though it is assuredly the case that
> you CAN use iterators to implement
> state machines, poor-mans coroutines,
> and so on, I wish people would not do
> so.
>
> Please use tools for the purposes for
> which they were intended. If you want
> to write state machines, write
> yourself a library that is designed
> specifically to solve that general
> problem and then use it.
>
> Using tools for purposes other than
> what they were intended for is
> "clever", and clever is bad; clever is
> hard for maintenance programemrs to
> understand, clever is hard to extend,
> clever is hard to reason about, clever
> makes people think "out of the box";
> there's good stuff in that box.
---
Going with the `Future<>` answer because that stays in C# which is the same as my sample code. Unfortunately, neither the TPL nor F# are officially supported by Microsoft...yet. | ```
public Image GetDilbert()
{
var dilbertUrl = new Uri(@"http://dilbert.com");
var request = WebRequest.CreateDefault(dilbertUrl);
var webHandle = new ManualResetEvent(false /* nonsignaled */);
Image returnValue = null;
request.BeginGetResponse(ar =>
{
//inside AsynchCallBack method for request.BeginGetResponse()
var response = (HttpWebResponse) request.EndGetResponse(ar);
string html;
using (var receiveStream = response.GetResponseStream())
using (var readStream = new StreamReader( receiveStream
, Encoding.UTF8))
{
html = readStream.ReadToEnd();
}
var re=new Regex(@"dyn/str_strip/[0-9/]+/[0-9]*\.strip\.gif");
var match=re.Match(html);
var imgHandle = new ManualResetEvent(true /* signaled */);
if (match.Success)
{
imgHandle.Reset();
var groups = match.Groups;
var s = (groups.Count>0) ?groups[groups.Count-1].ToString()
:match.Value;
var _uri = new Uri(dilbertUrl, s);
var imgReq = WebRequest.CreateDefault(_uri);
imgReq.BeginGetResponse(ar2 =>
{ var imageRsp= (HttpWebResponse)imgReq.EndGetResponse(ar2);
using (var imgStream=imageRsp.GetResponseStream())
{
var im=(Image)Image.FromStream(imgStream,true,true);
returnValue = (Image) im.Clone();
}
imgHandle.Set();
}, new object() /*state*/);
}
imgHandle.WaitOne();
webHandle.Set();
}, new object() /* state */);
webHandle.WaitOne();
return returnValue;
}
```
For the Begin/EndGetDilbert() methods, you can use a technique with `Future<T>` as described at <http://blogs.msdn.com/pfxteam/archive/2008/02/29/7960146.aspx>
*See also <http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx>* | It is kind of a nightmare to get this right. You need to create callbacks to pass into each 'Begin' method that then run the 'continuation' of the method. (And don't forget to ensure all the exception-handling and CompletedSynchronously logic is correct!) When you author this in C# today, your code turns into a hopeless mess of spaghetti, but that's about the only way you can achieve your goal (not have threads blocking on I/O waits).
On the other hand, if it's within reason for your situation, [F#](http://fsharp.net) makes this very simple and straightforward to author correctly. See [this video](http://channel9.msdn.com/pdc2008/TL11/) (namely, 8 minutes starting at 52:20) for a synopsis.
EDIT
to answer Dan's comment, here is a very rough sketch... I pulled it from an email I wrote in outlook, I doubt it compiles. The exception paths are always gnarly, so be careful (what if ‘cb’ throws?); you may want to find a rock-solid AR/Begin/End implementation in C# somewhere (I dunno where, I’m sure there must be many) and use it as a model, but this shows the gist. The thing is, once you author this once, you have it for all time; BeginRun and EndRun work as the 'begin/end' on any F# async object. We have a suggestion in the F# bug database to expose the Begin/End APM on top of async in a future release of the F# library, so as to make it easier to consume F# async computations from traditional C# code. (And of course we're striving to work better with 'Task's from the parallel task library in .Net 4.0 as well.)
```
type AR<’a>(o,mre,result) =
member x.Data = result
interface IAsyncResult with
member x.AsyncState = o
member x.AsyncWaitHandle = mre
member x.CompletedSynchronously = false
member x.IsCompleted = mre.IsSignalled
let BeginRun(a : Async<’a>, cb : AsyncCallback, o : obj) =
let mre = new ManualResetEvent(false)
let result = ref None
let iar = new AR(o,mre,result) :> IAsyncResult
let a2 = async {
try
let! r = a
result := Choice2_1(r)
with e ->
result := Choice2_2(e)
mre.Signal()
if cb <> null then
cb.Invoke(iar)
return ()
}
Async.Spawn(a2)
iar
let EndRun<’a>(iar) =
match iar with
| :? AR<’a> as ar ->
iar.AsyncWaitHandle.WaitOne()
match !(ar.Data) with
| Choice2_1(r) -> r
| Choice2_2(e) -> raise e
``` | How can I easily chain two asynchronous requests together? | [
"",
"c#",
".net",
"multithreading",
"asynchronous",
"iasyncresult",
""
] |
I am trying to write a Java applet that will read from a user's serial port. For this I am using the [Java Comm API](http://java.sun.com/products/javacomm/) in conjuction with the [RXTX library](http://www.rxtx.org/). I've successfully managed to read data through a local Java application but I can't seem to do the same from within an applet. The problem is that the RXTX library is a native library and I haven't found a way to load this library inside the Java applet. I've found two interesting articles (Using [JNI in Applets](http://mindprod.com/jgloss/jni.html#APPLETS) which references to [this article](http://www.javaworld.com/jw-10-1998/jw-10-apptowin32.html)), but both are over 10 years old and I am wondering if there is a newer solution. Or if you can suggest an alternative, I would love to hear it! | Use Java Web Start. You can include the native library as a signed jar and everything should work.
1) put the native librarys in a jar in the ROOT directory
2) sign ALL the jars
3) write a JNLP referencing all the jars (go do a search on how to write jnlp's)
after that it should work | Firstly I'd suggest doing that in an Applet is probably a bad idea.
If you do go ahead anyway, [JNLPAppletLauncher](https://applet-launcher.dev.java.net/) may help. | Dynamically loading a native library inside Java applet | [
"",
"java",
"applet",
"java-native-interface",
"rxtx",
""
] |
Imagine this... I have a field in the database titled 'current\_round'. This may only be in the range of 0,1,2,3.
Through the application logic, it is impossible to get a number above 3 or less than 0 into the database.
Should there be error checking in place to see if the value is malformed (i.e. not in the range 0-3)? Or is this just unnecessary overhead? Is it OK to assume values in a database are correctly formatted/ranged etc (assuming you sanatise/evaluate correctly all user input?) | I generally don't validate all data from the database. Instead I try to enforce constraints on the database. In your case depending on the meaning of 0, 1, 2, 3 I might use a lookup table with a foreign key constraint or if they are just numeric values I might use a check constraint (differs from DB vendor to the next).
This helps protect against changes made to the DB by someone with direct access and/or future applications that may use the same DB but not share your input validation process. | Wherever you decide to place validation prior to insertion in the database is where you should catch these things.
The process of validation should take place in one place and one place only. Depending on how your application is structured:
* Is it procedural or object oriented?
* If it is object oriented, then are you using an Active Record pattern, Gateway pattern or Data Mapper pattern to handle your database mapping?
* Do you have domain objects that are separate from your database abstraction layer?
Then you will need to decide on where to place this logic in your application.
In my case, domain objects contain the validation logic and functions with data mappers that actually perform the insert and update functions to the database. So before I ever attempt to save information to the database, I confirm that there are valid values. | Should a PHP application perform error handling on incorrect database values? | [
"",
"php",
"database",
""
] |
I've got a third-party component that does PDF file manipulation. Whenever I need to perform operations I retrieve the PDF documents from a document store (database, SharePoint, filesystem, etc.). To make things a little consistent I pass the PDF documents around as a `byte[]`.
This 3rd party component expects a `MemoryStream[]` (`MemoryStream` array) as a parameter to one of the main methods I need to use.
I am trying to wrap this functionality in my own component so that I can use this functionality for a number of areas within my application. I have come up with essentially the following:
```
public class PdfDocumentManipulator : IDisposable
{
List<MemoryStream> pdfDocumentStreams = new List<MemoryStream>();
public void AddFileToManipulate(byte[] pdfDocument)
{
using (MemoryStream stream = new MemoryStream(pdfDocument))
{
pdfDocumentStreams.Add(stream);
}
}
public byte[] ManipulatePdfDocuments()
{
byte[] outputBytes = null;
using (MemoryStream outputStream = new MemoryStream())
{
ThirdPartyComponent component = new ThirdPartyComponent();
component.Manipuate(this.pdfDocumentStreams.ToArray(), outputStream);
//move to begining
outputStream.Seek(0, SeekOrigin.Begin);
//convert the memory stream to a byte array
outputBytes = outputStream.ToArray();
}
return outputBytes;
}
#region IDisposable Members
public void Dispose()
{
for (int i = this.pdfDocumentStreams.Count - 1; i >= 0; i--)
{
MemoryStream stream = this.pdfDocumentStreams[i];
this.pdfDocumentStreams.RemoveAt(i);
stream.Dispose();
}
}
#endregion
}
```
The calling code to my "wrapper" looks like this:
```
byte[] manipulatedResult = null;
using (PdfDocumentManipulator manipulator = new PdfDocumentManipulator())
{
manipulator.AddFileToManipulate(file1bytes);
manipulator.AddFileToManipulate(file2bytes);
manipulatedResult = manipulator.Manipulate();
}
```
A few questions about the above:
1. Is the `using` clause in the `AddFileToManipulate()` method redundant and unnecessary?
2. Am I cleaning up things OK in my object's `Dispose()` method?
3. Is this an "acceptable" usage of `MemoryStream`? I am not anticipating very many files in memory at once...Likely 1-10 total PDF pages, each page about 200KB. App designed to run on server supporting an ASP.NET site.
4. Any comments/suggestions?
Thanks for the code review :) | 1. Is the using clause in the AddFileToManipulate() method redundant and unnecessary?
Worse, it's destructive. You're basically closing your memory stream before it's added in. See the other answers for details, but basically, dispose at the end, but not any other time. Every using with an object causes a Dispose to happen at the end of the block, even if the object is "passed off" to other objects via methods.
2. Am I cleaning up things OK in my object's Dispose() method?
Yes, but you're making life more difficult than it needs to be. Try this:
```` ```
foreach (var stream in this.pdfDocumentStreams)
{
stream.Dispose();
}
this.pdfDocumentStreams.Clear();
``` ````
This works just as well, and is much simpler. Disposing an object does not delete it - it just tells it to free it's internal, unmanaged resources. Calling dispose on an object in this way is fine - the object stays uncollected, in the collection. You can do this and then clear the list in one shot.
3. Is this an "acceptable" usage of MemoryStream? I am not anticipating very many files in memory at once...Likely 1-10 total PDF pages, each page about 200KB. App designed to run on server supporting an ASP.NET site.
This depends on your situation. Only you can determine whether the overhead of having these files in memory is going to cause you problems. This is going to be a fairly heavy-weight object, though, so I'd use it carefully.
4. Any comments/suggestions?
Implement a finalizer. It's a good idea whenever you implement IDisposable. Also, you should rework your Dispose implementation to the standard one, or mark your class as sealed. For details on how this should be done, [see this article.](http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx) In particular, you should have a method declared as `protected virtual void Dispose(bool disposing)` that your Dispose method and your finalizer both call. | AddFileToManipulate scares me.
```
public void AddFileToManipulate(byte[] pdfDocument)
{
using (MemoryStream stream = new MemoryStream(pdfDocument))
{
pdfDocumentStreams.Add(stream);
}
}
```
This code is adding a disposed stream to your pdfDocumentStream list. Instead you should simply add the stream using:
```
pdfDocumentStreams.Add(new MemoryStream(pdfDocument));
```
And dispose of it in the Dispose method.
Also you should look at implementing a finalizer to ensure stuff gets disposed in case someone forgets to dispose the top level object. | Does my code properly clean up its List<MemoryStream>? | [
"",
"c#",
"dispose",
"idisposable",
"memorystream",
""
] |
I have an installer class using `ServiceProcessInstaller`. In the installer class in the constructor I add it to installers:
```
serviceProcessInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// Add Both Installers to Project Installers Collection to be Run
Installers.AddRange(new Installer[]
{
serviceProcessInstaller,
serviceInstaller
});
```
and in Install method I set the username and password:
```
public override void Install(IDictionary stateSaver)
{
.... open the form, bla bla bla
serviceProcessInstaller.Password = accountForm.txtPassword.Text;
serviceProcessInstaller.Username = accountForm.txtServiceAccount.Text;
serviceProcessInstaller.Account = ServiceAccount.User;
}
```
when I try to run it however, I get the very descriptive error message: "No mapping between account names and security IDs was done". What am I doing wrong?
EDIT: I tested that this error happens only when I install this component using msi package. It works just fine when I run InstallUtil against it. | Found it finally: there seems to be a "feature" in `ServiceProcessInstaller`, where the code overwrites the values I provided explicitly with the values from the context. The MSI installer set the username to some crap (my company name), and `ServiceProcessInstaller` tried to install the service as this user and not the one explicitly provided by me. So the workaround is to set the correct values in the config:
```
public override void Install(IDictionary stateSaver)
{
.... open the form, bla bla bla
serviceProcessInstaller.Password = accountForm.txtPassword.Text;
Context.Parameters["PASSWORD"] = accountForm.txtPassword.Text;
serviceProcessInstaller.Username = accountForm.txtServiceAccount.Text;
Context.Parameters["USERNAME"] = accountForm.txtServiceAccount.Text;
serviceProcessInstaller.Account = ServiceAccount.User;
}
``` | Maybe its got something to do with your service account on you machine environment
* <http://www.shog9.com/log/archives/1-No-mapping-between-account-names-and-security-IDs-was-done.html>
* <http://support.microsoft.com/kb/890737>
* <http://bytes.com/groups/net-c/227254-serviceprocessinstaller-account-user-doesnt-work>
Hope the help to understand your situation. | ServiceProcessInstaller fails with "No mapping between account names and security IDs was done" | [
"",
"c#",
".net",
"web-services",
"installation",
""
] |
I don't get this. I really don't get the ReadEndElement. I assume after every ReadStartElement, you need to close off the reader to advanced to the next start element and if there's no more start elements, close by ReadEndElement for all other elements?
Sample of the returned XML:
```
<Envelope>
<Body>
<RESULT>
<SUCCESS>true</SUCCESS>
<SESSIONID>dc302149861088513512481</SESSIONID>
<ENCODING>dc302149861088513512481
</ENCODING>
</RESULT>
</Body>
</Envelope>
reader.Read();
reader.ReadStartElement("Envelope");
reader.ReadStartElement("Body");
reader.ReadStartElement("RESULT");
reader.ReadStartElement("SUCCESS");
reader.ReadEndElement();
reader.ReadStartElement("SESSIONID");
_sessionID = reader.ReadString();
reader.ReadEndElement();
reader.ReadEndElement(); <-- error here
reader.ReadEndElement();
reader.ReadEndElement();
```
I am ignoring one of the elements (ENCODING) retuned, because I don't need it...not sure if that has anything to do with it. Maybe I'm required to read every element regardless if I want to use it or not. | You have to read every node (attribute, element, ...) in the document.
If the reader is positioned on an element, you may skip it (and all its subnodes) with [XmlReader.Skip](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.skip.aspx). | I experienced this error when attempting to deserialize using the XmlSerializer. I have a valid XML which contained some `<br />` HTML tags which were un-encoded in my source document.
```
<Event>
<Id>1</Id>
<Title>The first Sicknote with Chris Liberator</Title>
<Copy>
Sicknote - Techno vs Dubstep <br />
------------------------------------<br />
<br /><br />
Thursday 8th October - 11pm - 4am
</Copy>
<Date>2009-10-08T10:00:00</Date>
<FlierImage>1.jpg</FlierImage>
</Event>
``` | 'Element' is an invalid XmlNodeType | [
"",
"c#",
"xml",
""
] |
There seems to be a lot of fuss about multicore and java. While some people say that java support is not [good enough](http://r-c-r.blogspot.com/2008/03/concurrency-support-in-java7-is-not.html), it definitely seems to be an area to look forward to. There seems to be [many](http://www.sdtimes.com/link/32943) [techniques](http://www.javaworld.com/javaworld/jw-11-2006/jw-1121-thread.html) to improve performance of concurrent programs.
Any tips/advices about programming in a multi core scenario is appreciated. | Look into the new Java concurrency facilities (in the [`java.util.concurrent` package](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html)) which have been added in Java 5. It provides functionality that is more high-level than regular `Thread`s which will make it easier (and less error-prone) to write concurrent applications. The [Lesson: Concurrency](http://java.sun.com/docs/books/tutorial/essential/concurrency/) of [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) would be a good place to start.
So far, I've only used the [`ExecutorService`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html), which allows can produce [thread pools](http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html), to which new tasks can be handed off in units of [`Runnable`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runnable.html)s or [`Callable`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html)s (which can return values after execution as [`Future`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html)s), and the actual threading code is handled by the `ExecutorService`.
For example, performing some calculation using a thread pool of 2 threads, and getting the result can be as simple as:
```
ExecutorService es = Executors.newFixedThreadPool(2);
Future f1 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Future f2 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Integer firstInteger = f1.get();
Integer secondInteger = f2.get();
```
In the above (untested) code, all I have to worry about is making a couple of `Callable`s and [`submit`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable))ing it to the `ExecutorService` and later on, using the `Future`s to retrieve the result.
The catch is, once the [`get`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html#get()) method of the `Future` is called, if the processing isn't complete, the program will stop until the result of the `Future` can be retrieved. So, in this example, even if the result of `f2` is available before `f1`, the program will wait until the result of `f1` is available.
In terms of reading material, on my list of books to purchase soon is [Java Concurrency in Practice](http://jcip.net/) by Brian Goetz, which comes up often when concurrency in Java is brought up.
The [Concurrency Utilities](http://java.sun.com/j2se/1.5.0/docs/guide/concurrency/) page from the Java 5 documentation has more information as well. | The best tip has got to be: *get your synchronization correct!*
This may seem somewhat obvious but an understanding of the [Java Memory Model](http://en.wikipedia.org/wiki/Java_Memory_Model) is vital, particularly how **volatile** and **final** fields work, how **synchronized** acts as both a mutex *and* a *memory barrier* and then the new `java.util.concurrent` constructs as well | Tips of coding java programs in multicore scenario | [
"",
"java",
"performance",
"concurrency",
"multicore",
""
] |
I'm using a custom named query with NHibernate which I want to return a collection of Person objects. The Person object is not mapped with an NHibernate mapping which means I'm getting the following exception:
> System.Collections.Generic.KeyNotFoundException:
> The given key was not present in the
> dictionary.
It's getting thrown when the Session gets created because it can't find the class name when it calls NHibernate.Cfg.Mappings.GetClass(String className). This is all fairly understandable but I was wondering if there was any way to tell NHibernate to use the class even though I haven't got a mapping for it? | To solve this, I ended up using the TupleToPropertyResultTransformer and providing the list of property values. There are a few limitations to this, the main one being that the SQL query must return the results in the same order as you provide your properties to the TupleToPropertyResultTransformer constructor.
Also the property types are inferred so you need to be careful with decimal columns returning only integer values etc. Apart from that using the TupleToPropertyResultTransformer provided a reasonably easy way to use an SQL query to return a collection of objects without explicitly mapping the objects within NHibernate. | Why don't you use:
`query.SetResultTransformer(Transformers.AliasToBean(typeof(Person)));`
It will insert data from each column in your query into Person object properties using column alias as a property name. | Using Unmapped Class with NHibernate Named Query | [
"",
"c#",
"nhibernate",
"named-query",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.