Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron. I will click on a link and it will hang for a while. I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit. So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?" I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage). Does anybody know of a plugin that does this, or something similar? Has anyone else done this kind of inspection another way? I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources. Any suggestions or insights?
It's probably the [awesome firefox3 fsync "bug"](http://shaver.off.net/diary/2008/05/25/fsyncers-and-curveballs/), which is a giant pile of fail. In summary * Firefox3 saves its bookmarks and history in an SQLite database * Every time you load a page it writes to this database several times * SQLite cares deeply that you don't lose your bookmarks, so each time it writes, instructs the kernel to flush it's database file to disk and ensure that it's fully written * Many variants of linux, when told to flush like that, flush EVERY FILE. This may take up to a minute or more if you have background tasks doing any kind of disk intensive stuff. * The kernel makes firefox wait while this flush happens, which locks up the UI.
> So, my question is, is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3? Because of the way Firefox is built this is not possible at the moment. But the new Internet Explorer 8 Beta 2 and the just announced Google Chrome browser are heading in that direction, so I suppose Firefox will be heading there too. Here is a post ( [Google Chrome Process Manager](http://ejohn.org/blog/google-chrome-process-manager/) ),by John Resig from Mozilla and jQuery fame on the subject.
Some kind of task manager for JavaScript in Firefox 3?
[ "", "javascript", "firefox", "memory", "cpu", "" ]
I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
From the [Python Enterprise Application Kit community](http://peak.telecommunity.com/DevCenter/PythonEggs): > *"Eggs are to Pythons as Jars are to Java..."* > > Python eggs are a way of bundling > additional information with a Python > project, that allows the project's > dependencies to be checked and > satisfied at runtime, as well as > allowing projects to provide plugins > for other projects. There are several > binary formats that embody eggs, but > the most common is '.egg' zipfile > format, because it's a convenient one > for distributing projects. All of the > formats support including > package-specific data, project-wide > metadata, C extensions, and Python > code. > > The primary benefits of Python Eggs > are: > > * They enable tools like the "Easy Install" Python package manager > * .egg files are a "zero installation" format for a Python > package; no build or install step is > required, just put them on PYTHONPATH > or sys.path and use them (may require > the runtime installed if C extensions > or data files are used) > * They can include package metadata, such as the other eggs they depend on > * They allow "namespace packages" (packages that just contain other > packages) to be split into separate > distributions (e.g. zope.*, twisted.*, > peak.\* packages can be distributed as > separate eggs, unlike normal packages > which must always be placed under the > same parent directory. This allows > what are now huge monolithic packages > to be distributed as separate > components.) > * They allow applications or libraries to specify the needed > version of a library, so that you can > e.g. require("Twisted-Internet>=2.0") > before doing an import > twisted.internet. > * They're a great format for distributing extensions or plugins to > extensible applications and frameworks > (such as Trac, which uses eggs for > plugins as of 0.9b1), because the egg > runtime provides simple APIs to locate > eggs and find their advertised entry > points (similar to Eclipse's > "extension point" concept). > * There are also other benefits that may come from having a standardized > format, similar to the benefits of > Java's "jar" format. -Adam
One egg by itself is not better than a proper source release. The good part is the dependency handling. Like debian or rpm packages, you can say you depend on other eggs and they'll be installed automatically (through [pypi.python.org](http://pypi.python.org)). A second comment: the egg format itself is a binary packaged format. Normal python packages that consist of just python code are best distributed as "source releases", so "python setup.py sdist" which result in a .tar.gz. These are also commonly called "eggs" when uploaded to pypi. Where you need binary eggs: when you're bundling some C code extension. You'll need several binary eggs (a 32bit unix one, a windows one, etc.) then.
What are the advantages of packaging your python library/application as an .egg file?
[ "", "python", "zip", "packaging", "software-distribution", "egg", "" ]
It strikes me that Properties in C# should be use when trying to manipulate a field in the class. But when there's complex calculations or database involved, we should use a getter/setter. Is this correct? When do you use s/getter over properties?
The .NET design guidelines provide some answers to this question in the [Properties vs. Methods](http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1) section. Basically, properties have the same semantics as a field. You shouldn't let a property throw exceptions, properties shouldn't have side effects, order shouldn't matter, and properties should return relatively quickly. If any of those things could happen, it's better to use a method. The guidelines also recommend using methods for returning arrays. When deciding whether to use a property or method, it helps if I think of it like a field. I think about the behavior of the property and ask myself, "If this were a field on the class, would I be surprised if it behaved the way it does?" Consider, for example, the [TcpClient.GetStream method](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream.aspx). It can throw several exceptions based on if the connection is made, and it's important that the TcpClient is configured before you try to get the stream. Because of this, it is a Get method rather than a property. If you take a good look at the design guidelines, you'll see that it's usually *not* a matter of preference; there's good reasons to use methods instead of properties in certain cases.
If your language supports properties, just use properties.
Convention question: When do you use a Getter/Setter function rather than using a Property
[ "", "c#", "" ]
I want to be able to play sound files in my program. Where should I look?
I wrote the following code that works fine. But I think it only works with `.wav` format. ``` public static synchronized void playSound(final String url) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); } ```
A bad example: ``` import sun.audio.*; //import the sun.audio package import java.io.*; //** add this into your application code as appropriate // Open an input stream to the audio file. InputStream in = new FileInputStream(Filename); // Create an AudioStream object from the input stream. AudioStream as = new AudioStream(in); // Use the static class member "player" from class AudioPlayer to play // clip. AudioPlayer.player.start(as); // Similarly, to stop the audio. AudioPlayer.player.stop(as); ```
How can I play sound in Java?
[ "", "java", "audio", "" ]
What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#? Anyone want to post a good custom one you created yourself? [Anyone?... Bueller?](http://en.wikipedia.org/wiki/Ferris_Bueller)
Microsoft have released a whole bunch of C# snippets that bring it up to parity with the ones for Visual Basic. You can download them here: <http://msdn.microsoft.com/en-us/library/z41h7fat.aspx>
My absolute favorite is `cw`.
What are the most useful (custom) code snippets for C#?
[ "", "c#", "visual-studio", "code-snippets", "" ]
I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. Currently, I'm just using [include\_once](http://php.net/manual/en/function.include-once.php) to include the classes I access directly. Each of those would `include_once` the classes that they access. I've looked into using the `__autoload` function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. ***Also, I'm not sure how this effects classes with the same name in different namespaces.*** **Is there an easier way to handle this?** Or is PHP just not suited to "**enterprisey**" type applications with lots of different objects all located in separate files that can be in many different directories.
I my applications I usually have `setup.php` file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map. Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, \_\_autoload function looks up class name in that array and gets include path. Here's the code: **autobuild.php** ``` define('MAP', 'var/cache/autoload.map'); error_reporting(E_ALL); require 'setup.php'; print(buildAutoloaderMap() . " classes mapped\n"); function buildAutoloaderMap() { $dirs = array('lib', 'view', 'model'); $cache = array(); $n = 0; foreach ($dirs as $dir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) { $fn = $entry->getFilename(); if (!preg_match('/\.class\.php$/', $fn)) continue; $c = str_replace('.class.php', '', $fn); if (!class_exists($c)) { $cache[$c] = ($pn = $entry->getPathname()); ++$n; } } } ksort($cache); file_put_contents(MAP, serialize($cache)); return $n; } ``` **autoload.php** ``` define('MAP', 'var/cache/autoload.map'); function __autoload($className) { static $map; $map or ($map = unserialize(file_get_contents(MAP))); $fn = array_key_exists($className, $map) ? $map[$className] : null; if ($fn and file_exists($fn)) { include $fn; unset($map[$className]); } } ``` Note that file naming convention must be [class\_name].class.php. Alter the directories classes will be looked in `autobuild.php`. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop. Serialized arrays are darn fast. @JasonMichael: PHP 4 is dead. Get over it.
You can define multiple autoloading functions with spl\_autoload\_register: ``` spl_autoload_register('load_controllers'); spl_autoload_register('load_models'); function load_models($class){ if( !file_exists("models/$class.php") ) return false; include "models/$class.php"; return true; } function load_controllers($class){ if( !file_exists("controllers/$class.php") ) return false; include "controllers/$class.php"; return true; } ```
How to handle including needed classes in PHP
[ "", "php", "class", "include", "autoload", "" ]
This is driving me crazy. I have this one php file on a test server at work which does not work.. I kept deleting stuff from it till it became ``` <? print 'Hello'; ?> ``` it outputs > Hello if I create a new file and copy / paste the same script to it it works! Why does this one file give me the strange characters all the time?
That's the [BOM (Byte Order Mark)](http://en.wikipedia.org/wiki/Byte_Order_Mark) you are seeing. In your editor, there should be a way to force saving without BOM which will remove the problem.
Found it, file -> encoding -> UTF8 with BOM , changed to to UTF :-) I should ahve asked before wasing time trying to figure it out :-)
Strange characters in PHP
[ "", "php", "encoding", "" ]
I'm using [Zend Studio](http://www.zend.com/en/products/studio/) to do remote debugging of my php scripts on a dev server. It works great for web code, but can I make it work with command line scripts? I have several helper apps to make my application run. It would be really useful to fire up the remote debugger through command line instead of a web browser so I can test these out. I assume it's possible, since I think Zend is using xdebug to talk to Eclipse. Apparently, it adds some parameters to the request to wake the Zend code up on a request. I'm guessing I'd need to tap into that? *UPDATE* I ended up using xdebug with [protoeditor](http://protoeditor.sourceforge.net/) over X to do my debugging.
I was able to get [remote CLI debugging working in Eclipse](http://thenazg.blogspot.com/2008/12/remote-cli-debugging-via-eclipse-pdt.html), using xdebug, though I've not tried it with the zend debugger. I would assume this should work the same with ZSfE, if that's the "Zend Studio" you're using.
Since this is more along the lines of product support, your best bet is probably emailing the support people. We bought Zend Studio at my last job and they were always able to help us in a matter of hours. Feel free to post the answer though, I am sure there are more people looking for it. :)
Remote Debugging PHP Command Line Scripts with Zend?
[ "", "php", "debugging", "xdebug", "zend-studio", "" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?
The python-magic method suggested by [toivotuo](https://stackoverflow.com/a/2133843/5337834) is outdated. [Python-magic's](http://github.com/ahupp/python-magic) current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. ``` # For MIME types import magic mime = magic.Magic(mime=True) mime.from_file("testdata/test.pdf") # 'application/pdf' ```
The [mimetypes module](https://docs.python.org/library/mimetypes.html) in the standard library will determine/guess the MIME type from a file extension. If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the [UploadedFile](https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects) object.
How to find the mime type of a file in python?
[ "", "python", "mime", "" ]
A very niche problem: I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js>). Now on this page I have a Google Map and I use the Prototype Window library. The problem occurs in IE7 and FF3. This is the info FireBug gives: ``` handler is undefined ? in prototype.js@3871()prototype.js (line 3877) handler.call(element, event); ``` I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error... I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).
I just found out this error also occurs if you accidentally leave on the parenthesis on your observer call: ``` Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp()); ``` instead of ``` Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp); ```
> I switched to a local version of prototypejs and added some debugging > in the offending method (createWraper) but the debugging never appears > before the error... Actually the offending function being called when the error occurs is "wrapper" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist. If you're trying to put any debug information in to try and pinpoint which function "doesn't exist" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878.
"undefined handler" from prototype.js line 3877
[ "", "javascript", "google-maps", "prototypejs", "" ]
I have this idea for a free backup application. The largest problem I need to solve at the moment is how to access files which are being used or are system files. I would like the application to be able to perform a full backup of files (i.e. not on a disk sector by sector level). I'll turn the server part of the application into a service. First of all this service will need to be run with administrative privileges I guess? And secondly, is it possible to access locked files and files used by the system? Maybe take those files after the next reboot? (I've seen some anti virus applications work that way.) I will use C# and the .NET platform, as it seems to be the easiest way to develop Windows applications these days.
What you're looking for regarding the files in use is the "[Volume Shadow Copy Service](http://msdn.microsoft.com/en-us/library/bb968832(VS.85).aspx "MSDN - Volume Shadow Copy Service")" which is available on Windows XP, Server 2003 and above. This will allow you to copy files even when they are in use. I have found a CodeProject article "[Volume Shadow Copies from .NET](http://www.codeproject.com/KB/dotnet/makeshadowcopy.aspx?display=Print "CodeProject - Volume Shadow Copies from .NET")" which describes a simple Outlook PST backup application written against Volume Shadow Copy.
Do a Google on HoboCopy. It is an open source backup tool for windows that can backup files that are in use using Windows Volume Shadow Service.
Reading files in use and system files on Windows XP & Vista using .NET
[ "", "c#", ".net", "windows", "" ]
Has anybody out there used the [SWIG](http://www.swig.org/exec.html) library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application. Edit: Some clarification on target OS's. I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.
I think the mistake the earlier posters did was read the docs and not look at the examples. A few hours ago I needed to interface some C++ classes to C#. I looked in my Swig dir (I already had it for other work), found the directory `Examples/csharp/class`, browsed the code, loaded the solution, grokked it, copied it, put in my code, it worked, my job was done. With that said, generated P/Invoke code isn't a solution for all needs. Depending on your project, it may be just as simple to write some simple API wrappers yourself or write managed C++ (Look up SlimDX for a superb example of this). For my needs, it was simple and easy - I had `mystuff.dll`, and now in addition I can ship `mystuffnet.dll`. I'll agree that the doc is difficult to get into. Edit: I noticed the OP only mentioned C. For that, you don't really need Swig, just use the [usual C#/C DLLImport interop syntax](http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx#pinvoke_callingdllexport). Swig becomes useful when you want to let **C++ classes** be invoked from C#.
For my last project, here's the entire C# SWIG configuration file: ``` %module mdProject %{ #include "mdProject.h" %} ``` I compiled it in SWIG with: ``` swig -csharp -c++ -I../../Include mdProject.i ``` This generated a Project.cxx which I compiled and linked directly into the 'main' DLL, so I didn't need a second C++ 'helper' DLL. SWIG also generated a bunch of C# files which I compiled into a .NET DLL. My other wrappers (Java, PHP, etc) do use a helper DLL. As @patrick mentioned, SWIG uses P/Invoke, so if you have a problem with that, you'll need to find another solution. If you use types that stray from the ordinary (voids, structures, etc), you will have to do some extra work to get it right, but for the average API using int's, char\*'s etc, it's fine.
What are the best practices when using SWIG with C#?
[ "", "c#", "c", "swig", "" ]
I want to delete foo() if foo() isn't called from anywhere.
[Gendarme](http://www.mono-project.com/Gendarme) will detect private methods with no upstream callers. It is available cross platform, and the latest version handles "[AvoidUncalledPrivateCodeRule](http://www.mono-project.com/Gendarme.Rules.Performance)". [FxCop](http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx "FxCop") will detect public/protected methods with no upstream callers. However, FxCop does not detect all methods without upstream callers, as it is meant to check in the case that your code is part of a Library, so public members are left out. [You can use NDepend to do a search for public members with no upstream callers, which I detail here in this other StackOverflow answer](https://stackoverflow.com/questions/71518/is-there-a-custom-fxcop-rule-that-will-detect-unused-public-methods#71929). *(edit: added information about Gendarme which actually does what the questioner asked)*
[NDepend](http://www.ndepend.com) will also report on potentially unused code.
Is there a tool for finding unreferenced functions (dead, obsolete code) in a C# app?
[ "", "c#", ".net", "code-analysis", "" ]
In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this: ``` Color blended = Color.FromArgb(alpha, color); ``` or ``` Color blended = Color.FromArgb(alpha, red, green , blue); ``` However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get: ``` Color.FromArgb(int red, int green, int blue); ``` and ``` Color.FromArgb(int val); ``` The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following: ``` private Color FromARGB(byte alpha, byte red, byte green, byte blue) { int val = (alpha << 24) | (red << 16) | (green << 8) | blue; return Color.FromArgb(val); } ``` But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0. Has anyone gotten this to work on the Compact Framework?
Apparently, it's not quite that simple, but [still possible](http://blogs.msdn.com/chrislorton/archive/2006/04/07/570649.aspx), if you have Windows Mobile 5.0 or newer.
There is a [codeplex site](http://www.codeplex.com/alphamobilecontrols) out there that seems to do the heavy lifting of com interop for you:
Alpha blending colors in .NET Compact Framework 2.0
[ "", "c#", ".net", "graphics", "compact-framework", "" ]
What are some reasons why PHP would force errors to show, no matter what you tell it to disable? I have tried ``` error_reporting(0); ini_set('display_errors', 0); ``` with no luck.
Note the caveat in the manual at <http://uk.php.net/error_reporting>: > > Most of E\_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error\_reporting is enhanced to include E\_STRICT errors (and vice versa). If your underlying system is configured to report E\_STRICT errors, these may be output before your code is even considered. Don't forget, error\_reporting/ini\_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects. --- Based on your comment that your error is... > Parse error: syntax error, unexpected T\_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public\_html/dev.php on line 11 Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered. Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place... php\_value error\_reporting 0 in a .htaccess file to suppress them all, but this is system configuration dependent. Pragmatically, don't write files with syntax errors :)
To prevent errors from displaying you can * Write in a .htaccess: *php\_flag display\_errors 0* * Split your code in separate modules where the main (parent) PHP file only sets the error\_logging and then include() the other files.
What are the reasons why PHP would echo errors, even with error_reporting(0)?
[ "", "php", "error-reporting", "ini-set", "" ]
I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?
``` $first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year)); $last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year)); ``` See [date()](https://www.php.net/date) in PHP documentation.
First day is always YYYY-MM-01, isn't it? Example: `date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))` Last day is the previous day of the next month's first day: ``` $date = new DateTime("2008-09-01"); $date->modify("-1 day"); echo $date->format("Y-m-d"); ```
In PHP, is there an easy way to get the first and last date of a month?
[ "", "php", "" ]
I have a C# singleton class that multiple classes use. Is access through `Instance` to the `Toggle()` method thread-safe? If yes, by what assumptions, rules, etc. If no, why *and* how can I fix it? ``` public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } } ```
> Is access through 'Instance' to the 'Toggle()' class threadsafe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? No, it's not threadsafe. Basically, both threads can run the `Toggle` function at the same time, so this could happen ``` // thread 1 is running this code if(value == 0) { value = 1; // RIGHT NOW, thread 2 steps in. // It sees value as 1, so runs the other branch, and changes it to 0 // This causes your method to return 0 even though you actually want 1 } else if(value == 1) { value = 0; } return value; ``` You need to operate with the following assumption. If 2 threads are running, they can and will interleave and interact with eachother randomly at any point. You can be half way through writing or reading a 64 bit integer or float (on a 32 bit CPU) and another thread can jump in and change it out from underneath you. If the 2 threads never access anything in common, it doesn't matter, but as soon as they do, you need to prevent them from stepping on each others toes. The way to do this in .NET is with locks. You can decide what and where to lock by thinking about things like this: For a given block of code, if the value of `something` got changed out from underneath me, would it matter? If it would, you need to lock that `something` for the duration of the code where it would matter. Looking at your example again ``` // we read value here if(value == 0) { value = 1; } else if(value == 1) { value = 0; } // and we return it here return value; ``` In order for this to return what we expect it to, we assume that `value` won't get changed between the read and the `return`. In order for this assumption to actually be correct, you need to lock `value` for the duration of that code block. So you'd do this: ``` lock( value ) { if(value == 0) ... // all your code here return value; } ``` **HOWEVER** In .NET you can only lock Reference Types. Int32 is a Value Type, so we can't lock it. We solve this by introducing a 'dummy' object, and locking *that* wherever we'd want to lock 'value'. This is what [Ben Scheirman](https://stackoverflow.com/questions/42505/thread-safe-use-of-a-singletons-members/42517#42517) is referring to.
The original impplementation is not thread safe, as Ben points out A simple way to make it thread safe is to introduce a lock statement. Eg. like this: ``` public class MyClass { private Object thisLock = new Object(); private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private Int32 value = 0; public Int32 Toggle() { lock(thisLock) { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } } } ```
Thread-safe use of a singleton's members
[ "", "c#", ".net", "multithreading", "singleton", "thread-safety", "" ]
How can I set the cookies in my `PHP apps` as `HttpOnly cookies`?
* For **your cookies**, see this answer. * For **PHP's own session cookie** (`PHPSESSID`, by default), see [@richie's answer](https://stackoverflow.com/a/8726269/1820) The [`setcookie()`](http://php.net/manual/en/function.setcookie.php) and [`setrawcookie()`](http://php.net/manual/en/function.setrawcookie.php) functions, introduced the boolean `httponly` parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax *Function syntax simplified for brevity* ``` setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) ``` In PHP < 8, specify `NULL` for parameters you wish to remain as default. In PHP >= 8 you can benefit from using named parameters. See [this question about named params](https://stackoverflow.com/a/64997399/1820). ``` setcookie( $name, $value, httponly:true ) ``` It is also possible using the older, lower-level [`header()`](http://php.net/manual/en/function.header.php) function: ``` header( "Set-Cookie: name=value; HttpOnly" ); ``` You may also want to consider if you should be setting the `Secure` parameter.
For PHP's own session cookies on Apache: add this to your Apache configuration or `.htaccess` ``` <IfModule php5_module> php_flag session.cookie_httponly on </IfModule> ``` This can also be set within a script, as long as it is called before `session_start()`. ``` ini_set( 'session.cookie_httponly', 1 ); ```
How do you set up use HttpOnly cookies in PHP
[ "", "php", "security", "cookies", "xss", "httponly", "" ]
I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header. The TabSpecs are created in this way within a `setupTabs()` method which loops to create the appropriate number of tabs: ``` TabSpec ts = mTabs.newTabSpec("tab"); ts.setIndicator("TabTitle", iconResource); ts.setContent(new TabHost.TabContentFactory( { public View createTabContent(String tag) { ... } }); mTabs.addTab(ts); ``` There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them. ``` mTabs.getTabWidget().removeAllViews(); mTabs.clearAllTabs(true); setupTabs(); ``` Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?
The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a `TabHost` after it's been created. The `TabSpec` is only used to build the tab, so changing the `TabSpec` after the fact will have no effect. I think there's a workaround, though. Call `mTabs.getTabWidget()` to get a `TabWidget` object. This is just a subclass of `ViewGroup`, so you can call `getChildCount()` and `getChildAt()` to access individual tabs within the `TabWidget`. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other `ViewGroup` (maybe a `LinearLayout`, but it doesn't matter) that contains an `ImageView` and a `TextView`. So with a little fiddling with the debugger or `Log.i`, you should be able to figure out a recipe to get the `ImageView` and change it directly. The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.
Just to confirm dominics answer, here's his solution in code (that actually works): ``` tabHost.setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(String tabId) { if (TAB_MAP.equals(tabId)) { ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon); iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black)); iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon); iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white)); } else if (TAB_LIST.equals(tabId)) { ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon); iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white)); iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon); iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black)); } } }); ``` Of course it's not polished at all and using those direct indices in getChildAt() is not nice at all...
Updating Android Tab Icons
[ "", "java", "android", "android-tabhost", "" ]
I'm trying to use `jQuery` to format code blocks, specifically to add a `<pre>` tag inside the `<code>` tag: ``` $(document).ready(function() { $("code").wrapInner("<pre></pre>"); }); ``` Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert ``` alert($("code").html()); ``` I see that IE has inserted some additional text into the pre tag: ``` <PRE jQuery1218834632572="null"> ``` If I reload the page, the number following jQuery changes. If I use `wrap()` instead of `wrapInner()`, to wrap the `<pre>` outside the `<code>` tag, both IE and Firefox handle it correctly. But shouldn't `<pre>` work *inside* `<code>` as well? I'd prefer to use `wrapInner()` because I can then add a CSS class to the `<pre>` tag to handle all formatting, but if I use `wrap()`, I have to put page formatting CSS in the `<pre>` tag and text/font formatting in the `<code>` tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible. Has anyone else encountered this? Am I missing something?
That's the difference between [block and inline](http://www.w3.org/TR/html4/struct/global.html#h-7.5.3) elements. [`pre` is a block level element](http://www.w3.org/TR/html4/sgml/dtd.html#block). It's not legal to put it inside a `code` tag, which [can only contain inline content](http://www.w3.org/TR/html4/struct/text.html#h-9.2.1). Because browsers have to support whatever godawful tag soup they might find on the real web, Firefox tries to do what you mean. IE happens to handle it differently, which is fine by the spec; behavior in that case is unspecified, because it should never happen. * Could you instead *replace* the `code` element with the `pre`? (Because of the block/inline issue, technically that should only work if the elements are inside [an element with "flow" content](http://www.w3.org/TR/html4/sgml/dtd.html#flow), but the browsers might do what you want anyway.) * Why is it a `code` element in the first place, if you want `pre`'s behavior? * You could also give the `code` element `pre`'s whitespace preserving power with the CSS [`white-space: pre`](http://www.blooberry.com/indexdot/css/properties/text/whitespace.htm), but apparently [IE 6 only honors that in Strict Mode](http://www.quirksmode.org/css/whitespace.html).
Btw I don't know if it is related but pre tags inside code tags will not validate in strict mode.
How do I add a pre tag inside a code tag with jQuery?
[ "", "javascript", "jquery", "html", "internet-explorer", "" ]
Specifically, is the following legal C++? ``` class A{}; void foo(A*); void bar(const A&); int main(void) { foo(&A()); // 1 bar(A()); // 2 } ``` It appears to work correctly, but that doesn't mean it's necessarily legal. Is it? *Edit - changed `A&` to `const A&`*
1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default). 2: This is perfectly legal.
No, it's against the standard to pass a non-const reference to a temporary object. You can use a const reference: ``` class A{}; void bar(const A&); int main(void) { bar(A()); // 2 } ``` So while some compliers will accept it, and it would work as long as don't use the memory after the semicolon, a conforming compiler will not accept it.
Is it legal to pass a newly constructed object by reference to a function?
[ "", "c++", "" ]
Is there some way I can use URLs like: *<http://www.blog.com/team-spirit/>* instead of *<http://www.blog.com/?p=122>* in a Windows hosted PHP server?
This is how I did it with WordPress on IIS 6.0 <http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/> However it all depends on what version of IIS you are using. If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box. However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS.
[Isapi Rewrite Filter on CodePlex](http://www.codeplex.com/IIRF) - actively developed, free ("DonationWare"), open source.
How to make 'pretty urls' work in php hosted in IIS?
[ "", "php", "iis", "" ]
I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients? I'm using TAO.
Recompilation of clients is not required (and should not be, regardless of the ORB that you use). As Adam indicated, lookups are done by operation name (a straight text comparison). I've done what you're describing with our ACE/TAO-based system, and encountered no issues (servers were in ACE/TAO C++, clients were ACE/TAO C++, C# using Borland's Janeva, and OmniORBPy).
Assuming that the clients and servers are communicating via IIOP, no recompilation is required. An IIOP message contains the name of the interface, the name of the method, and the parameters. If none of those things have changed, then everything should remain compatible. Adding another method to the interface won't change any of those existing things. On the other hand, if your objects are using a different protocol, or if the clients are in-process with the server and thus bypassing IIOP, you may need to make sure everything gets recompiled.
Changing a CORBA interface without recompiling
[ "", "c++", "corba", "idl", "tao", "" ]
In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields. I get the following error: ``` TypeError: __init__() got an unexpected keyword argument 'core' ``` [Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?
To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).
The `core` attribute isn't used anymore. From [Brian Rosner's Blog](http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/): > You can safely just remove any and all `core` arguments. They are no longer used. *newforms-admin* now provides a nice delete checkbox for exisiting instances in inlines.
Django ImageField core=False in newforms admin
[ "", "python", "django", "django-models", "" ]
The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}. The following XML, for example, when deserialized, sets the boolean property "Emulate" to `true`. ``` <root> <emulate>1</emulate> </root> ``` However, when I serialize the object back to the XML, I get `true` instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML?
You can implement IXmlSerializable which will allow you to alter the serialized output of your class however you want. This will entail creating the 3 methods GetSchema(), ReadXml(XmlReader r) and WriteXml(XmlWriter r). When you implement the interface, these methods are called instead of .NET trying to serialize the object itself. Examples can be found at: <http://www.developerfusion.co.uk/show/4639/> and <http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx>
You can also do this by using some XmlSerializer attribute black magic: ``` [XmlIgnore] public bool MyValue { get; set; } /// <summary>Get a value purely for serialization purposes</summary> [XmlElement("MyValue")] public string MyValueSerialize { get { return this.MyValue ? "1" : "0"; } set { this.MyValue = XmlConvert.ToBoolean(value); } } ``` You can also use other attributes to hide this member from intellisense if you're offended by it! It's not a perfect solution, but it can be quicker than implementing IXmlSerializable.
XML Serialize boolean as 0 and 1
[ "", "c#", "xml", "serialization", "schema", "constraints", "" ]
I'm curious about people's approaches to using stored procedures in a database that is accessed by many applications. Specifically, do you tend to keep different sets of stored procedures for each application, do you try to use a shared set, or do you do a mix? On the one hand, reuse of SPs allows for fewer changes when there is a model change or something similar and ideally less maintenance. On the other hand, if the needs of the applications diverge, changes to a stored procedure for one application can break other applications. I should note that in our environment, each application has its own development team, with poor communication between them. The data team has better communication though, and is mostly tasked with the stored procedure writing. Thanks!
It all depends on your abstraction strategy. Are the stored procedures treated as a discrete point of abstraction, or are they treated as just another part of the application that calls them. The answer to that will tell you how to manage them. If they are a discrete abstraction, they can be shared, as if you need new functionality, you'll add new procedures. If they are part of the app that calls them, they shouldn't be shared.
Stored procedures should be created based on the data you intend to return, not the application making the request. If you have a stored procedure that is GetAllItems, it should return all of the items in the database. If one of the applications would like to get all of the items by category, create GetAllItemsByCategory. There is no reason for the business rules of a stored procedure to change based on the application requesting the data.
Reuse of SQL stored procedures across applications
[ "", "sql", "architecture", "stored-procedures", "code-reuse", "" ]
Has anyone encountered this oddity? I'm checking for the existence of a number of directories in one of my unit tests. `is_dir` is reporting true (1) in spite of the folder not existing at the time it is called. The code looks like this (with a few extraneous intermediate vars to ease debugging): ``` foreach($userfolders as $uf) { $uf = sprintf($uf, $user_id); $uf = ltrim($uf,'/'); $path = trim($base . '/' . $uf); $res = is_dir($path); //returns false except last time returns 1 $this->assertFalse($res, $path); } ``` The machine running Ubuntu Linux 8.04 with PHP Version 5.2.4-2ubuntu5.3 Things I have checked: ``` - Paths are full paths - The same thing happens on two separate machines (both running Ubuntu) - I have stepped through line by line in a debugger - Paths genuinely don't exist at the point where is_dir is called - While the code is paused on this line, I can actually drop to a shell and run ``` the interactive PHP interpreter and get the correct result - The paths are all WELL under 256 chars - I can't imagine a permissions problem as the folder doesn't exist! The parent folder can't be causing permissions problems as the other folders in the loop are correctly reported as missing. Comments on the PHP docs point to the odd issue with `is_dir` but not this particular one. I'm not posting this as a "please help me fix" but in the hope that somebody encountering the same thing can search here and *hopefully* an answer from somebody else who has seen this!
I don't think this would cause your problem, but $path does have the trailing slash, correct?
For what its worth, `is_readable` can be used as a work around.
php is_dir returns true for non-existent folder
[ "", "php", "" ]
At the beginning of all my executable Python scripts I put the [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) line: ``` #!/usr/bin/env python ``` I'm running these scripts on a system where `env python` yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: ``` if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") ``` I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of `env python` and I don't want to force a particular version, as in: ``` #!/usr/bin/env python2.4 ``` I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in `~/bin` and ensuring your PATH has `~/bin` before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
Pretty hackish solution - if your check fails, use this function (which probably could be significantly improved) to determine the best interpreter available, determine if it is acceptable, and if so relaunch your script with os.system or something similar and your sys.argv using the new interpreter. ``` import os import glob def best_python(): plist = [] for i in os.getenv("PATH").split(":"): for j in glob.glob(os.path.join(i, "python2.[0-9]")): plist.append(os.path.join(i, j)) plist.sort() plist.reverse() if len(plist) == 0: return None return plist[0] ```
Python deployment and /usr/bin/env portability
[ "", "python", "executable", "environment", "shebang", "" ]
What do `*args` and `**kwargs` mean in these function definitions? ``` def foo(x, y, *args): pass def bar(x, y, **kwargs): pass ``` --- See [What do \*\* (double star/asterisk) and \* (star/asterisk) mean in a function call?](https://stackoverflow.com/questions/2921847) for the complementary question about arguments.
The `*args` and `**kwargs` are common idioms to allow an arbitrary number of arguments to functions, as described in the section [more on defining functions](http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions) in the Python tutorial. The `*args` will give you all positional arguments [as a tuple](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists): ``` def foo(*args): for a in args: print(a) foo(1) # 1 foo(1, 2, 3) # 1 # 2 # 3 ``` The `**kwargs` will give you all keyword arguments as a dictionary: ``` def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) bar(name='one', age=27) # name one # age 27 ``` Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments: ``` def foo(kind, *args, bar=None, **kwargs): print(kind, args, bar, kwargs) foo(123, 'a', 'b', apple='red') # 123 ('a', 'b') None {'apple': 'red'} ``` It is also possible to use this the other way around: ``` def foo(a, b, c): print(a, b, c) obj = {'b':10, 'c':'lee'} foo(100, **obj) # 100 10 lee ``` Another usage of the `*l` idiom is to **unpack argument lists** when calling a function. ``` def foo(bar, lee): print(bar, lee) baz = [1, 2] foo(*baz) # 1 2 ``` In Python 3 it is possible to use `*l` on the left side of an assignment ([Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132/)), though it gives a list instead of a tuple in this context: ``` first, *rest = [1, 2, 3, 4] # first = 1 # rest = [2, 3, 4] ``` Also Python 3 adds a new semantic (refer [PEP 3102](https://www.python.org/dev/peps/pep-3102/)): ``` def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass ``` Such function accepts only 3 positional arguments, and everything after `*` can only be passed as keyword arguments. ### Note: A Python `dict`, semantically used for keyword argument passing, is arbitrarily ordered. However, in Python 3.6+, keyword arguments are guaranteed to remember insertion order. "The order of elements in `**kwargs` now corresponds to the order in which keyword arguments were passed to the function." - [What’s New In Python 3.6](https://docs.python.org/3/whatsnew/3.6.html). In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, and this becomes standard in Python 3.7.
It's also worth noting that you can use `*` and `**` when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function: ``` def foo(x,y,z): print("x=" + str(x)) print("y=" + str(y)) print("z=" + str(z)) ``` You can do things like: ``` >>> mylist = [1,2,3] >>> foo(*mylist) x=1 y=2 z=3 >>> mydict = {'x':1,'y':2,'z':3} >>> foo(**mydict) x=1 y=2 z=3 >>> mytuple = (1, 2, 3) >>> foo(*mytuple) x=1 y=2 z=3 ``` Note: The keys in `mydict` have to be named exactly like the parameters of function `foo`. Otherwise it will throw a `TypeError`: ``` >>> mydict = {'x':1,'y':2,'z':3,'badnews':9} >>> foo(**mydict) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() got an unexpected keyword argument 'badnews' ```
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
[ "", "python", "syntax", "parameter-passing", "variadic-functions", "argument-unpacking", "" ]
I'm using [jQuery](http://jquery.com/) and [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/) in an ASP.Net project to make some nice dialogs for a web app. Unfortunately, any buttons in a modal dialog can no longer execute their postbacks, which is not really acceptable. There is one source I've found with a [workaround](http://blog.hurlman.com/post/jQuery2c-simpleModal2c-and-ASPNet-postbacks-do-not-play-well-together.aspx), but for the life of me I can't get it to work, mostly because I am not fully understanding all of the necessary steps. I also have a workaround, which is to replace the postbacks, but it's ugly and probably not the most reliable. I would really like to make the postbacks work again. Any ideas? UPDATE: I should clarify, the postbacks are not working because the Javascript used to execute the post backs has broken in some way, so nothing happens at all when the button is clicked.
Both of you were on the right track. What I realized is that SimpleModal appends the dialog to the body, which is outside ASP.Net's `<form>`, which breaks the functionality, since it can't find the elements. To fix it, I just modified the SimpleModal source to append eveything to `'form'` instead of `'body'`. When I create the dialog, I also use the `persist: true` option, to make sure the buttons stay through opening and closing. Thanks everyone for the suggestions! *UPDATE:* Version 1.3 adds an `appendTo` option in the configuration for specifying which element the modal dialog should be appended to. [Here are the docs](http://www.ericmmartin.com/projects/simplemodal/#options).
All standard ASP.NET postbacks work by calling a \_\_doPostBack javascript method on the page. That function submits the form (ASP.NET only really likes one form per page) which includes some hidden input field in which all the viewstate and other goodness lives. On the face of it I can't see anything in SimpalModal that would screw up your page's form or any of the standard hidden inputs, unless the contents of that modal happened to come from a HTTP GET to an ASP.NET page. That would result in two ASP.NET forms being rendered into one DOM and would would almost certainly screw up the \_\_doPostBack function. Have you considered using the [ASP.NET AJAX ModalPopup control](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ModalPopup/ModalPopup.aspx)?
SimpleModal breaks ASP.Net Postbacks
[ "", "asp.net", "javascript", "jquery", "postback", "simplemodal", "" ]
I would like to use `as` and `is` as members of an enumeration. I know that this is possible in VB.NET to write it like this: ``` Public Enum Test [as] = 1 [is] = 2 End Enum ``` How do I write the equivalent statement in C#? The following code does not compile: ``` public enum Test { as = 1, is = 2 } ```
Prefixing reserved words in C# is done with @. ``` public enum Test { @as = 1, @is = 2 } ```
You will need to prefix them with the @ symbol to use them. Here is the [msdn page](https://msdn.microsoft.com/en-us/library/x53a06bb.aspx) that explains it.
Reserved Keyword in Enumeration in C#
[ "", "c#", "vb.net", ".net-2.0", "" ]
More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib) Failing that, maybe a mingw cross compiler with the app running under wine. Half answered my own question here, but wondered if anyone had heard of anything like this being done?
I've had some luck with this. I've managed to compile [this simple Direct3D example](http://www.directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B5.aspx). I used winelib for this (wine-dev package on Ubuntu). Thanks to [alastair](https://stackoverflow.com/users/9554/alastair) for pointing me to winelib. I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running. I then compiled the source with the following: ``` wineg++ -ld3d9 -ld3dx9 triangle.cpp ``` This generates an a.out.exe.so binary, as well as an a.out script to run it under wine.
If this is not about porting but creating, you should really consider OpenGL as this API is as powerful as DirectX and much easier to port to Mac or Linux. I don't know your requirements so better mention it.
Is it possible to develop DirectX apps in Linux?
[ "", "c++", "linux", "directx", "mingw", "wine", "" ]
What is the best way to create a fixed width file in C#. I have a bunch of fields with lengths to write out. Say 20,80.10,2 etc all left aligned. Is there an easy way to do this?
You can use string.Format to easily pad a value with spaces e.g. ``` string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300); string b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300); // 'a' will be equal to "| 1| 20| 300|" // 'b' will be equal to "|1 |20 |300 |" ```
This is a system I made for a configurable Fixed Width file writing module. It's configured with an XML file, the relevant part looking like this: ``` <WriteFixedWidth Table="orders" StartAt="1" Output="Return"> <Position Start="1" Length="17" Name="Unique Identifier"/> <Position Start="18" Length="3" Name="Error Flag"/> <Position Start="21" Length="16" Name="Account Number" Justification="right"/> <Position Start="37" Length="8" Name="Member Number"/> <Position Start="45" Length="4" Name="Product"/> <Position Start="49" Length="3" Name="Paytype"/> <Position Start="52" Length="9" Name="Transit Routing Number"/> </WriteFixedWidth> ``` StartAt tells the program whether your positions are 0-based or 1-based. I made that configurable because I would be copying down offsets from specs and wanted to have the config resemble the spec as much as possible, regardless of what starting index the author chose. The Name attribute on the Position tags refer to the names of columns in a DataTable. The following code was written for .Net 3.5, using LINQ-to-XML, so the method assumed it'd be passed an XElement with the above configuration, which you can get after you use `XDocument.Load(filename)` to load the XML file, then call `.Descendants("WriteFixedWidth")` on the `XDocument` object to get the configuration element. ``` public void WriteFixedWidth(System.Xml.Linq.XElement CommandNode, DataTable Table, Stream outputStream) { StreamWriter Output = new StreamWriter(outputStream); int StartAt = CommandNode.Attribute("StartAt") != null ? int.Parse(CommandNode.Attribute("StartAt").Value) : 0; var positions = from c in CommandNode.Descendants(Namespaces.Integration + "Position") orderby int.Parse(c.Attribute("Start").Value) ascending select new { Name = c.Attribute("Name").Value, Start = int.Parse(c.Attribute("Start").Value) - StartAt, Length = int.Parse(c.Attribute("Length").Value), Justification = c.Attribute("Justification") != null ? c.Attribute("Justification").Value.ToLower() : "left" }; int lineLength = positions.Last().Start + positions.Last().Length; foreach (DataRow row in Table.Rows) { StringBuilder line = new StringBuilder(lineLength); foreach (var p in positions) line.Insert(p.Start, p.Justification == "left" ? (row.Field<string>(p.Name) ?? "").PadRight(p.Length,' ') : (row.Field<string>(p.Name) ?? "").PadLeft(p.Length,' ') ); Output.WriteLine(line.ToString()); } Output.Flush(); } ``` The engine is StringBuilder, which is faster than concatenating immutable strings together, especially if you're processing multi-megabyte files.
Creating a fixed width file in C#
[ "", "c#", "" ]
Would it not make sense to support a set of languages (Java, Python, Ruby, etc.) by way of a standardized virtual machine hosted in the browser rather than requiring the use of a specialized language -- really, a specialized paradigm -- for client scripting only? To clarify the suggestion, a web page would contain byte code instead of any higher-level language like JavaScript. I understand the pragmatic reality that JavaScript is simply what we have to work with now due to evolutionary reasons, but I'm thinking more about the long term. With regard to backward compatibility, there's no reason that inline JavaScript could not be simultaneously supported for a period of time and of course JavaScript could be one of the languages supported by the browser virtual machine.
Well, yes. Certainly if we had a time machine, going back and ensuring a lot of the Javascript features were designed differently would be a major pastime (that, and ensuring the people who designed IE's CSS engine never went into IT). But it's not going to happen, and we're stuck with it now. I suspect, in time, it will become the "Machine language" for the web, with other better designed languages and APIs compile down to it (and cater for different runtime engine foibles). I don't think, however, any of these "better designed languages" will be Java, Python or Ruby. Javascript is, despite the ability to be used elsewhere, a Web application scripting language. Given that use case, we can do better than any of those languages.
I think JavaScript is a good language, but I would love to have a choice when developing client-side web applications. For legacy reasons we're stuck with JavaScript, but there are projects and ideas looking for changing that scenario: 1. [Google Native Client](http://code.google.com/p/nativeclient/): technology for running native code in the browser. 2. [Emscripten](http://kripken.github.io/emscripten-site/): LLVM bytecode compiler to javascript. Allows LLVM languages to run in the browser. 3. Idea: .NET CLI in the browser, by the creator of Mono: <http://tirania.org/blog/archive/2010/May-03.html> I think we will have JavaScript for a long time, but that will change sooner or later. There are so many developers willing to use other languages in the browser.
Why JavaScript rather than a standard browser virtual machine?
[ "", "javascript", "" ]
Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way. Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.) ``` Intermec.Print.LinePrinter lp; int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber); char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' }; lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL"); lp.Open(); lp.Write(charArray2); //switch to ez print mode string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}"; lp.Write(testBarcode); lp.Write("{LP}"); //switch from ez print mode back to line printer mode lp.NewLine(); lp.Write("Test"); //verify line printer mode is working ``` There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes.
Last time I had to print Barcode (despite the printer or framework) I resorted to use a True Type font with the Barcode I needed. (In my case was EAN-13 something), an european barcode. There are fonts where you simply write numbers (and/or letters when supported) and you get a perfect barcode any scanner can read :) Google is your friend. I don't know if there are free ones.
Print a barcode to a Intermec PB20 via the LinePrinter API
[ "", "c#", "windows-mobile", "" ]
I've found [an article](http://blogs.msdn.com/priozersk/archive/2007/08/06/implementing-mvc-pattern-in-net-cf-applications-part-1.aspx) on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this. I haven't looked at the [Mobile Software Factory](http://msdn.microsoft.com/en-us/library/aa480471.aspx) from the P&P group, but I suspect it's kind of heavy. Is it worth a look? **Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that.**
I personally think that the Mobile Software Factory doesn't hold much joy for CF. We still use one part of it (EventBroker) at work and I'd like to even remove that part if possible (as it doesn't support generic events and you have to cast the arguments into their strong types from EventArgs). A sister project at work used it for part of their UI but had to rip it out due to performance issues (another big project, although that has additional performance issues of it's own as well). The issue I find with the MVP framework that the P&P lib offers is that Forms and Controls OWN presenters instead of Presenters/Controllers owning Forms (who didn't read "It's just a view" : Pragmatic Programmer?). This fits beautifully with MS's "Form First" rapid application development mantra but it sucks when you consider how expensive windows handles can be in CE (if you have a lot of them). We run a very large CF application at work and we've rolled our own MVC framework. It's not hard to roll your own, just make sure you separate everything out into Controllers, Views, Business Objects and Services and have a UIController that controls the interactions between the controllers. We actually go one step further and re-use forms/controls by using a Controller->View->Layout pattern. The controller is the same as usual, the view is the object that customises a layout into a particular view and the layout is the actual UserControl. We then swap these in and out of a single Form. This reduces the amount of Windows Controls we use dramatically. This + initialising all of the forms on start-up means that we eradicate the noticable pause that you get when creating new Windows Controls "on-demand". Obviously it only really pays to do this kind of thing if you are rolling a large application. We have roughly 20 + different types of View which use in total about 7 different layouts. This hurts our initialisation routine (as we load the forms at start up) by a magnitude of about 10 seconds but psychologically most users are willing to accept such a hit at start up as opposed to noticeable pauses during run-time. The main issue with the P&P library in my books is that it is a FF -> CF port and due to certain incompatability and performance differences between the two platforms you lose a lot of useful functionality. Btw, [this](http://ctrl-shift-b.blogspot.com/2007/08/interactive-application-architecture.html) is by far and away the most comprehensive article i've ever read on MVC/MVP. For Windows application (desktop or CE) I'd recommend using the Taligent Model-View-Presenter version without the interactions, commands and selections (e.g the controller/presenter performs all the work).
Neither of you (davidg or Kevin Pang) paid attention to the fact that he's interested in *WinForms*, not *Web Forms*. He wants a framework that pushes the Model-View-Controller design pattern (davidg, MVC isn't just the name of an ASP.NET framework) in a WinForms project using the .NET Compact Framework. He asked his question just fine.
Compact Framework - Is there an MVC framework/library available?
[ "", "c#", "model-view-controller", "windows-mobile", "compact-framework", "design-patterns", "" ]
I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g. ``` public bool MethodToReturnTrue(string seedValue); ``` appears to the client apps as ``` public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); ``` I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client. My current app.config looks like this. ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service behaviorConfiguration="MyServiceTypeBehaviors" Name="MyCompany.Services.CentreService.CentreService"> <clear /> <endpoint address="http://localhost:8080/CSMEX" binding="basicHttpBinding" bindingConfiguration="" contract="IMetadataExchange" /> <endpoint address="http://localhost:8080/CentreService" binding="basicHttpBinding" bindingName="Compatible" name="basicEndpoint" contract="MyCompany.Services.CentreService.ICentreService" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> ``` Can anyone advise, please?
OK, we needed to resolve this issue in the short term, and so we came up with the idea of a "interop", or compatibility layer. Baiscally, all we did was added a traditional ASMX web service to the project, and called the WCF service from that using native WCF calls. We were then able to return the appropriate types back to the client applications without a significant amount of re-factoring work. I know it was a hacky solution, but it was the best option we had with such a large legacy code-base. And the added bonus is that it actually works surprisingly well. :)
Ah, this is killing me! I did this at work about 3 months ago, and now I can't remember all the details. I do remember, however, that you need basicHttpBinding, and you can't use the new serializer (which is the default); you have to use the "old" XmlSerializer. Unfortunately, I don't work at the place where I did this anymore, so I can't go look at the code. I'll call my boss and see what I can dig up.
WCF Service - Backward compatibility issue
[ "", "c#", ".net", "wcf", "web-services", "backwards-compatibility", "" ]
I have a script that checks responses from HTTP servers using the PEAR HTTP classes. However, I've recently found that the script fails on FTP servers (and probably anything that's not HTTP or HTTPS). I tried Google, but didn't see any scripts or code that returned the server status code from servers other than HTTP servers. How can I find out the status of a newsgroup or FTP server using PHP? EDIT: I should clarify that I am interested only in the ability to read from an FTP server and the directory that I specify. I need to know if the server is dead/gone, I'm not authorized to read, etc. Please note that, although most of the time I'm language agnostic, the entire website is PHP-driven, so a PHP solution would be the best for easy of maintainability and extensibility in the future.
HTTP works slightly differently than FTP though unfortunately. Although both may look the same in your browser, HTTP works off the basis of URI (i.e. to access resource A, you have an identifier which tells you how to access that). FTP is very old school server driven. Even anonymous FTP is a bit of a hack, since you still supply a username and password, it's just defined as "anonymous" and your email address. Checking if an FTP server is up means checking 1. That you can connect to the FTP server `if (!($ftpfd = ftp_connect($hostname))) { ... }` 2. That you can login to the server: `if (!ftp_login($ftpfd, $username, $password)) { ... }` 3. Then, if there are further underlying resources that you need to access to test whether a particular site is up, then use an appropiate operation on them. e.g. on a file, maybe use `ftp_mdtm()` to get the last modified time or on a directory, see if `ftp_nlist()` works.
Wouldn't it be simpler to use the built-in PHP FTP\* functionality than trying to roll your own? If the URI is coming from a source outside your control, you would need to check the protocal definition (http:// or ftp://, etc) in order to determine which functionality to use, but that is fairly trivial. If there is now protocal specified (there really should be!) then you could try to default to http. * see [here](http://uk.php.net/ftp)
Checking FTP status codes with a PHP script
[ "", "php", "http", "ftp", "pear", "server-response", "" ]
I would like to reload an `<iframe>` using JavaScript. The best way I found until now was set the iframe’s `src` attribute to itself, but this isn’t very clean. Any ideas?
``` document.getElementById('some_frame_id').contentWindow.location.reload(); ``` be careful, in Firefox, `window.frames[]` cannot be indexed by id, but by name or index
``` document.getElementById('iframeid').src = document.getElementById('iframeid').src ``` It will reload the `iframe`, even across domains! Tested with IE7/8, Firefox and Chrome. **Note:** As mentioned by @user85461, this approach **doesn't work** if the iframe src URL has a hash in it (e.g. `http://example.com/#something`).
What’s the best way to reload / refresh an iframe?
[ "", "javascript", "iframe", "" ]
I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC. Now we are moving to the [Acer Aspire One](http://en.wikipedia.org/wiki/Aspire_One) but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.
Hi Guys well I finally got this thing to work the basic workflow was this: ``` #!/bin/bash sudo yum install yum-utils #We don't want to update the main gtk2 by mistake so we download them #manually and install with no-deps[1](and forced because gtk version #version of AA1 and the gtk2-devel aren't compatible). sudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel sudo rpm --force --nodeps -i gtk2*rpm glib2*rpm #We install the rest of the libraries needed. sudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel sudo yum install php-cli php-devel make gcc #We Download and compile php-gtk wget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz tar -xvzf php-gtk-2.0.1.tar.gz cd php-gtk-2.0.1 ./buildconf ./configure make sudo make install ``` If you want to add more libraries like gtk-extra please type `./configure -help` before making it to see the different options available. After installing you'll need to add `php_gtk2.so` to the *Dynamic Extensions* of `/etc/php.ini` ``` extension=php_gtk2.so ``` Sources: [1]: [Dependency problems on Acer Aspire One Linux](http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html)
I managed to get all components needed for Phoronix test suite installed on Fedora but still have one issue. ``` # phoronix-test-suite gui shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory pwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory pwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory /usr/bin/phoronix-test-suite: line 28: [: /usr/share/phoronix-test-suite: unary operator expected ``` You need two packages that aren't in Fedora, php-gtk, but php-gtk also has it's dependency - pecl-cairo php-gtk needs to be downloaded from svn because tar.gz version is really old and doesn't work with php 5.3 Here is how I got all components built. ``` su -c "yum install php-cli php-devel make gcc gtk2-devel svn" svn co http://svn.php.net/repository/pecl/cairo/trunk pecl-cairo cd pecl-cairo/ phpize ./configure make su -c "make install" cd .. svn co http://svn.php.net/repository/gtk/php-gtk/trunk php-gtk cd php-gtk ./buildconf ./configure make su -c "make install" cd .. wget http://www.phoronix-test-suite.com/download.php?file=phoronix-test-suite-2.8.1 tar xvzf phoronix-test-suite-2.8.1.tar.gz cd phoronix-test-suite su -c "./install-sh" ``` So please take where I left to get Phoronix test suite running on Fedora.
How to install php-gtk in the Acer Aspire One?
[ "", "php", "fedora", "php-gtk", "" ]
It's been mentioned to me that I'll be the sole developer behind a large new system. Among other things I'll be designing a UI and database schema. I'm sure I'll receive some guidance, but I'd like to be able to knock their socks off. What can I do in the meantime to prepare, and what will I need to keep in mind when I sit down at my computer with the spec? A few things to keep in mind: I'm a college student at my first real programming job. I'll be using Java. We already have SCM set up with automated testing, etc...so tools are not an issue.
Do you know much about OOP? If so, look into Spring and Hibernate to keep your implementation clean and [orthogonal](http://codebetter.com/blogs/jeremy.miller/archive/2007/01/08/Orthogonal-Code.aspx). If you get that, you should find TDD a good way to keep your design compact and lean, especially since you have "automated testing" up and running. UPDATE: Looking at the first slew of answers, I couldn't disagree more. Particularly in the Java space, you should find plenty of mentors/resources on working out your application with Objects, **not a database-centric approach**. Database design is typically the first step for Microsoft folks (which I do daily, but am in a recovery program, er, Alt.Net). If you keep the focus on what you need to deliver to a customer and let your ORM figure out how to persist your objects, your design should be better.
This sounds very much like my first job. Straight out of university, I was asked to design the database and business logic layer, while other people would take care of the UI. Meanwhile the boss was looking over my shoulder, unwilling to let go of what used to be his baby and was now mine, and poking his finger in it. Three years later, developers were fleeing the company and we were still X months away from actually selling anything. The big mistake was in being too ambitious. If this is your first job, you *will* make mistakes and you *will* need to change how things work long after you've written them. We had all sorts of features that made the system more complicated than it needed to be, both on the database level and in the API that it presented to other developers. In the end, the whole thing was just far too complicated to support all at once and just died. So my advice: 1. If you're not sure about taking on such a big job single-handed, don't. Tell your employers, and get them to find or hire somebody for you to work with who can help you out. If people need to be added to the project, then it should be done near the start rather than after stuff starts going wrong. 2. Think very carefully about what the product is for, and to boil it down to the **simplest** set of requirements you can think of. If the people giving you the spec aren't technical, try to see past what they've written to what will actually work and make money. Talk to customers and salespeople, and understand the market. 3. There's no shame in admitting you're wrong. If it turns out that the entire system needs to be rewritten, because you made some mistake in your first version, then it's better to admit this as soon as possible so you can get to it. Correspondingly, don't try to make an architecture that can anticipate every possible contingency in your first version, because you don't know what every contingency is and will just get it wrong. Write once with an eye to throwing away and starting again - you may not have to, the first version may be fine, but admit it if you do.
How do you begin designing a large system?
[ "", "java", "oop", "architecture", "" ]
Does anybody know a "technique" to discover memory leaks caused by smart pointers? I am currently working on a large project written in **C++** that heavily uses smart pointers with reference counting. Obviously we have some memory leaks caused by smart pointers, that are still referenced somewhere in the code, so that their memory does not get free'd. It's very hard to find the line of code with the "needless" reference, that causes the corresponding object not to be free'd (although it's not of use any longer). I found some advice in the web, that proposed to collect call stacks of the increment/decrement operations of the reference counter. This gives me a good hint, which piece of code has caused the reference counter to get increased or decreased. But what I need is some kind of algorithm that groups the corresponding "increase/decrease call stacks" together. After removing these pairs of call stacks, I hopefully have (at least) one "increase call stack" left over, that shows me the piece of code with the "needless" reference, that caused the corresponding object not to be freed. Now it will be no big deal to fix the leak! But has anybody an idea for an "algorithm" that does the grouping? Development takes place under **Windows XP**. (I hope someone understood, what I tried to explain ...) EDIt: I am talking about leaks caused by circular references.
Note that one source of leaks with **reference-counting smart pointers** are pointers with **circular dependancies**. For example, A have a smart pointer to B, and B have a smart pointer to A. Neither A nor B will be destroyed. You will have to find, and then break the dependancies. If possible, use boost smart pointers, and use shared\_ptr for pointers which are supposed to be owners of the data, and weak\_ptr for pointers not supposed to call delete.
The way I do it is simply: - on every AddRef() record call-stack, - matching Release() removes it. This way at the end of the program I'm left with AddRefs() without maching Releases. No need to match pairs,
Find memory leaks caused by smart pointers
[ "", "c++", "pointers", "memory-leaks", "smart-pointers", "" ]
The company I just started working for is using [Stripes](http://www.stripesframework.org/display/stripes/Home) for parts of its web page development these days, and while it seems to be a nice enough web framework it no one really uses it-- it is almost non existent on the 'net. It's not even first in it's [google search](http://www.google.com/search?client=opera&rls=en&q=stripes&sourceid=opera&ie=utf-8&oe=utf-8) and the result you **do** get is for its old home page. So, do any of you people use Stripes? Of your own volition? Do you know of any good tutorials / examples?
I've never used (or even heard of) Stripes. Regardless, there's a book from [The Pragmatic Bookshelf](http://www.pragprog.com/) called [Stripes: ...and Java web development is fun again](http://www.pragprog.com/titles/fdstr/stripes) that may be worth checking out. You could also check out the Stripes [mailing list archive](https://sourceforge.net/mail/?group_id=145476).
I recommend checking out the book referenced by jko: > a book from The Pragmatic Bookshelf called [Stripes: ...and Java web development is fun again](http://www.pragprog.com/titles/fdstr/stripes) Whilst still in 'beta' the book covers everything very well. Another good place to start is [this ONJava article](http://www.onjava.com/pub/a/onjava/2007/01/24/java-web-development-with-stripes.html). I have used Stripes on a few projects now and have liked it a lot. It may sound crazy but the Stripes quickstart and sample application documentation on [the website](http://www.stripesframework.org/display/stripes/Sample+Application) does a pretty good job of covering the bases. This is helped by the fact there is little to Stripes, probably because it is relatively new and not trying to be all things to all people. I would say give the quick-start a try and if by the end of it you are unsatisfied look elsewhere. At the end of the day you and your company have to be happy (and productive) with what you are using irrespective of how many people are using it.
Good Stripes tutorials / examples?
[ "", "java", "stripes", "" ]
I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer. I have seen [watin](http://watin.sourceforge.net/) and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source. Does one exist or are all products based on recording mouse and keyboard presses? **Update:** I have looked at this [blog post on white](http://blog.benhall.me.uk/2008/02/project-white-automated-ui-testing.html) and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.
Check out <http://www.codeplex.com/white> and <http://nunitforms.sourceforge.net/>. We've used the White project with success. *Same Answer to a previous question* **Edit** The White project has moved, and is now located on [GitHub](https://github.com/TestStack/White) as part of TestStack.
[AutomatedQA's TestComplete](http://www.automatedqa.com/products/testcomplete/index.asp) is a good testing application to automate GUI testing. It supports more than just Windows Forms also, so you can reuse it for other applications. It is not open source and this is the best that I have found. I haven't seen an open source equivalent to WatiN. It does have a free trial, for you decide if you like it or not. The main reason I went with it, is that it really is cost effective, compared to other testing applications.
Is there any way to automate windows forms testing?
[ "", "c#", ".net", "vb.net", "winforms", "automated-tests", "" ]
I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list. The custom list defines an iterator; ``` class Iterator: public std::iterator<std::forward_iterator_tag, T> { // ... } Iterator begin() { return (Iterator(root)); } Iterator end() { return (Iterator(NULL)); } ``` with the appropriate operators overloaded. Ideally, I would like to do this; ``` class Foo { public: Foo() { std::list<int> x; std::vector<int> y; custom_list<int> z; iter = x.begin(); // OR iter = y.begin(); // OR iter = z.begin(); // ... }; private: std::iterator<int> iter; }; ``` But obviously these are all iterators of different types. I can assume all the containers are of the same type however. Is there an elegant way to solve this problem?
Here are some articles you might find of interest [Giving STL Iterators a Base Class](http://accu.org/index.php/journals/479) [Type Erasure for C++ Iterators](http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/start_page.html) [any\_iterator Class Reference](http://stlab.adobe.com/classadobe_1_1any__iterator.html)
Better late than never... The latest issue of [C-Vu](http://accu.org/index.php/aboutus/aboutjournals) turned up and guess what was in it: That's right, iterators that do *exactly* what you wanted. Unfortunately you need to become a member of the [ACCU](http://accu.org/) to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so [what are you waiting for](http://accu.org/index.php/joining)?
Generic iterator
[ "", "c++", "generics", "iteration", "containers", "" ]
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: * <http://www.artima.com/weblogs/viewpost.jsp?thread=214235> * <http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/> From the last link an interesting quote: > Let me explain what all that means. > Threads run inside the same virtual > machine, and hence run on the same > physical machine. Processes can run > on the same physical machine or in > another physical machine. If you > architect your application around > threads, you’ve done nothing to access > multiple machines. So, you can scale > to as many cores are on the single > machine (which will be quite a few > over time), but to really reach web > scales, you’ll need to solve the > multiple machine problem anyway. If you want to use multi core, [pyprocessing](http://www.python.org/dev/peps/pep-0371/) defines an process based API to do real parallelization. The [PEP](http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development) also includes some interesting benchmarks.
Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes. EDIT: I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well. Thus, you need to re-consider why you want to use threads. If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes. If you want to improve responsiveness, you should CONSIDER using threads. There are other alternatives though, namely [microthreading](http://en.wikipedia.org/wiki/Microthread). There are also some frameworks that you should look into: * [stackless python](http://www.stackless.com/) * [greenlets](http://greenlet.readthedocs.org/en/latest/) * [gevent](http://www.gevent.org/) * [monocle](https://github.com/saucelabs/monocle)
How do threads work in Python, and what are common Python-threading specific pitfalls?
[ "", "python", "multithreading", "" ]
I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0?
Why not: ``` string s = "foobar\ngork"; string v = s.Replace(Environment.NewLine,","); System.Console.WriteLine(v); ```
Like this: ``` string s = "hello\nworld"; s = s.Replace(Environment.NewLine, ","); ```
What would be the fastest way to remove Newlines from a String in C#?
[ "", "c#", ".net", "string", "replace", "" ]
How do you automatically set the focus to a textbox when a web page loads? Is there an HTML tag to do it or does it have to be done via Javascript?
If you're using jquery: ``` $(function() { $("#Box1").focus(); }); ``` or prototype: ``` Event.observe(window, 'load', function() { $("Box1").focus(); }); ``` or plain javascript: ``` window.onload = function() { document.getElementById("Box1").focus(); }; ``` though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.
In HTML there's an [`autofocus` attribute](http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#autofocusing-a-form-control) to all form fields. There's a good tutorial on it in [Dive Into HTML 5](http://diveintohtml5.info/forms.html#autofocus). Unfortunately it's currently not [supported](http://www.wufoo.com/html5/attributes/02-autofocus.html) by IE versions less than 10. To use the HTML 5 attribute and fall back to a JS option: ``` <input id="my-input" autofocus="autofocus" /> <script> if (!("autofocus" in document.createElement("input"))) { document.getElementById("my-input").focus(); } </script> ``` No jQuery, onload or event handlers are required, because the JS is below the HTML element. Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers. Edit 2: Firefox 4 now supports the `autofocus` attribute, just leaving IE without support.
How do you automatically set the focus to a textbox when a web page loads?
[ "", "javascript", "html", "" ]
In the STL almost all containers have an erase function. The question I have is in a vector, the erase function returns an iterator pointing to the next element in the vector. The map container does not do this. Instead it returns a void. Anyone know why there is this inconsistancy?
See <http://www.sgi.com/tech/stl/Map.html> > Map has the important property that > inserting a new element into a map > does not invalidate iterators that > point to existing elements. Erasing an > element from a map also does not > invalidate any iterators, except, of > course, for iterators that actually > point to the element that is being > erased. The reason for returning an iterator on erase is so that you can iterate over the list erasing elements as you go. If erasing an item doesn't invalidate existing iterators there is no need to do this.
`erase` returns an `iterator` in C++11. This is due to [defect report 130](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2728.html#130): > Table 67 (23.1.1) says that container::erase(iterator) returns an iterator. Table 69 (23.1.2) says that in addition to this requirement, associative containers also say that container::erase(iterator) returns void. That's not an addition; it's a change to the requirements, which has the effect of making associative containers fail to meet the requirements for containers. The standards committee accepted this: > the LWG agrees the return type should be iterator, not void. (Alex Stepanov agrees too.) (LWG = Library Working Group).
STL vector vs map erase
[ "", "c++", "stl", "" ]
I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this - ``` /src MyClass.java /test MyClassTest.java ``` and so on. When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.
I think it's a good idea to keep your files separate. I normally use a folder structure like this: ``` /myapp/src/ <- my classes /myapp/tests/ <- my tests for the classes /myapp/public/ <- document root ``` In your case, for including the class in your test file, why not just pass the the whole path to the include method? ``` include('/path/to/myapp/src/MyClass.php'); ``` or ``` include('../src/MyClass.php'); ```
You need to modify PHP's include\_path so that it knows where to find MyClass.php when you `include()` it in your unit test. You could have something like this at the top of your test file (preceding your include): ``` set_include_path(get_include_path() . PATH_SEPARATOR . "../src"); ``` This appends your `src` directory onto the include path and should allow you to keep your real code separate from your test code.
Directory layout for PHPUnit tests?
[ "", "php", "unit-testing", "phpunit", "" ]
Does anyone know of an open source module or a good method for handling application errors and e-mailing them to an admin and/or saving to a database?
[ELMAH](http://code.google.com/p/elmah/) is a great drop-in tool for this. DLL in the bin directory, and some markup to add to the web.config and you're done.
[log4net](http://logging.apache.org/log4net/index.html) can save errors to a database or send emails. We use this at my job (despite the fact it caused Jeff Atwood much stress in the SO beta). Catch the errors in the global.asax page in the Application Error method.
Error handling reporting methods with ASP.NET 2.0 / C#
[ "", "c#", "asp.net", "" ]
This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight. The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time. My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system.
This is what I've learned so far from my research. .NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler: ``` -- network protocol: TCP/IP set quoted_identifier off set arithabort off set numeric_roundabort off set ansi_warnings on set ansi_padding on set ansi_nulls off set concat_null_yields_null on set cursor_close_on_commit off set implicit_transactions off set language us_english set dateformat mdy set datefirst 7 set transaction isolation level read committed ``` I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same. For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second. The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one. But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes. Is there something else about the arithabort setting that might cause a query to run slowly in some cases? The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'. For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster). But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds.
I've had similar problems. Try setting the with "WITH RECOMPILE" option on the sproc create to force the system to recompute the execution plan each time it is called. Sometimes the Query processor gets confused in complex stored procedures with lots of branching or case statements and just pulls a really sub-optimal execution plan. If that seems to "fix" the problem, you will probably need to verify statistics are up to date and/or break down the sproc. You can also confirm this by profiling the sproc. When you execute it from SQL Managment Studio, how does the IO compare to when you profile it from the ASP.NET application. If they very a lot, it just re-enforces that its pulling a bad execution plan.
Query times out from web app but runs fine from management studio
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this: ``` Category | Revenue | Yearh | Month Bikes 10 000 2008 1 Bikes 12 000 2008 2 Bikes 12 000 2008 3 Bikes 15 000 2008 1 Bikes 11 000 2007 2 Bikes 11 500 2007 3 Bikes 15 400 2007 4 ``` ... And so forth The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 ``` The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up. Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008. The query I got looks something like this: ``` SELECT SP1.Program, SP1.Year, SP1.Month, SP1.TotalRevenue, IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue FROM PVMonthlyStatusReport AS SP1 LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON SP1.Program = SP2.Program AND SP2.Year = SP1.Year - 1 AND SP1.Month = SP2.Month WHERE SP1.Program = 'Bikes' AND SP1.Category = @Category AND (SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND ((SP1.Year = @FinancialYear AND SP1.Month > 6) OR (SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6)) ORDER BY SP1.Year, SP1.Month ``` The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007. This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated! Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.
The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months. Assumptions are based on the availability of following tables: > sales: Category | Revenue | Yearh | > Month and > tm: Year | Month (populated with all > dates required for reporting) Example 1 without empty rows: ``` select Category ,month ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year from sales where year in (2008,2007) group by Category ,month ``` RETURNS: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 ``` Example 2 with empty rows: I am going to use a sub query (but others may not) and will return an empty row for every product and year month combo. ``` select fill.Category ,fill.month ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year from sales Right join (select distinct --try out left, right and cross joins to test results. product ,year ,month from sales --this ideally would be from a products table cross join tm where year in (2008,2007)) fill where fill.year in (2008,2007) group by fill.Category ,fill.month ``` RETURNS: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 Bikes 5 0 0 Bikes 6 0 0 Bikes 7 0 0 Bikes 8 0 0 ``` Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well. Here are some additional resources. CASE <https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml> SQL SERVER 2005 PIVOT <http://msdn.microsoft.com/en-us/library/ms177410.aspx>
@Christian -- markdown editor -- UGH; especially when the preview and the final version of your post disagree... @Christian -- full outer join -- the full outer join is overruled by the fact that there are references to SP1 in the WHERE clause, and the WHERE clause is applied after the JOIN. To do a full outer join with filtering on one of the tables, you need to put your WHERE clause into a subquery, so the filtering happens *before* the join, or try to build all of your WHERE criteria onto the JOIN ON clause, which is insanely ugly. Well, there's actually no pretty way to do this one. @Jonas: Considering this: > Also, the report is actually for financial year - so **I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.** and the fact that this job can't be done with a pretty query, I would definitely try to get the results you actually want. No point in having an ugly query and not even getting the exact data you actually want. ;) So, I'd suggest doing this in 5 steps: 1. create a temp table in the format you want your results to match 2. populate it with twelve rows, with 1-12 in the month column 3. update the "This Year" column using your SP1 logic 4. update the "Last Year" column using your SP2 logic 5. select from the temp table Of course, I guess I'm working from the assumption that you can create a stored procedure to accomplish this. You might technically be able to run this whole batch inline, but that kind of ugliness is very rarely seen. If you can't make an SP, I suggest you fall back on the full outer join via subquery, but it won't get you a row when a month had no sales either year.
SQL query to compare product sales by month
[ "", "sql", "sql-server", "sql-server-2005", "reporting", "" ]
If you are working in PHP (or I guess any programming language) and using subversion as your source control, is there a way to take your project (for example): > C:\Projects\test\.svn > C:\Projects\test\docs\ > C:\Projects\test\faq.php > C:\Projects\test\guestbook.php > C:\Projects\test\index.php > C:\Projects\test\test.php and build/copy/whatever it so it weeds out certain files and becomes: > C:\Projects\test\faq.php > C:\Projects\test\guestbook.php > C:\Projects\test\index.php automatically? I'm getting tired of making a branch, and then going through the branch and deleting all of the ".svn" folders, the docs directory, and my prototyping files. I know I could probably use a .bat file to only copy the specific files I want, but I was hoping there was some way with subversion to sort of pseudo ignore a file, to where it will still version it, but where you could make a snapshot of the project that ignores the files you told it to pseudo ignore. I know I read online somewhere about some functionality that at least lets you copy without the .svn folders, but I can't find it now.
If you use TortoiseSVN, you can use the export feature to automatically strip out all of the .svn files. I think other svn things have the same feature. Right click the root project folder, then select `TortoiseSVN > Export`, and tell it where you want the `.svn` free directory.
Copy all the files manually or using your existing method for the first time. Then, since I take it you're on a Windows platform, install [SyncToy](http://www.microsoft.com/downloads/details.aspx?FamilyId=E0FC1154-C975-4814-9649-CCE41AF06EB7&displaylang=en) and configure it in the [subscribe method](http://en.wikipedia.org/wiki/SyncToy#Features), which would effectively one-way copy only the changes made since the last pseudo-commit to production for files already in production. If you want to add a file you can just copy it manually and resume the SyncToy operation.
Making a production build of a PHP project with Subversion
[ "", "php", "svn", "scripting", "tortoisesvn", "build-process", "" ]
I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.
You can try the following tool to make things more sane: <http://www.bdsoft.com/tools/stlfilt.html>
I sure as hell can't. Small errors explode into pages and pages of unreadable junk. Usually early in the morning, before coffee. :( My only advice is to take a deep breath, start at the top and try and parse the important pieces of information. (I know, easier said than done, right?).
Deciphering C++ template error messages
[ "", "c++", "templates", "compiler-errors", "" ]
How can I set, clear, and toggle a bit?
### Setting a bit Use the bitwise OR operator (`|`) to set `n`th bit of `number` to `1`. ``` // Can be whatever unsigned integer type you want, but // it's important to use the same type everywhere to avoid // performance issues caused by mixing integer types. typedef unsigned long Uint; // In C++, this can be template. // In C11, you can make it generic with _Generic, or with macros prior to C11. inline Uint bit_set(Uint number, Uint n) { return number | ((Uint)1 << n); } ``` Note that it's undefined behavior to shift by more than the width of a `Uint`. The same applies to all remaining examples. ### Clearing a bit Use the bitwise AND operator (`&`) to set the `n`th bit of `number` to `0`. ``` inline Uint bit_clear(Uint number, Uint n) { return number & ~((Uint)1 << n); } ``` You must invert the bit string with the bitwise NOT operator (`~`), then AND it. ### Toggling a bit Use the bitwise XOR operator (`^`) to toggle the `n`th bit of `number`. ``` inline Uint bit_toggle(Uint number, Uint n) { return number ^ ((Uint)1 << n); } ``` ### Checking a bit You didn't ask for this, but I might as well add it. To check a bit, shift `number` `n` to the right, then bitwise AND it: ``` // bool requires #include <stdbool.h> prior to C23 inline bool bit_check(Uint number, Uint n) { return (number >> n) & (Uint)1; } ``` ### Changing the *n*th bit to *x* There are alternatives with worse codegen, but the best way is to clear the bit like in `bit_clear`, then set the bit to value, similar to `bit_set`. ``` inline Uint bit_set_to(Uint number, Uint n, bool x) { return (number & ~((Uint)1 << n)) | ((Uint)x << n); } ``` --- All solutions have been tested to provide optimal codegen with GCC and clang. See <https://godbolt.org/z/Wfzh8xsjW>.
Using the Standard C++ Library: [`std::bitset<N>`](http://en.cppreference.com/w/cpp/utility/bitset). Or the [Boost](http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29) version: [`boost::dynamic_bitset`](http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html). There isn't any need to roll your own: ``` #include <bitset> #include <iostream> int main() { std::bitset<5> x; x[1] = 1; x[2] = 0; // Note x[0-4] valid std::cout << x << std::endl; } ``` --- ``` ./a.out ``` Output: ``` 00010 ``` The Boost version allows a runtime sized bitset compared with a [standard library](https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library) compile-time sized bitset.
How to set, clear, and toggle a single bit
[ "", "c++", "c", "bit-manipulation", "bitwise-operators", "" ]
If one wants to paginate results from a data source that supports pagination we have to go to a process of: 1. defining the page size - that is the number of results to show per page; 2. fetch each page requested by the user using an offset = page number (0 based) \* page size 3. show the results of the fetched page. All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data. ``` page_size = 10; get page 0 -> results from 0 to 9; user inserts a record that due to the query being executed goes to page 0 - the one just shown; get page 1 -> results from 10 to 19 - the first results on the page is the result on the old page 0. ``` The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem.
There are a few schools of thought o this. 1. data gets updated let it be 2. You could implement some sort of caching method that will hold the entire result set (This might not be an option if working with really large Datasets) 3. You could do a comparison on each page operation and notify the user if the total record count changes .
If the updates you are concerned with are primarily new insertions (for example, StackOverflow itself seems to suffer from this problem when paging through questions and new questions come in) one way to handle it is to capture a timestamp when you issue the first pagination query, and then limit the results of requests for subsequent pages to items which existed before that timestamp.
Keep pagination repeatable if change operations are performed
[ "", "sql", "pagination", "" ]
I've opened an old workspace that is a library and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app. I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately, I can't post the project as this is used in production code. The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However, this is part of the standard template library - and is a header at that. The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use `std::string` directly, but does call a class that does: `Comms::Exception` accepts a `std::string` and the value of `GetLastError` or `WSAGetLastError`. The function mentioned in the error (`GetMessage`) is implemented but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an ANSI version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However, both projects specify \_MBCS in the compiler options. > --------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj) > : error LNK2001: unresolved external symbol "public: virtual class > std::basic\_string<char,struct std::char\_traits,class > std::allocator > \_\_thiscall > Comms::Exception::GetMessageA(void)const " (?GetMessageA@ > Exception@Comms@@UBE?AV?$basic\_string@DU?$char\_traits@D@std@@V?$allocator@D@2@@std@@XZ) > Debug/TestComms.exe : fatal error LNK1120: 1 unresolved externals > Error executing link.exe. > > TestComms.exe - 2 error(s), 0 warning(s) Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too.
One possibility lies with Win32 ANSI/Unicode "name-mangling", which turns the symbol `GetMessage` into either `GetMessageA` or `GetMessageW`. There are three possibilities: 1. Windows.h hasn't been loaded, so `GetMessage` stays `GetMessage` 2. Windows.h was loaded with symbols set for ANSI, so `GetMessage` becomes `GetMessageA` 3. Windows.h was loaded with symbols set for Unicode, so `GetMessage` becomes `GetMessageW` If you've compiled two different files in ways that trigger two different scenarios, you'll get a linker error. The error message indicates that the `Comms::Exception` class was an instance of #2, above -- perhaps it's used somewhere that windows.h hasn't been loaded? Other things I'd do in your place, just as a matter of routine: 1) Ensure that my include and library paths don't contain anything that I'm not expecting. 2) Do a "build clean" and then manually verify it, deleting any extra object files if necessary. 3) Make sure there aren't any hardcoded paths in include statements that don't mean what they meant when the project was originally rebuilt. EDIT: Fighting with the formatting :(
@Curt: I think you came the closest. I haven't tested this but I think I sort of gave the answer in my original question. [GetMessage](http://msdn.microsoft.com/en-us/library/ms644936.aspx) is a define in Windows.h wrapped in a ifndef block to switch between Ansi (GetMessageA) and Unicode (GetMessageW).
Link issues (VC6)
[ "", "c++", "visual-c++", "linker", "visual-c++-6", "" ]
I have created a UserControl that has a `ListView` in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the `ListView` though the property, the `ListView` stays that way until I compile again and it reverts back to the default state. How do I get my design changes to stick for the `ListView`?
You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so: ``` [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ListView MyListView { get { return this.listView1; } } ``` This tells the designer's code generator to output code for it.
[Fredrik](https://stackoverflow.com/questions/15716/design-problems-with-net-usercontrol#15803) is right, basically, when you need to enable the designer to persist the property to page so it can be instantiated at run time. There is only one way to do this, and that is to write its values to the ASPX page, which is then picked up by the runtime. Otherwise, the control will simply revert to its default state each and every time. Always keep in the back of your mind that the Page (and its contents) and the code are completely seperate in ASP.NET, they are hooked up at run time. This means that you dont get the nice code-behind designer support like you do in a WinForms app (where the form is an instance of an object).
Design problems with .Net UserControl
[ "", "c#", "user-controls", ".net-2.0", "" ]
Has anybody used the MS Project Gantt chart control in C#? If yes, can you share some resources regarding this?
You could also check [Gantt Chart Library](http://DlhSoft.com/GanttChart) for WPF or Windows Forms, they do not require Microsoft Project installed on the client computer, but provide similar UI for project and related Gantt Charts.
Try these links for a start. <http://www.ilog.com/products/ganttnet/> <http://www.netronic.com/products-for-developers/gantt-charts.html?gclid=COLdutasoZUCFQunQwodoWOPkw>
MS Project Gantt chart control usage in C#
[ "", "c#", ".net-2.0", "controls", "ms-project", "gantt-chart", "" ]
Looking for an example that: 1. Launches an EXE 2. Waits for the EXE to finish. 3. Properly closes all the handles when the executable finishes.
Something like this: ``` STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) { WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } ```
There is an example at [<http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx>](http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx) Just replace the `argv[1]` with your constant or variable containing the program. ``` #include <windows.h> #include <stdio.h> #include <tchar.h> void _tmain( int argc, TCHAR *argv[] ) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if( argc != 2 ) { printf("Usage: %s [cmdline]\n", argv[0]); return; } // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) argv[1], // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d).\n", GetLastError() ); return; } // Wait until child process exits. WaitForSingleObject( pi.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } ```
How do I call ::CreateProcess in c++ to launch a Windows executable?
[ "", "c++", "windows", "winapi", "" ]
I want to be able to make an HTTP call updating some select boxes after a date is selected. I would like to be in control of updating the textbox so I know when there has been a "true" change (in the event the same date was selected). Ideally, I would call a function to pop-up the calendar and be able to evaluate the date before populating the text box...so I can do my validation before making a server call.
JQuery's [datepicker](http://docs.jquery.com/UI/Datepicker) is an extremely flexible tool. With the ability to attach handlers prior to opening or after date selection, [themes](http://marcgrabanski.com/article/jquery-ui-datepicker-themes), range selection and a variety of other incredibly useful options, I've found that it meets all my needs. The fact that I sit next to one of its maintainers here at work is also fairly useful...
I've been playing with the jquery datePicker script - you should be able to do everything you need to with this.
What is the best calendar pop-up to populate a web form?
[ "", "javascript", "calendar", "" ]
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.
> : are lambda expressions useful for anything other than querying Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'. So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.) An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function. This <http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx> is a superb step-by-step introduction into all this stuff, which might help you.
Lambdas bring functional programing to C#. They are anonymous functions that can be passed as values to certain other functions. Used most in LINQ. Here is a contrived example: ``` List<int> myInts = GetAll(); IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0); ``` Now when you foreach through evenNumbers the lamda ``` x=> x % 2 == 0 ``` is then applied as a filter to myInts. They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops.
What is appliance and how to use lambda expressions?
[ "", "c#", "lambda", "" ]
I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)? Some people pointed to `Application.LocalUserAppDataPath`. However, that creates a folder structure like: > C:\Documents and Settings\user\_name\Local Settings\Application > Data\company\_name\product\_name\product\_version\ If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I love using the built-in [Application Settings](http://msdn.microsoft.com/en-us/library/a65txexh.aspx). Then you have built in support for using the settings designer if you want at design-time, or at runtime to use: ``` // read setting string setting1 = (string)Settings.Default["MySetting1"]; // save setting Settings.Default["MySetting2"] = "My Setting Value"; // you can force a save with Properties.Settings.Default.Save(); ``` It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to: ``` Properties.Settings.Default.Upgrade(); ``` The app will pull all previous versions settings in to save in.
.NET applications have a built-in settings mechanism that is easy to use. The problem with it, in my opinion, is that it stores those settings off into a rather obscure directory and end users will not be able to find it. Moreover, just switching from debug to release build changes the location of this directory, meaning that any settings saved in one configuration are lost in the other. For these and other reasons, I came up with [my own settings code for Windows Forms](http://www.blackbeltcoder.com/Articles/winforms/a-custom-settings-class-for-winforms). It's not quite as slick as the one that comes with .NET, but it's more flexible, and I use it all the time.
What is the best way to store user settings for a .NET application?
[ "", "c#", ".net", "" ]
I have the following code: ``` $bind = new COM("LDAP://CN=GroupName,OU=Groups,OU=Division,DC=company,DC=local"); ``` When I execute it from a command-prompt, it runs fine. When it runs under IIS/PHP/ISAPI, it barfs. ``` Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `LDAP://CN=...[cut]...,DC=local': An operations error occurred. ' in index.php Stack trace: #0 index.php: com->com('LDAP://CN=...') #1 {main} thrown ``` IIS is configured for Windows Authentication (no anonymous, no basic, no digest) and I am connecting as the same user as the command prompt. I cannot find any specific errors in the IIS logfiles or the eventlog. The main purpose of this exercise is to refrain from keeping user credentials in my script and relying on IIS authentication to pass them through to the active directory. I understand that you can use LDAP to accomplish the same thing, but as far as I know credentials cannot be passed through. Perhaps it is in some way related to the error I get when I try to port it to ASP. I get error 80072020 (which I'm currently looking up). The event logs show nothing out of the ordinary. No warnings, no errors. Full security auditing is enabled (success and failure on every item in the security policy), and it shows successful Windows logons for every user I authenticate against the web page (which is expected.)
Since you're using Windows Authentication in IIS, you may have some security events in the Windows Event log. I would check the Event log for Security Events as well as Application Events and see if you're hitting any sort of permissions issues. Also, since you're basically just communicating to AD via LDAP...you might look into using the a native LDAP library for PHP rather than a COM. You'll have to enable the extension probably in your php.ini. Worth looking at probably.
It seems to be working now. I enabled "Trust this computer for delegation" for the computer object in Active Directory. Normally IIS cannot both authenticate you and then subsequently impersonate you across the network (in my case to a domain controller to query Active Directory) without the delegation trust enabled. You just have to be sure that it's authenticating using Kerberos and not NTLM or some other digest authentication because the digest is not trusted to use as an impersonation token. It fixed both my PHP and ASP scripts.
How To Read Active Directory Group Membership From PHP/IIS using COM?
[ "", "php", "iis", "com", "adsi", "" ]
To make it short: hibernate doesn't support projections and query by example? I found this post: The code is this: ``` User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)) ``` Like the other poster said, The generated sql keeps having a where class refering to just **y0\_= ? instead of this\_.city**. I already tried several approaches, and searched the issue tracker but found nothing about this. I even tried to use Projection alias and Transformers, but it does not work: ``` User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class)); ``` Has anyone used projections and query by example ?
Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though). ``` getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Restrictions.eq("city", "TEST"))) .setResultTransformer(Transformers.aliasToBean(User.class)) .list(); ``` I've never used the alaistToBean, but I just read about it. You could also just loop over the results.. ``` List<Object> rows = criteria.list(); for(Object r: rows){ Object[] row = (Object[]) r; Type t = ((<Type>) row[0]); } ``` If you have to you can manually populate User yourself that way. Its sort of hard to look into the issue without some more information to diagnose the issue.
The problem seems to happen when you have an alias the same name as the objects property. Hibernate seems to pick up the alias and use it in the sql. I found this documented [here](http://opensource.atlassian.com/projects/hibernate/browse/HHH-3371;jsessionid=aLJbC8zJhKhanJbr49?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel) and [here](https://forum.hibernate.org/viewtopic.php?t=988049), and I believe it to be a bug in Hibernate, although I am not sure that the Hibernate team agrees. Either way, I have found a simple work around that works in my case. Your mileage may vary. The details are below, I tried to simplify the code for this sample so I apologize for any errors or typo's: ``` Criteria criteria = session.createCriteria(MyClass.class) .setProjection(Projections.projectionList() .add(Projections.property("sectionHeader"), "sectionHeader") .add(Projections.property("subSectionHeader"), "subSectionHeader") .add(Projections.property("sectionNumber"), "sectionNumber")) .add(Restrictions.ilike("sectionHeader", sectionHeaderVar)) // <- Problem! .setResultTransformer(Transformers.aliasToBean(MyDTO.class)); ``` Would produce this sql: ``` select this_.SECTION_HEADER as y1_, this_.SUB_SECTION_HEADER as y2_, this_.SECTION_NUMBER as y3_, from MY_TABLE this_ where ( lower(y1_) like ? ) ``` Which was causing an error: *java.sql.SQLException: ORA-00904: "Y1\_": invalid identifier* **But, when I changed my restriction to use "this", like so:** ``` Criteria criteria = session.createCriteria(MyClass.class) .setProjection(Projections.projectionList() .add(Projections.property("sectionHeader"), "sectionHeader") .add(Projections.property("subSectionHeader"), "subSectionHeader") .add(Projections.property("sectionNumber"), "sectionNumber")) .add(Restrictions.ilike("this.sectionHeader", sectionHeaderVar)) // <- Problem Solved! .setResultTransformer(Transformers.aliasToBean(MyDTO.class)); ``` It produced the following sql and my problem was solved. ``` select this_.SECTION_HEADER as y1_, this_.SUB_SECTION_HEADER as y2_, this_.SECTION_NUMBER as y3_, from MY_TABLE this_ where ( lower(this_.SECTION_HEADER) like ? ) ``` Thats, it! A pretty simple fix to a painful problem. I don't know how this fix would translate to the query by example problem, but it may get you closer.
Hibernate Query By Example and Projections
[ "", "java", "hibernate", "criteria", "projection", "" ]
I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server. I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6. If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even *trying* to connect to the server to begin with. Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly. Here are my security-related beans: ``` <beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"> <beans:constructor-arg> <beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"> <beans:constructor-arg ref="initialDirContextFactory" /> <beans:property name="userDnPatterns"> <beans:list> <beans:value>CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com</beans:value> </beans:list> </beans:property> </beans:bean> </beans:constructor-arg> </beans:bean> <beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager"> <beans:constructor-arg ref="initialDirContextFactory" /> </beans:bean> <beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"> <beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" /> </beans:bean> ```
I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provider that does an LDAP query against the Active Directory server. So my security-related beans are: ``` <beans:bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource"> <beans:constructor-arg value="ldap://hostname.queso.com:389/" /> </beans:bean> <beans:bean id="ldapAuthenticationProvider" class="org.queso.ad.service.authentication.LdapAuthenticationProvider"> <beans:property name="authenticator" ref="ldapAuthenticator" /> <custom-authentication-provider /> </beans:bean> <beans:bean id="ldapAuthenticator" class="org.queso.ad.service.authentication.LdapAuthenticatorImpl"> <beans:property name="contextFactory" ref="contextSource" /> <beans:property name="principalPrefix" value="QUESO\" /> </beans:bean> ``` Then the LdapAuthenticationProvider class: ``` /** * Custom Spring Security authentication provider which tries to bind to an LDAP server with * the passed-in credentials; of note, when used with the custom {@link LdapAuthenticatorImpl}, * does <strong>not</strong> require an LDAP username and password for initial binding. * * @author Jason */ public class LdapAuthenticationProvider implements AuthenticationProvider { private LdapAuthenticator authenticator; public Authentication authenticate(Authentication auth) throws AuthenticationException { // Authenticate, using the passed-in credentials. DirContextOperations authAdapter = authenticator.authenticate(auth); // Creating an LdapAuthenticationToken (rather than using the existing Authentication // object) allows us to add the already-created LDAP context for our app to use later. LdapAuthenticationToken ldapAuth = new LdapAuthenticationToken(auth, "ROLE_USER"); InitialLdapContext ldapContext = (InitialLdapContext) authAdapter .getObjectAttribute("ldapContext"); if (ldapContext != null) { ldapAuth.setContext(ldapContext); } return ldapAuth; } public boolean supports(Class clazz) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz)); } public LdapAuthenticator getAuthenticator() { return authenticator; } public void setAuthenticator(LdapAuthenticator authenticator) { this.authenticator = authenticator; } } ``` Then the LdapAuthenticatorImpl class: ``` /** * Custom Spring Security LDAP authenticator which tries to bind to an LDAP server using the * passed-in credentials; does <strong>not</strong> require "master" credentials for an * initial bind prior to searching for the passed-in username. * * @author Jason */ public class LdapAuthenticatorImpl implements LdapAuthenticator { private DefaultSpringSecurityContextSource contextFactory; private String principalPrefix = ""; public DirContextOperations authenticate(Authentication authentication) { // Grab the username and password out of the authentication object. String principal = principalPrefix + authentication.getName(); String password = ""; if (authentication.getCredentials() != null) { password = authentication.getCredentials().toString(); } // If we have a valid username and password, try to authenticate. if (!("".equals(principal.trim())) && !("".equals(password.trim()))) { InitialLdapContext ldapContext = (InitialLdapContext) contextFactory .getReadWriteContext(principal, password); // We need to pass the context back out, so that the auth provider can add it to the // Authentication object. DirContextOperations authAdapter = new DirContextAdapter(); authAdapter.addAttributeValue("ldapContext", ldapContext); return authAdapter; } else { throw new BadCredentialsException("Blank username and/or password!"); } } /** * Since the InitialLdapContext that's stored as a property of an LdapAuthenticationToken is * transient (because it isn't Serializable), we need some way to recreate the * InitialLdapContext if it's null (e.g., if the LdapAuthenticationToken has been serialized * and deserialized). This is that mechanism. * * @param authenticator * the LdapAuthenticator instance from your application's context * @param auth * the LdapAuthenticationToken in which to recreate the InitialLdapContext * @return */ static public InitialLdapContext recreateLdapContext(LdapAuthenticator authenticator, LdapAuthenticationToken auth) { DirContextOperations authAdapter = authenticator.authenticate(auth); InitialLdapContext context = (InitialLdapContext) authAdapter .getObjectAttribute("ldapContext"); auth.setContext(context); return context; } public DefaultSpringSecurityContextSource getContextFactory() { return contextFactory; } /** * Set the context factory to use for generating a new LDAP context. * * @param contextFactory */ public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) { this.contextFactory = contextFactory; } public String getPrincipalPrefix() { return principalPrefix; } /** * Set the string to be prepended to all principal names prior to attempting authentication * against the LDAP server. (For example, if the Active Directory wants the domain-name-plus * backslash prepended, use this.) * * @param principalPrefix */ public void setPrincipalPrefix(String principalPrefix) { if (principalPrefix != null) { this.principalPrefix = principalPrefix; } else { this.principalPrefix = ""; } } } ``` And finally, the LdapAuthenticationToken class: ``` /** * <p> * Authentication token to use when an app needs further access to the LDAP context used to * authenticate the user. * </p> * * <p> * When this is the Authentication object stored in the Spring Security context, an application * can retrieve the current LDAP context thusly: * </p> * * <pre> * LdapAuthenticationToken ldapAuth = (LdapAuthenticationToken) SecurityContextHolder * .getContext().getAuthentication(); * InitialLdapContext ldapContext = ldapAuth.getContext(); * </pre> * * @author Jason * */ public class LdapAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = -5040340622950665401L; private Authentication auth; transient private InitialLdapContext context; private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); /** * Construct a new LdapAuthenticationToken, using an existing Authentication object and * granting all users a default authority. * * @param auth * @param defaultAuthority */ public LdapAuthenticationToken(Authentication auth, GrantedAuthority defaultAuthority) { this.auth = auth; if (auth.getAuthorities() != null) { this.authorities.addAll(Arrays.asList(auth.getAuthorities())); } if (defaultAuthority != null) { this.authorities.add(defaultAuthority); } super.setAuthenticated(true); } /** * Construct a new LdapAuthenticationToken, using an existing Authentication object and * granting all users a default authority. * * @param auth * @param defaultAuthority */ public LdapAuthenticationToken(Authentication auth, String defaultAuthority) { this(auth, new GrantedAuthorityImpl(defaultAuthority)); } public GrantedAuthority[] getAuthorities() { GrantedAuthority[] authoritiesArray = this.authorities.toArray(new GrantedAuthority[0]); return authoritiesArray; } public void addAuthority(GrantedAuthority authority) { this.authorities.add(authority); } public Object getCredentials() { return auth.getCredentials(); } public Object getPrincipal() { return auth.getPrincipal(); } /** * Retrieve the LDAP context attached to this user's authentication object. * * @return the LDAP context */ public InitialLdapContext getContext() { return context; } /** * Attach an LDAP context to this user's authentication object. * * @param context * the LDAP context */ public void setContext(InitialLdapContext context) { this.context = context; } } ``` You'll notice that there are a few bits in there that you might not need. For example, my app needed to retain the successfully-logged-in LDAP context for further use by the user once logged in -- the app's purpose is to let users log in via their AD credentials and then perform further AD-related functions. So because of that, I have a custom authentication token, LdapAuthenticationToken, that I pass around (rather than Spring's default Authentication token) which allows me to attach the LDAP context. In LdapAuthenticationProvider.authenticate(), I create that token and pass it back out; in LdapAuthenticatorImpl.authenticate(), I attach the logged-in context to the return object so that it can be added to the user's Spring authentication object. Also, in LdapAuthenticationProvider.authenticate(), I assign all logged-in users the ROLE\_USER role -- that's what lets me then test for that role in my intercept-url elements. You'll want to make this match whatever role you want to test for, or even assign roles based on Active Directory groups or whatever. Finally, and a corollary to that, the way I implemented LdapAuthenticationProvider.authenticate() gives all users with valid AD accounts the same ROLE\_USER role. Obviously, in that method, you can perform further tests on the user (i.e., is the user in a specific AD group?) and assign roles that way, or even test for some condition before even granting the user access at *all*.
For reference, Spring Security 3.1 has an authentication provider [specifically for Active Directory](http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory).
How do you authenticate against an Active Directory server using Spring Security?
[ "", "java", "spring", "active-directory", "ldap", "" ]
If I have 2 query sources how do I find ones that are in one that are not in the other? example of join to find items in both: ``` var results = from item1 in qs1.Items join item2 in qs2 on item1.field1 equals item2.field2 select item1; ``` So what would the linq code be to return the items in qs1 that are not in qs2?
Darren Kopp's [answer](https://stackoverflow.com/questions/50702/linq-how-do-you-do-a-query-for-items-in-one-query-source-that-are-not-in-anothe/50724#50724): ``` var excluded = items1.Except(items2); ``` is the best solution from a performance perspective. *(NB: This true for at least regular LINQ, perhaps LINQ to SQL changes things as per [Marco Russo's blog post](http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx). However, I'd imagine that in the "worst case" Darren Kopp's method will return at least the speed of Russo's method even in a LINQ to SQL environment).* As a quick example try this in [LINQPad](http://www.linqpad.net/): ``` void Main() { Random rand = new Random(); int n = 100000; var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next()); var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next()); /* Method 1: Bramha Ghosh's/Marco Russo's method */ (from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump("Result"); /* Method 2: Darren Kopp's method */ randomSeq.Except(randomFilter).Dump("Result"); } ``` Try commenting one of the two methods out at a time and try out the performance for different values of n. My experience (on my Core 2 Duo Laptop) seems to suggest: ``` n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds n = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds n = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds n = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds n = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds ``` *Method 2 (Darren Kopp's answer) is clearly faster.* The speed decrease for Method 2 for larger n is most likely due to the creation of the random data (feel free to put in a DateTime diff to confirm this) whereas Method 1 clearly has algorithmic complexity issues (and just by looking you can see it is at least O(N^2) as for each number in the first collection it is comparing against the entire second collection). **Conclusion:** Use Darren Kopp's answer of LINQ's 'Except' method
From [Marco Russo](http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx) ``` NorthwindDataContext dc = new NorthwindDataContext(); dc.Log = Console.Out; var query = from c in dc.Customers where !(from o in dc.Orders select o.CustomerID) .Contains(c.CustomerID) select c; foreach (var c in query) Console.WriteLine( c ); ```
linq - how do you do a query for items in one query source that are not in another one?
[ "", "c#", ".net", "linq", ".net-3.5", "" ]
ASP.NET 2.0 provides the `ClientScript.RegisterClientScriptBlock()` method for registering JavaScript in an ASP.NET Page. The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work: ``` ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true); ``` Instead of dropping the code into the page like [this page](http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7) says it should, it instead displays `../dir/subdir/script.js` , my question is this: Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?
What you're after is: ``` ClientScript.RegisterClientScriptInclude(this.GetType(), "scriptName", "../dir/subdir/scriptName.js") ```
use: ClientScript.RegisterClientScriptInclude(key, url);
How do I use RegisterClientScriptBlock to register JavaScript?
[ "", "javascript", "asp.net", "" ]
I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
[Enums](https://docs.python.org/3/library/enum.html) have been added to Python 3.4 as described in [PEP 435](http://www.python.org/dev/peps/pep-0435/). It has also been [backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4](https://pypi.python.org/pypi/enum34) on pypi. For more advanced Enum techniques try the [aenum library](https://pypi.python.org/pypi/aenum) (2.7, 3.3+, same author as `enum34`. Code is not perfectly compatible between py2 and py3, e.g. you'll need [`__order__` in python 2](https://stackoverflow.com/a/25982264/57461)). * To use `enum34`, do `$ pip install enum34` * To use `aenum`, do `$ pip install aenum` Installing `enum` (no numbers) will install a completely different and incompatible version. --- ``` from enum import Enum # for enum34, or the stdlib version # from aenum import Enum # for the aenum version Animal = Enum('Animal', 'ant bee cat dog') Animal.ant # returns <Animal.ant: 1> Animal['ant'] # returns <Animal.ant: 1> (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) ``` or equivalently: ``` class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 ``` --- In earlier versions, one way of accomplishing enums is: ``` def enum(**enums): return type('Enum', (), enums) ``` which is used like so: ``` >>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three' ``` You can also easily support automatic enumeration with something like this: ``` def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) ``` and used like so: ``` >>> Numbers = enum('ZERO', 'ONE', 'TWO') >>> Numbers.ZERO 0 >>> Numbers.ONE 1 ``` Support for converting the values back to names can be added this way: ``` def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) ``` This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a `KeyError` if the reverse mapping doesn't exist. With the first example: ``` >>> Numbers.reverse_mapping['three'] 'THREE' ``` --- If you are using MyPy another way to express "enums" is with [`typing.Literal`](https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals). For example: ``` from typing import Literal #python >=3.8 from typing_extensions import Literal #python 2.7, 3.4-3.7 Animal = Literal['ant', 'bee', 'cat', 'dog'] def hello_animal(animal: Animal): print(f"hello {animal}") hello_animal('rock') # error hello_animal('bee') # passes ```
Before PEP 435, Python didn't have an equivalent but you could implement your own. Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ... ``` class Animal: DOG = 1 CAT = 2 x = Animal.DOG ``` --- In Python 3.4 ([PEP 435](http://www.python.org/dev/peps/pep-0435/)), you can make [Enum](https://docs.python.org/3/library/enum.html) the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a `name` and a `value`. ``` from enum import Enum class Animal(Enum): DOG = 1 CAT = 2 print(Animal.DOG) # <Animal.DOG: 1> print(Animal.DOG.value) # 1 print(Animal.DOG.name) # "DOG" ``` --- If you don't want to type the values, use the following shortcut: ``` class Animal(Enum): DOG, CAT = range(2) ``` --- `Enum` implementations [can be converted to lists and are iterable](https://docs.python.org/3/library/enum.html#how-are-enums-different). The order of its members is the declaration order and has nothing to do with their values. For example: ``` class Animal(Enum): DOG = 1 CAT = 2 COW = 0 list(Animal) # [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>] [animal.value for animal in Animal] # [1, 2, 0] Animal.CAT in Animal # True ```
How can I represent an 'Enum' in Python?
[ "", "python", "python-3.x", "enums", "" ]
I would like to replicate this in python: ``` gvimdiff <(hg cat file.txt) file.txt ``` (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: ``` $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" ``` Getting to the python part... ``` # hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file]) ``` When subprocess is called it merely passes `<(hg cat file)` onto `gvimdiff` as a filename. So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff: ``` diff <(cat file.txt) file.txt ```
It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable: ``` import subprocess import sys file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen([ 'gvimdiff', '/proc/self/fd/%s' % p1.stdout.fileno(), file]) p2.wait() ``` That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question: ``` file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout) diff_text = p2.communicate()[0] ```
There is also the commands module: ``` import commands status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt") ``` There is also the popen set of functions, if you want to actually grok the data from a command as it is running.
Redirect command to input of another in Python
[ "", "python", "bash", "redirect", "diff", "vimdiff", "" ]
The eval function is a powerful and easy way to dynamically generate code, so what are the caveats?
1. Improper use of **eval** opens up your code for injection attacks 2. **Debugging** can be more challenging (no line numbers, etc.) 3. eval'd code executes slower (no opportunity to compile/cache eval'd code) Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.
eval isn't always evil. There are times where it's perfectly appropriate. However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way. To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato': ``` eval('document.' + potato + '.style.color = "red"'); ``` If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval: ``` document[potato].style.color = 'red'; ``` ...which is much easier to read as well as less potentially buggy. (But then, someone who /really/ knew what they were doing would say: ``` document.getElementById(potato).style.color = 'red'; ``` which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)
Why is using the JavaScript eval function a bad idea?
[ "", "javascript", "security", "eval", "" ]
What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP ``` <?php $class_name = 'SomeClassName'; $object = new $class_name; ?> ``` This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement. Problems that come immediately to mind are 1. ~~You lose the ability to pass arguments into a constructor~~ (LIES. Thanks Jeremy) 2. Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?) What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?
One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff. As long as you don't do something like ``` $classname = 'SomeClassName'; for ($x = 0; $x < 100000; $x++){ $object = new $classname; } ``` you are probably fine :-) (my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will). Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.
It looks you can still pass arguments to the constructor, here's my test code: ``` <?php class Test { function __construct($x) { echo $x; } } $class = 'Test'; $object = new $class('test'); // echoes "test" ?> ``` That is what you meant, right? So the only other problem you mentioned and that I can think of is the security of it, but it shouldn't be too difficult to make it secure, and it's obviously a lot more secure than using eval().
Implications of Instantiating Objects with Dynamic Variables in PHP
[ "", "php", "performance", "oop", "" ]
As a classic `ASP developer` about once a year since `ASP.NET` came out I decide I really gotta buckle down and learn this fancy new `ASP.NET`. A few days in and messing with code-behinds and webforms and all this other stuff. I decide the new fancy stuff is whack and go find something else to learn (`PHP and Ruby and Python were all fun to play with but I couldn't use it much with my existing ASP stuff`). Anyway, one project came up and I was able to use `PHP` and `CakePHP` and after getting my head around MVC I finally found something I liked and felt it was worth using over ASP (`PHP is cool too but it feels a lot like` ASP `so maybe that's why I like it so much`). But now with Jeff and the SO team raving about `ASP.NET MVC`, I think it's about time I start messing with `ASP.NET` again but **I keep thinking that PHP is free and blah blah blah . . . is `ASP.NET MVC` that much better than PHP with tools like CakePHP?** I know about compiled vs. not compiled and speed issues but most of that seems like a non-issue when you factor in all the caching and the fact that you can compile your PHP if you want.
For a classic ASP developer moving to ASP.NET MVC you are looking at learning a new language (C# or VB.NET), a new database layer (ADO.NET), and a new framework (ASP.NET MVC). That's a lot of new technologies to wrap your head around all at once. Also, I don't think it is so much that ASP.NET MVC is so much better than CakePHP (or Code Igniter, Ruby on Rails, etc.) The great thing about ASP.NET MVC (and other ASP.NET-based technologies such as MonoRail <http://www.castleproject.org/monorail/index.html>) is that developers who are using ASP.NET now have the option of following the MVC pattern using tools and languages they are familiar with. That is an option that wasn't available before.
Not too experienced with Microsoft's web stack, so I can't speak to that. But I will say I as a web developer I was pretty disappointed by CakePHP. What especially bothers me about it is that because it forces itself to be backward compatible with PHP4, therefore, it lacks much of the oop design and structure I am used to. Everything ends up being array based instead of the state in an object. Personally, after spending some time with cake and being disappointed, I decided to suck it up and learn Ruby on Rails, which I am doing now. If you wanted to stay with PHP I would look at Symfony, but they are all really heavily inspired by rails.
How do the CakePHP and codeigniter frameworks compare to the ASP.NET MVC framework?
[ "", "php", "asp.net-mvc", "cakephp", "asp-classic", "" ]
We have our own ORM we use here, and provide strongly typed wrappers for all of our db tables. We also allow weakly typed ad-hoc SQL to be executed, but these queries still go through the same class for getting values out of a data reader. In tweaking that class to work with Oracle, we've come across an interesting question. Is it better to use DBNull.Value, or null? Are there any benefits to using DBNull.Value? It seems more "correct" to use null, since we've separated ourselves from the DB world, but there are implications (you can't just blindly `ToString()` when a value is null for example) so its definitely something we need to make a conscious decision about.
I find it better to use null, instead of DB null. The reason is because, as you said, you're separating yourself from the DB world. It is generally good practice to check reference types to ensure they aren't null anyway. You're going to be checking for null for things other than DB data, and I find it is best to keep consistency across the system, and use null, not `DBNull`. In the long run, architecturally I find it to be the better solution.
If you've written your own ORM, then I would say just use null, since you can use it however you want. I believe DBNull was originally used only to get around the fact that value types (int, DateTime, etc.) could not *be* null, so rather than return some value like zero or DateTime.Min, which would *imply* a null (bad, bad), they created DBNull to indicate this. Maybe there was more to it, but I always assumed that was the reason. However, now that we have nullable types in C# 3.0, DBNull is no longer necessary. In fact, LINQ to SQL just uses null all over the place. No problem at all. Embrace the future... use null. ;-)
C# Database Access: DBNull vs null
[ "", "c#", "orm", "null", "dbnull", "" ]
I understand how JS is run and I think I understand most of the DOM but I've no idea about animation. Does anybody here know of a good guide that can explain to me how it's done in Javascript? In addition, should I even consider Javascript for animation? Should I instead be looking to learn flash?
Avoid flash, its a horrible requirement, uncrawlable by Google, unsopported by a bunch of browsers and systems (eg iPhone) and most importantly: it forces you to reinvent web standards (e.g. scroll bars and whatnot), Javascript on the other hand is easier to maintain and code for in the noscript case. try [scriptaculous](http://script.aculo.us/) for your animations; * [here's a quickie 3-line tutorial so you can see it working](http://woork.blogspot.com/2008/01/toggle-effect-using-scriptaculous.html) * [here's a more complete tutorial](http://www.tutorialspoint.com/script.aculo.us/index.htm) * [here's the scriptaculous wiki](http://github.com/madrobby/scriptaculous/wikis) note that there are a gazillion JS animation libraries, some really good [jQuery](http://jquery.com/) comes to mind. Usually they're just a script tag and an onclick event to setup. Good luck! /mp
if your animation is simple, change colors over time, move from x to y in 3 seconds. Javascript is fine. If you want all kinds of wizbang buttons and coordinated rotation of the screen, straight up js + dhtml will be clunky at best. Silverlight vs Flash are you questions at that point. Interestingly enough, you program Silverlight with javascript, and that would be the major benefit to simply upgrading to a faster and more dynamic DOM that is implemented in Silverlight but still writing the same code. Flash programmability is very limited in my experience, you can do anything, but it will be slow and take thousands of lines of code to get there. For simple JS animations look at jQuery or Scriptaculous.
Animation in javascript, a starting point
[ "", "javascript", "animation", "" ]
Trying to keep all the presentation stuff in the xhtml on this project and I need to format some values in a selectItem tag have a BigDecimal value and need to make it look like currency. Is there anyway to apply a `<f:convertNumber pattern="$#,##0.00"/>` Inside a `<f:selectItem>` tag? Any way to do this or a work around that doesn't involve pushing this into the java code?
After doing some more research here I'm pretty convinced this isn't possible with the current implementation of JSF. There just isn't an opportunity to transform the value. <http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/f/selectItem.html> The tld shows the `itemLabel` property as being a `ValueExpression` and the body content of `<f:selectItem>` as being empty. So nothing is allowed to exist inside one of these tags, and the label has to point to a verbatim value in the Java model. So it has be be formatted coming out of the Java model.
being a beginner to jsf i had a similar problem, maybe my solution is helpful, maybe its not in the "jsf spirit" i just created a custom taglib and extended the class (in my case org.apache.myfaces.component.html.ext.HtmlCommandButton) and overrided the setters to apply custom parameters. so instead of `<t:commandButton/>` i used `<mytags:commandButton/>`, which is as flexible as i want.
JSF selectItem label formatting
[ "", "java", "jsf", "" ]
Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?
A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This would mean retrieving the pointer and calling a function or jumping to the machine code depending on the type of table used. The benefits of doing this in embedded programming are: 1. Indexes are more memory efficient than machine code or pointers, so there is a potential for memory savings in constrained environments. 2. For any particular function the index will remain stable and changing the function merely requires swapping out the function pointer. If does cost you a tiny bit of performance for accessing the table, but this is no worse than any other virtual function call.
A jump table, also known as a branch table, is a series of instructions, all unconditionally branching to another point in code. You can think of them as a switch (or select) statement where all the cases are filled: ``` MyJump(int c) { switch(state) { case 0: goto func0label; case 1: goto func1label; case 2: goto func2label; } } ``` Note that there's no return - the code that it jumps to will execute the return, and it will jump back to wherever myjump was called. This is useful for state machines where you execute certain code based on the state variable. There are many, many other uses, but this is one of the main uses. It's used where you don't want to waste time fiddling with the stack, and want to save code space. It is especially of use in interrupt handlers where speed is extremely important, and the peripheral that caused the interrupt is only known by a single variable. This is similar to the vector table in processors with interrupt controllers. One use would be taking a $0.60 microcontroller and generating a composite (TV) signal for video applications. the micro isn't powerful - in fact it's just barely fast enough to write each scan line. A jump table would be used to draw characters, because it would take too long to load a bitmap from memory, and use a for() loop to shove the bitmap out. Instead there's a separate jump to the letter and scan line, and then 8 or so instructions that actually write the data directly to the port. -Adam
What is a jump table?
[ "", "c++", "c", "memory", "embedded", "" ]
I'm trying to rebuild an old metronome application that was originally written using `MFC` in C++ to be written in `.NET` using `C#`. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks". I've found a few articles online about playing `MIDI` in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it *should* be a mostly trivial exercise. So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application?
I think you'll need to p/invoke out to the windows api to be able to play midi files from .net. This codeproject article does a good job on explaining how to do this: [vb.net article to play midi files](http://www.codeproject.com/KB/audio-video/vbnetSoundClass.aspx) To rewrite this is c# you'd need the following import statement for mciSendString: ``` [DllImport("winmm.dll")] static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback); ``` Hope this helps - good luck!
I'm working on a C# MIDI application at the moment, and the others are right - you need to use p/invoke for this. I'm rolling my own as that seemed more appropriate for the application (I only need a small subset of MIDI functionality), but for your purposes the [C# MIDI Toolkit](http://www.codeproject.com/KB/audio-video/MIDIToolkit.aspx) might be a better fit. It is at least the best .NET MIDI library I found, and I searched extensively before starting the project.
Best way to play MIDI sounds using C#
[ "", "c#", ".net", "midi", "" ]
What's the best way to make a linked list in Java?
The obvious solution to developers familiar to Java is to use the **LinkedList** class already provided in **java.util**. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. **Enhancements** to this implementation include making it a **double-linked list**, adding methods to **insert** and **delete** from the middle or end, and by adding **get** and **sort** methods as well. **Note**: In the example, the Link object doesn't actually contain another Link object - *nextLink* is actually only a reference to another link. ``` class Link { public int data1; public double data2; public Link nextLink; //Link constructor public Link(int d1, double d2) { data1 = d1; data2 = d2; } //Print Link data public void printLink() { System.out.print("{" + data1 + ", " + data2 + "} "); } } class LinkList { private Link first; //LinkList constructor public LinkList() { first = null; } //Returns true if list is empty public boolean isEmpty() { return first == null; } //Inserts a new Link at the first of the list public void insert(int d1, double d2) { Link link = new Link(d1, d2); link.nextLink = first; first = link; } //Deletes the link at the first of the list public Link delete() { Link temp = first; if(first == null){ return null; //throw new NoSuchElementException(); // this is the better way. } first = first.nextLink; return temp; } //Prints list data public void printList() { Link currentLink = first; System.out.print("List: "); while(currentLink != null) { currentLink.printLink(); currentLink = currentLink.nextLink; } System.out.println(""); } } class LinkListTest { public static void main(String[] args) { LinkList list = new LinkList(); list.insert(1, 1.01); list.insert(2, 2.02); list.insert(3, 3.03); list.insert(4, 4.04); list.insert(5, 5.05); list.printList(); while(!list.isEmpty()) { Link deletedLink = list.delete(); System.out.print("deleted: "); deletedLink.printLink(); System.out.println(""); } list.printList(); } } ```
Java has a [LinkedList](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html) implementation, that you might wanna check out. You can download the JDK and it's sources at [java.sun.com](http://java.sun.com/javase/downloads/index.jsp).
How do I create a Linked List Data Structure in Java?
[ "", "java", "data-structures", "linked-list", "" ]
I am using [js2-mode](http://code.google.com/p/js2-mode/) to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.
Do you have ``` (setq-default indent-tabs-mode nil) ``` in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.
Add this to your `.emacs` file somewhere after you load js2 mode: ``` (setq js2-mode-hook '(lambda () (progn (set-variable 'indent-tabs-mode nil)))) ```
How do I get js2-mode to use spaces instead of tabs in Emacs?
[ "", "javascript", "emacs", "ide", "js2-mode", "" ]
I'm writing a wizard for an Eclipse RCP application. After doing some processing on a file and taking some user input, I don't want to let the user go back to make changes. At this point they must either accept or reject the changes they are about to make to the system. What I can't seem to find is a method call that lets me override the buttons that display or the user's ability to hit the back button. I'd prefer that it not be there or at least be disabled. Has anyone found a way to do this using the [JFace Wizard](http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/wizard/package-summary.html) and [WizardPage](http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/wizard/package-summary.html)? Usability-wise, am I breaking wizard conventions? Should I consider a different approach to the problem?
You can return null from the getPreviousPage() method in your wizard page implementation.
Expanding on jodonell's answer: Disabling the back button is harder than it should be, due to non-intuitive behavior in the default implementation of WizardPage.getPreviousPage(). You can call setPreviousPage( null ), and getPreviousPage() still returns the previous page. You need to override the implementation of getPreviousPage() in order to disable the back button: ``` public abstract class MyWizardPage extends WizardPage { private boolean backButtonEnabled = true; public void setBackButtonEnabled(boolean enabled) { backButtonEnabled = enabled; getContainer().updateButtons(); } @Override public IWizardPage getPreviousPage() { if (!backButtonEnabled) { return null; } return super.getPreviousPage(); } } ``` See my blog post for a few more JFace wizard tips and tricks: <http://nsawadsky.blogspot.com/2011/07/jface-wizard-tips-and-tricks.html>
Can you disable the back button in a JFace wizard?
[ "", "java", "eclipse", "rcp", "jface", "wizard", "" ]
I was wondering if anyone that has experience in both this stuff can shed some light on the *significant* difference between the two if any? Any specific strength of each that makes it suitable for any specific case?
This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions. I'm ***really really*** baffled that SimpleTest **still** is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen: * PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit). * PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely. * Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else. * PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports. * Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously). * PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests. * (Subjective) [PHPUnit provides much nicer](http://www.phpunit.de/manual/3.6/en/code-coverage-analysis.html) code coverage reports [than Simpletest](http://www.simpletest.org/en/reporter_documentation.html) * With PHPUnit you also get these reports inside your IDE ([Netbeans](http://netbeans.org/kb/docs/php/phpunit.htm%60), Eclipse, ...) * Also there are a couple of suggestings for a [**`web interface to phpunit tests`**](https://stackoverflow.com/questions/2424457/web-interface-to-phpunit-tests). I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear: ``` pear channel-discover pear.phpunit.de pear install phpunit/PHPUnit ``` and the "first test" looks pretty much the same. As of `PHPUnit 3.7` it's **even easier to install** it by just using the [**`PHAR Archive`**](http://www.phpunit.de/manual/current/en/installation.html#installation.phar) ``` wget http://pear.phpunit.de/get/phpunit.phar chmod +x phpunit-3.7.6.phar ``` or for windows just [downloading](http://pear.phpunit.de/get/phpunit.phar) the phar and running: ``` php phpunit-.phar ``` or when using the [supported composer install](http://www.phpunit.de/manual/current/en/installation.html#installation.composer) ways like ``` "require-dev": { "phpunit/phpunit": "3.7.*" } ``` to your composer.json. --- For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) ) Please correct me if I've stated something wrong or forgot something :) # Overview of PHP Testing tools Video: <http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/> Slides: <http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011> It mentions stuff like [Atoum](https://github.com/mageekguy/atoum) which calls its self: "A simple, modern and intuitive unit testing framework for PHP!" --- ### Full disclosure I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit.
I prefer PHPUnit now, but when I started out I used SimpleTest as I didn't always have access to the command line. SimpleTest is nice, but the only thing it really has over PHPUnit, in my opinion, is the web runner. The reasons I like PHPUnit are that it integrates with other PHP developer tools such as [phing](http://phing.info "Phing") (as does SimpleTest), [phpUnderControl](http://www.phpundercontrol.org/about.html "phpUnderControl"), and [Xinc](http://code.google.com/p/xinc/ "Xinc"). As of version 3.0 it [has mocking](http://www.phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects "PHPUnit Mock Objects") support, is being actively developed, and the documentation is excellent. Really the only way to answer this question for yourself is to try both out for a time, and see which fits your style better. EDIT: Phing now integrates with SimpleTest as well.
SimpleTest vs PHPunit
[ "", "php", "unit-testing", "phpunit", "simpletest", "" ]
How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. **Using the Constructor:** ``` class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; } } ``` **Using normal property syntax** (with an initial value) ``` private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } } ``` Is there a better way?
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor. Since [C# 6.0](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-60), you can specify initial value in-line. The syntax is: ``` public int X { get; set; } = x; // C# 6 or higher ``` [`DefaultValueAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8) is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value). At compile time `DefaultValueAttribute` will not impact the generated IL and it will not be read to initialize the property to that value (see [DefaultValue attribute is not working with my Auto Property](https://stackoverflow.com/questions/1980520/defaultvalue-attribute-is-not-working-with-my-auto-property)). Example of attributes that impact the IL are [`ThreadStaticAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8), [`CallerMemberNameAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8), ...
**C# 6** : With C# 6 you can initialize auto-properties directly (finally!), there are now other answers that describe that. **C# 5 and below**: Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway... ``` public class DefaultValuesTest { public DefaultValuesTest() { foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this)) { DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)]; if (myAttribute != null) { property.SetValue(this, myAttribute.Value); } } } public void DoTest() { var db = DefaultValueBool; var ds = DefaultValueString; var di = DefaultValueInt; } [System.ComponentModel.DefaultValue(true)] public bool DefaultValueBool { get; set; } [System.ComponentModel.DefaultValue("Good")] public string DefaultValueString { get; set; } [System.ComponentModel.DefaultValue(27)] public int DefaultValueInt { get; set; } } ```
What is the best way to give a C# auto-property an initial value?
[ "", "c#", "constructor", "getter", "setter", "automatic-properties", "" ]
This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is `org.eclipse.core.resources`. I want to get an `IFile` corresponding to a location `String` I have: ``` "platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl" ``` I have the enclosing `IWorkspace` and `IWorkspaceRoot`. If I had the `IPath` corresponding to the location above, I could simply call `IWorkspaceRoot.getFileForLocation(IPath)`. How do I get the corresponding `IPath` from the location `String`? Or is there some other way to get the corresponding `IFile`?
org.eclipse.core.runtime.Path implements IPath. ``` IPath p = new Path(locationString); IWorkspaceRoot.getFileForLocation(p); ``` This would have worked had the location string not been a URL of type "platform:" For this particular case, notes in org.eclipse.core.runtime.Platform javadoc indicate that the "correct" solution is something like ``` fileUrl = FileLocator.toFileURL(new URL(locationString)); IWorkspaceRoot.getFileForLocation(fileUrl.getPath()); ``` @[Paul Reiners] your solution apparently assumes that the workspace root is going to be in the "resources" folder
``` String platformLocationString = portTypeContainer .getLocation(); String locationString = platformLocationString .substring("platform:/resource/".length()); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot workspaceRoot = workspace.getRoot(); IFile wSDLFile = (IFile) workspaceRoot .findMember(locationString); ```
Get IFile from IWorkspaceRoot and location String
[ "", "java", "eclipse", "" ]
Some Eclipse plugins are mandated by your environment. The appropriate source code management plugin, for example - and I'm not interested in those. Some provide useful enhancements, but in a specific niche. I'm not interested in those. Some are great, but cost money. I'm not interested in those. Some were really useful on older versions of Eclipse, but are now part of the core build of the latest Eclipse version (3.4 as I write this). I'm not interested in those. I want advice on which plugins every Java SE developer should be installing, one per answer please.
Findbugs saved me doing something silly twice today. <http://findbugs.sourceforge.net/> Eclipse update site is: <http://findbugs.cs.umd.edu/eclipse/>
Answering my own question with my current favourite, Jadclipse, which works with jad to disassemble class files from third party libraries. <http://jadclipse.sourceforge.net/>
What is the single best free Eclipse plugin for a Java developer
[ "", "java", "ide", "eclipse-plugin", "" ]
I am looking for an efficient way to pull the data I want out of an array called $submission\_info so I can easily auto-fill my form fields. The array size is about 120. I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**. ``` Output of Print_r($submission_info[1]): Array ( [field_id] => 2399 [form_id] => 4 [field_name] => loanOfficer [field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ [field_size] => medium [field_type] => other [data_type] => string [field_title] => LoanOfficer [col_name] => loanOfficer [list_order] => 2 [admin_display] => yes [is_sortable] => yes [include_on_redirect] => yes [option_orientation] => vertical [file_upload_dir] => [file_upload_url] => [file_upload_max_size] => 1000000 [file_upload_types] => [content] => John Doe ) ``` I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**.
You're probably best off going through each entry and creating a new associative array out of it. ``` foreach($submission_info as $elem) { $newarray[$elem["field_name"]] = $elem["content"]; } ``` Then you can just find the form fields by getting the value from $newarray[*<field you're filling in>*]. Otherwise, you're going to have to search $submission\_info each time for the correct field.
Not sure if this is the optimal solution: ``` foreach($submission_info as $info){ if($info['field_name'] == 'loanOfficer'){ //check the field name $content = $info['content']; //store the desired value continue; //this will stop the loop after the desired item is found } } ``` Next time: Questions are more helpful to you and others if you generalize them such that they cover some overarching topic that you and maybe others don't understand. Seems like you could use an array refresher course...
How do I efficiently search an array to fill in form fields?
[ "", "php", "arrays", "" ]
I currently use the following function to do a simple HTTP GET. ``` public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n >= 0) { n = r.read(buffer, 0, buffer.length); if (n > 0) { content.append(buffer, 0, n); } } } finally { //if (b != null) b.close(); if (r != null) r.close(); if (s != null) s.close(); } return content.toString(); } ``` I see no reason to use the `BufferedReader` since I am just going to download everything in sequence. Am I right in thinking there is no use for the `BufferedReader` in this case?
In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers). There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until *flush()* is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using *mark(int)* and *reset()*. For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to. Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks: ``` InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } ``` If you are opening multiple streams, nest try/finally blocks. Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).
You are correct, if you use BufferedReader for reading HTTP content and headers you will want InputStreamReader so you can read byte for byte. BufferedReader in this scenario sometimes does weird things...escpecially when it comes to reading HTTP POST headers, sometimes you will be unable to read the POST data, if you use the InputStreamReader you can read the content length and read that many bytes...
Is there a reason to use BufferedReader over InputStreamReader when reading all characters?
[ "", "java", "performance", "http", "io", "buffer", "" ]
I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: ``` System.getProperty(current.user); ``` But, I'm not quite sure.
You're actually really close. This is what you're looking for: ``` System.getProperty("user.name") ```
The commonly available system properties are documented in the [`System.getProperties()`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29) method. As Chris said `"user.name"` is the property to get the user running your app.
Java: Programatic Way to Determine Current Windows User
[ "", "java", "windows", "" ]
I am reviewing a big java application to see if there are any performance bottlenecks. The real problem is that I cannot pinpoint the performance issues to any single module. The whole application is slow as such. Is there some tool/technique I can use to help me out in this?
Try using a profiler on your running code. It should help you identify the bottlenecks. Try [jprofiler](http://www.ej-technologies.com/products/jprofiler/overview.html) or [Netbeans profiler](http://www.netbeans.org/features/java/profiler.html)
I'm often happy enough using `Java -Xprof`. This gives you a sorted list of the functions your code spends most of its time in.
How to test java application for performance bottlenecks?
[ "", "java", "performance", "" ]
I'm new to NHibernate (my 1st big project with it). I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block. This doesn't work in a situation where lazy-loading is required, however. For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception. Anyone using a different method?
Session management: <http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/HybridSessionBuilder.cs> Session per request: <http://code.google.com/p/dot-net-reference-app/source/browse/trunk/src/Infrastructure/Impl/NHibernateSessionModule.cs>
check out the [SummerOfNHibernate](http://www.SummerOfNHibernate.com) webcasts for a great tutorial... What you're looking for specifically doesn't come until webisode 5 or 6.
Best way to manage session in NHibernate?
[ "", "c#", ".net", "nhibernate", "" ]
I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map. In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses. In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?
Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles. ``` function GetCenterLatLong() { //Check if in Birdseye or Oblique Map Style if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) { //IN Birdseye or Oblique Map Style //Get the BirdseyeScene being displayed var birdseyeScene = map.GetBirdseyeScene(); //Get approximate center coordinate of the map var x = birdseyeScene.GetWidth() / 2; var y = birdseyeScene.GetHeight() / 2; // Get the Lat/Long var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel()); // Convert the BirdseyeScene LatLong to a normal LatLong we can use return (new _xy1).Decode(center); } else { // NOT in Birdseye or Oblique Map Style return map.GetCenter(); } } ``` This code was copied from here: <http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx>
It always seems to me that the example solutions for this issue only find the centre of the current map on the screen, as if that is always the place you're going to click! Anyway, I wrote this little function to get the actual pixel location that you clicked on the screen and return a VELatLong for that. So far it seems pretty accurate (even though I see this as one big, horrible hack - but it's not like we have a choice at the moment). It takes a VEPixel as input, which is the x and y coordinates of where you clicked on the map. You can get that easily enough on the mouse event passed to the onclick handler for the map. ``` function getBirdseyeViewLatLong(vePixel) { var be = map.GetBirdseyeScene(); var centrePixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel()); var currentPixelWidth = be.GetWidth(); var currentPixelHeight = be.GetHeight(); var mapDiv = document.getElementById("map"); var mapDivPixelWidth = mapDiv.offsetWidth; var mapDivPixelHeight = mapDiv.offsetHeight; var xScreenPixel = centrePixel.x - (mapDivPixelWidth / 2) + vePixel.x; var yScreenPixel = centrePixel.y - (mapDivPixelHeight / 2) + vePixel.y; var position = be.PixelToLatLong(new VEPixel(xScreenPixel, yScreenPixel), map.GetZoomLevel()) return (new _xy1).Decode(position); } ```
How do I find the the exact lat/lng coordinates of a birdseye scene in Virtual Earth?
[ "", "javascript", "virtual-earth", "" ]
I want to create a Java program that can be extended with plugins. How can I do that and where should I look for? I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow. --- Although I do like Eclipse RCP, I think it's too much for my simple needs. Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it. But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.
I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java [ClassLoader](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html) to load those classes and create instances of them. One way you can go about it is this: ``` File dir = new File("put path to classes you want to load here"); URL loadPath = dir.toURI().toURL(); URL[] classUrl = new URL[]{loadPath}; ClassLoader cl = new URLClassLoader(classUrl); Class loadedClass = cl.loadClass("classname"); // must be in package.class name format ``` That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule: ``` MyModule modInstance = (MyModule)loadedClass.newInstance(); ```
Look into [OSGi](http://www.osgi.org). On one hand, OSGi provides all sorts of infrastructure for managing, starting, and doing lots of other things with modular software components. On the other hand, it could be too heavy-weight for your needs. Incidentally, Eclipse uses OSGi to manage its plugins.
How to create a pluginable Java program?
[ "", "java", "plugins", "plugin-architecture", "" ]
On my side job as programmer, I am to write a program in C++ to convert audio files from/to various formats. Probably, this will involve building a simple GUI. Will it be a great effort to build seperate GUIs for Mac and Windows using Cocoa and WinForms instead of a cross-platform toolkit like Qt or GTK? (I will have to maintain a seperate Windows-version and Mac-Version anyway) The GUI will probably be very simple and only need very basic functionality. I always felt that native GUIs feel far more intuitive than its cross-platform brethren...
If you have the expertise, use native frontends, it'll effectively double the job you have to do for UI but from my experience non-native UI is a little bit clunkier than their native counterparts.
Have you looked at [wxWidgets](http://www.wxwidgets.org/)? Cross platform native controls.
Should I use a cross-platform GUI-toolkit or rely on the native ones?
[ "", "c++", "user-interface", "cross-platform", "" ]
In [another question](https://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how "Python scripts as Windows service") I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?
As with most "aware" things in Windows, the answer is "Registry". Take a look at this Microsoft Knowledge Base article: <http://support.microsoft.com/kb/103000> Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in. The service registration (contents of KEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as. As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you.
Don't muck with the registry directly. User the SC command-line tool. Namely, SC CREATE ``` DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ... The option has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService ```
How do I make Windows aware of a service I have written in Python?
[ "", "python", "windows", "cross-platform", "" ]
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? ``` const int FIZZ = 6; for(int x = 0; x < MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } ``` vs: The way I am currently doing it: ``` const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x < MAXCOUNT; x++) { if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; } } ```
Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder. Still, there is a small branch of number theory devoted to [Modular Arithmetic](http://en.wikibooks.org/wiki/Discrete_mathematics/Modular_arithmetic) which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating [magic squares](http://www.math.utah.edu/~carlson/mathcircles/magic.pdf). So, in that vein, here's a [very low level look](http://piclist.org/techref/postbot.asp?by=time&id=piclist/2006/08/03/065022a) at the math of modulus for an example of x, which should show you how simple it can be compared to division: --- Maybe a better way to think about the problem is in terms of number bases and modulo arithmetic. For example, your goal is to compute DOW mod 7 where DOW is the 16-bit representation of the day of the week. You can write this as: ``` DOW = DOW_HI*256 + DOW_LO DOW%7 = (DOW_HI*256 + DOW_LO) % 7 = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7 = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7 = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7 ``` Expressed in this manner, you can separately compute the modulo 7 result for the high and low bytes. Multiply the result for the high by 4 and add it to the low and then finally compute result modulo 7. Computing the mod 7 result of an 8-bit number can be performed in a similar fashion. You can write an 8-bit number in octal like so: ``` X = a*64 + b*8 + c ``` Where a, b, and c are 3-bit numbers. ``` X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7 = (a%7 + b%7 + c%7) % 7 = (a + b + c) % 7 ``` since `64%7 = 8%7 = 1` Of course, a, b, and c are ``` c = X & 7 b = (X>>3) & 7 a = (X>>6) & 7 // (actually, a is only 2-bits). ``` The largest possible value for `a+b+c` is `7+7+3 = 17`. So, you'll need one more octal step. The complete (untested) C version could be written like: ``` unsigned char Mod7Byte(unsigned char X) { X = (X&7) + ((X>>3)&7) + (X>>6); X = (X&7) + (X>>3); return X==7 ? 0 : X; } ``` I spent a few moments writing a PIC version. The actual implementation is slightly different than described above ``` Mod7Byte: movwf temp1 ; andlw 7 ;W=c movwf temp2 ;temp2=c rlncf temp1,F ; swapf temp1,W ;W= a*8+b andlw 0x1F addwf temp2,W ;W= a*8+b+c movwf temp2 ;temp2 is now a 6-bit number andlw 0x38 ;get the high 3 bits == a' xorwf temp2,F ;temp2 now has the 3 low bits == b' rlncf WREG,F ;shift the high bits right 4 swapf WREG,F ; addwf temp2,W ;W = a' + b' ; at this point, W is between 0 and 10 addlw -7 bc Mod7Byte_L2 Mod7Byte_L1: addlw 7 Mod7Byte_L2: return ``` Here's a liitle routine to test the algorithm ``` clrf x clrf count TestLoop: movf x,W RCALL Mod7Byte cpfseq count bra fail incf count,W xorlw 7 skpz xorlw 7 movwf count incfsz x,F bra TestLoop passed: ``` Finally, for the 16-bit result (which I have not tested), you could write: ``` uint16 Mod7Word(uint16 X) { return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4); } ``` Scott ---
If you are calculating a number mod some power of two, you can use the bit-wise and operator. Just subtract one from the second number. For example: ``` x % 8 == x & 7 x % 256 == x & 255 ``` A few caveats: 1. This **only works** if the second number is a power of two. 2. It's only equivalent if the modulus is always positive. The C and C++ standards don't specify the sign of the modulus when the first number is negative (until C++11, which *does* guarantee it will be negative, which is what most compilers were already doing). A bit-wise and gets rid of the sign bit, so it will always be positive (i.e. it's a true modulus, not a remainder). It sounds like that's what you want anyway though. 3. **Your compiler probably already does this when it can, so in most cases it's not worth doing it manually.**
Is there any alternative to using % (modulus) in C/C++?
[ "", "c++", "c", "modulo", "embedded", "" ]
We're currently using Lucene 2.1.0 for our site search and we've hit a difficult problem: one of our index fields is being ignored during a targeted search. Here is the code for adding the field to a document in our index: ``` // Add market_local to index contactDocument.add( new Field( "market_local" , StringUtils.objectToString( currClip.get( "market_local" ) ) , Field.Store.YES , Field.Index.UN_TOKENIZED ) ); ``` Running a query ( \* ) against the index will return the following results: ``` Result 1: title: Foo Bar market_local: Local Result 2: title: Bar Foo market_local: National ``` Running a targeted query: ``` +( market_local:Local ) ``` won't find any results. I realize this is a highly specific question, I'm just trying to get information on where to start debugging this issue, as I'm a Lucene newbie. --- **UPDATE** Installed Luke, checking out latest index... the Field *market\_local* is available in searches, so if I execute something like: ``` market_local:Local ``` The search works correctly (in Luke). I'm going over our Analyzer code now, is there any way I could chalk this issue up to the fact that our search application is using Lucene 2.1.0 and the latest version of Luke is using 2.3.0?
For debugging Lucene, the best tool to use is [Luke](http://www.getopt.org/luke/), which lets you poke around in the index itself to see what got indexed, carry out searches, etc. I recommend downloading it, pointing it at your index, and seeing what's in there.
The [section on "Why am I getting no hits?"](http://wiki.apache.org/lucene-java/LuceneFAQ#head-3558e5121806fb4fce80fc022d889484a9248b71) in the Lucene FAQ has some suggestions you might find useful. You're using Field.Index.UN\_TOKENIZED, so no Analyzer will be used for indexing (I think). If you're using an Analyzer when you're searching then that might be the root of your problem - the indexing and searching Analyzers should be the same to make sure you get the right hits.
Troubleshoot Java Lucene ignoring Field
[ "", "java", "lucene", "" ]
We are producing a portable code (win+macOs) and we are looking at how to make the code more rubust as it crashes every so often... (overflows or bad initializations usually) :-( I was reading that Google Chrome uses a process for every tab so if something goes wrong then the program does not crash compleatelly, only that tab. I think that is quite neat, so i might give it a go! So i was wondering if someone has some tips, help, reading list, comment, or something that can help me build more rubust c++ code (portable is always better). In the same topic i was also wondering if there is a portable library for processes (like boost)? Well many Thanks.
I've developed on numerous multi-platform C++ apps (the largest being 1.5M lines of code and running on 7 platforms -- AIX, HP-UX PA-RISC, HP-UX Itanium, Solaris, Linux, Windows, OS X). You actually have two entirely different issues in your post. 1. Instability. Your code is not stable. Fix it. * Use unit tests to find logic problems before they kill you. * Use debuggers to find out what's causing the crashes if it's not obvious. * Use boost and similar libraries. In particular, the pointer types will help you avoid memory leaks. 2. Cross-platform coding. * Again, use libraries that are designed for this when possible. Particularly for any GUI bits. * Use standards (e.g. ANSI vs gcc/MSVC, POSIX threads vs Unix-specific thread models, etc) as much as possible, even if it requires a bit more work. Minimizing your platform specific code means less overall work, and fewer APIs to learn. * Isolate, isolate, isolate. Avoid in-line #ifdefs for different platforms as much as possible. Instead, stick platform specific code into its own header/source/class and use your build system and #includes to get the right code. This helps keep the code clean and readable. * Use the C99 integer types if at all possible instead of "long", "int", "short", etc -- otherwise it will bite you when you move from a 32-bit platform to a 64-bit one and longs suddenly change from 4 bytes to 8 bytes. And if that's ever written to the network/disk/etc then you'll run into incompatibility between platforms. Personally, I'd stabilize the code first (without adding any more features) and then deal with the cross-platform issues, but that's up to you. Note that Visual Studio has an excellent debugger (the code base mentioned above was ported to Windows just for that reason).
The Chrome answer is more about failure mitigation and not about code quality. Doing what Chrome is doing is admitting defeat. 1. Better QA that is more than just programmer testing their own work. 2. Unit testing 3. Regression testing 4. Read up on best practices that other companies use. To be blunt, if your software is crashing often due to overflows and bad initializations, then you have a very basic programming quality problem that isn't going to be easily fixed. That sounds a hash and mean, that isn't my intent. My point is that the problem with the bad code has to be your primary concern (which I'm sure it is). Things like Chrome or liberal use to exception handling to catch program flaw are only distracting you from the real problem.
Super Robust as chrome c++ and portable - tips - help - comments
[ "", "c++", "boost", "google-chrome", "portability", "robust", "" ]
I have been using Castle MonoRail for the last two years, but in a new job I am going to be the one to bring in ASP.NET MVC with me. I understand the basics of views, actions and the like. I just need a good sample for someone with MVC experience. Any good links besides Scott's Northwind traders sample?
[CodeCampServer](http://code.google.com/p/codecampserver/) - Built with ASP.NET MVC, pretty light and small project. No cruft at all. @lomaxx - Just FYI, most of what Troy Goode wrote is now part of [ASP.NET MVC as of Preview 4](http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx).
[Rob Conery's MVC Storefront project](http://blog.wekeroad.com/mvc-storefront/) is a good from-the-ground-up step-by-step series on how to put up an ASP.NET MVC site.
Where can I find a good ASP.NET MVC sample?
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
Should I use Named Pipes, or .NET Remoting to communicate with a running process on my machine?
WCF is the best choice. It supports [a number of different transport mechanisms](https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms733769%28v=vs.85%29) ([including](https://web.archive.org/web/20121019154711/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/05/19/exploring-the-wcf-named-pipe-binding-part-1.aspx) [Named](https://web.archive.org/web/20110919020547/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/06/16/exploring-the-wcf-named-pipe-binding-part-2.aspx) [Pipes](https://web.archive.org/web/20131017152044/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/06/23/exploring-the-wcf-named-pipe-binding-part-3.aspx)) and can be completely configuration driven. I would highly recommend that you take a look at WCF. Here is a blog that does a [WCF vs Remoting performance comparison](https://web.archive.org/web/20201031045150/http://geekswithblogs.net/marcel/archive/2007/09/26/115651.aspx). A quote from the blog: > The WCF and .NET Remoting are really comparable in performance. The differences are so small (measuring client latency) that it does not matter which one is a bit faster. WCF though has much better server throughput than .NET Remoting. If I would start completely new project I would chose the WCF. Anyway the WCF does much more than Remoting and for all those features I love it. [MSDN Section for WCF](https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.5/ms735119%28v=vs.90%29)
If it's on a single machine, Named Pipes gives you better performance and can be implemented with the [remoting infrastructure](https://web.archive.org/web/20081023122612/http://ivanweb.com/articles/namedpipes/index.cfm) as well as WCF. Or you can just directly use [System.IO.Pipes](https://web.archive.org/web/20081028231548/http://bartdesmet.net/blogs/bart/archive/2007/04/12/getting-started-with-named-pipes.aspx).
What is the best choice for .NET inter-process communication?
[ "", "c#", ".net", "process", "ipc", "" ]