Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Currently my code is organized in the following tree structure: ``` src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py ``` Where the `module*.py` files contains the source...
If they all begin with `test` then just `nosetest` should work. Nose automatically searches for any files beginning with 'test'.
Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc). When you're using nosetests, make sure that all directories with tests are real packages: ``` src/ module1.py module2.py subpackage1/ ...
How to organize python test in a way that I can run all tests in a single command?
[ "", "python", "unit-testing", "python-nose", "" ]
What's the easiest way to truncate a C++ `float` variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?
First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable. But here are a couple of solutions to the problem that will probably meet your need: Probably the better method but less efficient: ``` char sz[64];...
A good reference for *why* this happens can be found in [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) by David Goldberg.
Truncate a decimal value in C++
[ "", "c++", "decimal", "truncate", "" ]
I've got a number of WebService methods that all include some very boilerplate code of wrapping the actual work in a try/catch/finally and performing the same tasks in the catch/finally. So as a way to encapsulate all of the shared catch/finally stuff I wrote a simple generic. This works and really eliminates a bunch ...
I would change ``` public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req) ``` to ``` public static T2 Invoke<T1, T2>( this T1 req, RestfulServiceRequest<T1, T2> serviceCall) ``` This will change the call to ``` public class Initialization :IInitialization { public Applianc...
One thing that will make it cleaner is to define interfaces that your request/response objects implement. Then you can get rid of the generics in favor of the interfaces. Note, too, the name change which I think is more descriptive of what you are really trying to do. ``` public interface IServiceResponse { ... } publ...
Using Generics to encapsulate common method work
[ "", "c#", "generics", "" ]
I'm using JQuery and Prototype in this web application that I'm developing. I'm looking for a way to use Lightbox v2.04 by Lokesh Dhakar to play flash movies. If its not possible using the Lightbox v2.04 then what other ways can I accomplish the shadowing overlayed flash video pop-up with jquery and/or Prototype? The r...
I've used [LightWindow](http://www.stickmanlabs.com/lightwindow/) to display arbitrary HTML before, but my experience shows flash and LightWindow don't mix that well. We had a FLV player in the background (not in the LightWindow), and LightWindow caused flicker in some browsers.
Another alternative is using JQuery's [Thickbox plugin](http://jquery.com/demo/thickbox/).
playing flash movies in lightbox
[ "", "javascript", "jquery", "flash", "prototype", "lightbox", "" ]
A simple stupid "`UPDATE table SET something=another WHERE (always true)`" in accident will easily destroy everything in the database. It could be a human mistake, an SQL injection/overflow/truncation attack, or a bug in the code who build the WHERE causes. Are popular databases provide a feature that protect tables b...
You can add a trigger that checks how many rows are being updated (count the Inserted magic trigger table), and RAISEERROR if that's too many rows.
I don't know of anything. I'm not sure that this would solve anything. How can the database distinguish between a SQL injection attack and a nightly batch update that happens to exceed your limit? One assumption is the auto commit is set to true. If the SQL injection attack isn't committed, you always have the opport...
Is it possible to prevent batch update at the sql database level?
[ "", "sql", "sql-server", "database", "security", "" ]
I have to choose a platform for our product. I have to decide between The Qt Framework and Adobe's AIR. I am well versed with Qt as I have worked for the last two years. I looked up at the Adobe's site but all the info about flex, flash, ability to coding in HTML/ActionScript is overwhelming and confusing. I cannot und...
If you needs to access a lot of native libraries, you'll need to stay within your QT environment. Keep in mind that AIR is single-threaded and is run on the Flash Player (something that was originally designed for frame-based animations.) However, depending on the style of application you're building, AIR might suit yo...
Go spend some time with this AIR application and then ask yourself if Adobe Flex and AIR are worth investing your time in mastering (be prepared to ask yourself why something comparable doesn't exist for the likes of C++/QT): [Tour de Flex](http://flex.org/tour) > Tour de Flex is a desktop application > for exploring...
C++/Qt vs Adobe AIR
[ "", "c++", "apache-flex", "qt", "air", "" ]
I've seen [Veloedit](http://veloedit.sourceforge.net/), which seems to have good syntax highlighting but doesn't allow tab characters in the file being edited (wtf?) and also has no understanding of HTML. With a little bit of googling I've found [Veloecipse](http://propsorter.sourceforge.net/), which claims to build u...
Here's an update: I've been using Veloeclipse and it works well, not sure what led to my original comment about not working with Eclipse 3.4 but I am definitely using it with 3.4 now. Veloeclipse works better than Veloedit and Velocity Web Editor, in my opinion.
I have installed Veloeclipse since Veloedit raised exceptions when opening the editor and it works fine with eclipse 3.5.2. In order to install it, I had to *de*select "Group items by category" in the "Install new software..." dialog.
Velocity editor plugin for Eclipse?
[ "", "java", "eclipse", "velocity", "" ]
I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.
``` /^[a-z0-9]+$/i ^ Start of string [a-z0-9] a or b or c or ... z or 0 or 1 or ... 9 + one or more times (change to * to allow empty string) $ end of string /i case-insensitive ``` **Update (supporting universal characters)** if you need to this regexp supports universal characte...
If you wanted to return a replaced result, then this would work: ``` var a = 'Test123*** TEST'; var b = a.replace(/[^a-z0-9]/gi, ''); console.log(b); ``` This would return: ``` Test123TEST ``` Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I h...
RegEx for Javascript to allow only alphanumeric
[ "", "javascript", "regex", "" ]
This is in reference to the [question](https://stackoverflow.com/questions/282944/jquery-one-slider-controls-another) previously asked The problem here is, each `slider` controls the other. It results in feedback. How do I possibly stop it? ``` $(function() { $("#slider").slider({ slide: moveSlider2 }); $("#...
This is sort of a hack, but works: ``` $(function () { var slider = $("#slider"); var slider1 = $("#slider1"); var sliderHandle = $("#slider").find('.ui-slider-handle'); var slider1Handle = $("#slider1").find('.ui-slider-handle'); slider.slider({ slide: moveSlider1 }); slider1.slider({ slide: ...
You could store a var CurrentSlider = 'slider'; on mousedown on either of the sliders, you set the CurrentSlider value to that slider, and in your moveSlider(...) method you check whether this is the CurrentSlider, if not, you don't propagate the sliding (avoiding the feedback)
jQuery-ui slider - How to stop two sliders from controlling each other
[ "", "javascript", "jquery", "jquery-ui", "slider", "jquery-ui-slider", "" ]
I am sending the echo to mail function via PHP from variable that includes HTML code. The strange thing is, that this ``` <����}im� ``` shows up AFTER the string.. but I do not manipulate with it anymore. The charset of mail function (the attachment) is same as charset of HTML code.
Encoding problem, maybe it tries to display binary code? You should use htmlentities if ou want to display HTML > // Outputs: A 'quote' is > > <b>bold</b> echo > > htmlentities($str);
You could consider using the [htmlMimeMail](http://www.phpguru.org/static/mime.mail.html) class for handling the email. So you can avoid the nasty email internals.
How do I get these strange characters when I try to "echo" the html string?
[ "", "php", "html", "echo", "character", "" ]
I have a problem that I would like have solved via a SQL query. This is going to be used as a PoC (proof of concept). The problem: Product offerings are made up of one or many product instances, a product instance can belong to many product offerings. This can be realised like this in a table: ``` PO | PI ----- A ...
Okay, I think I have it. This meets the constraints you provided. There might be a way to simplify this further, but it ate my brain a little: ``` select distinct PO from POPI x where PO not in ( select PO from POPI where PI not in (10,11,12) ) and PI not in ( select PI from POPI ...
**Edit:** Whilst I think mine works fine, Adam's answer is without a doubt more elegant and more efficient - I'll just leave mine here for posterity! Apologies since I know this has been tagged as an Oracle issue since I started playing. This is some SQL2008 code which I think works for all the stated cases.... ``` d...
Recursive sql problem
[ "", "sql", "" ]
Let's say we have ``` public interface ITimestampProvider { DateTime GetTimestamp(); } ``` and a class which consumes it ``` public class Timestamped { private ITimestampProvider _timestampProvider public Timestamped(ITimestampProvider timestampProvider) { // arg null check _timesta...
I think it depends on the scenario, and is basically a function of who the consumer the code is (library vs. application) and whether you're using an IoC container or not. * If you're using an IoC container, and this is not part of a public API, then let the container do the heavy lifting, and just have the single con...
i wouldn't provide that constructor. Doing so makes it far too easy to call new TimeStamped and get an instance with new SystemTimestampProvider() when your IoC may be configured to use OtherTimestampProvider(). End of the day you'll end up with one hell of a time trying to debug why you're getting the wrong timestamp...
Constructor injection and default overloads
[ "", "c#", ".net", "dependency-injection", "" ]
Button class: ``` class SubmitButton extends JButton implements ActionListener { public SubmitButton(String title){ super(title); .... ``` Where I declare it: ``` SubmitButton submit = new SubmitButton("Submit"); submit.setBounds(530+150, 200, 100, 25); ``` **How does super(title) set the String...
* SubmitButton extends JButton * JButton has a constructor which might look like this (simplified): ``` public JButton(String title) { setText(title); } ``` * SubmitBUtton has a constructor: ``` public SubmitButton(String title) { super(title); } ``` The SubmitButton constructor is callin...
JButton is a central Java Swing class that supports multiple constructors. One of these constructors allows you to set the text for the button label. Adding super(title) didn't actually make a call - the constructor of the parent would have been called anyway, but it helped select which constructor is invoked. The se...
super() function in JAVA
[ "", "java", "super", "" ]
If I have a form-backing object that has a complicated object tree -- say a Person that has a Contact Info object that has an Address object that has a bunch of Strings -- it seems that the object needs to be fully populated with component objects before I can bind to it. So if I'm creating a new Person, I need to make...
Call it overkill if you like, but what we actually ended up doing was to create a generic factory that will take any object and use reflection to (recursively) find all the null properties and instantiate an object of the correct type. I did this using Apache Commons BeanUtils. This way you can take an object that you...
I would generally make sure objects are fully initialized - it makes using the object that much simplier and avoids you scattering null checks throughout your code. In the case you give here I'd probably put the initialization in the getter so the child object is only instantiated when it's actually going to be used, ...
Best Practice for Spring MVC form-backing object tree initialization
[ "", "java", "spring", "spring-mvc", "" ]
From what I gather, Google Chrome can run browser plugins written using [NPAPI](http://en.wikipedia.org/wiki/NPAPI). I've written one that does its job just fine in Firefox, but makes Chrome crash and burn as soon as you embed it on a page. I don't even have to call any of my methods, embedding is enough to cause a cr...
As it turns out, part of the initialization code from the old NPAPI plugin example I was using caused the crash. I'm sorry to say I solved this quite a while back and can't seem to locate the specific modifications I made to fix it in the version control history. Anyway, my problem is fixed and was caused by me being s...
The Chromium dev docs describe some tricks for attaching Visual Studio to Chrome processes: [Chromium Developer Documentation > Debugging Chromium](http://dev.chromium.org/developers/how-tos/debugging). Some problems you might be facing with an NPAPI plugin in Chrome: * Your plugin will be running in a separate proce...
Firefox plugin crashes in Chrome
[ "", "c++", "google-chrome", "npapi", "" ]
In the unmanaged development world, you could observe the DWORD return value of a method by typing '@eax' into the watch window of the debugger. Does anyone know of an equivalent shortcut in managed code? Related point: I have learned that VS2008 SP1 supports **$exception** as a magic word in the watch window. Are th...
The watch window tricks like @eax are called [Psuedovariables]. They are actually [documented.](http://msdn.microsoft.com/en-us/library/ms164891(VS.80).aspx) I wrote a [blog post](http://blogs.msdn.com/stevejs/archive/2005/10/18/482300.aspx#comments) about this and some other VS debugging items a few years ago. Format ...
I'm not sure if this is quite what you mean, but there are some other keywords that you can have printed out for tracepoints: ``` $ADDRESS address of current instruction $CALLER name of the previous function on the call stack $CALLSTACK entire call stack $FUNCTION name of the current function...
Do you know a managed equivalent to '@eax'?
[ "", "c#", "visual-studio-2008", "debugging", "" ]
I want to write a program in C/C++ that will dynamically read a web page and extract information from it. As an example imagine if you wanted to write an application to follow and log an ebay auction. Is there an easy way to grab the web page? A library which provides this functionality? And is there an easy way to par...
Have a look at the [cURL library](http://curl.haxx.se/libcurl/c/example.html): ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se"); res = curl_easy_perform(curl); ...
Windows code: ``` #include <winsock2.h> #include <windows.h> #include <iostream> #pragma comment(lib,"ws2_32.lib") using namespace std; int main (){ WSADATA wsaData; if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { cout << "WSAStartup failed.\n"; system("pause"); return 1; } SOCK...
Programmatically reading a web page
[ "", "c++", "c", "http", "" ]
I am tasked with developing a web application and am thinking of using the Struts framework as it seems to be a standard and is easy to implement. However, before making a decision I need to know the security features available in Struts. Are there effective ways to handle the [OWASP Top 10](http://www.owasp.org/inde...
Struts is there to offer you an MVC framework, and it has limited security features, e.g. you can map roles to actions. I will recommend you to look into something more full-fledged like the [Spring Security](http://static.springframework.org/spring-security/site/) (formerly Acegi).
The best way to handle the OWASP Top ten in struts is to look at the OWASP Enterprise Security API...
What security features are available in Struts?
[ "", "java", "security", "struts", "owasp", "" ]
is there any support in Mac OS X for signing data using smartcards? I have looked through the system headers and found only vauge references to smart card support (in SecKeychain.h), which didn't really take me anywhere. If there's no built-in support, which are my options (ie. what free/non-free libraries exist that ...
I'm answering my own question here, for reference. The [OpenSC](http://www.opensc-project.org/) libraries provides everything you need to deal with smartcards, and it is cross-platform (Windows, Linux and Mac), and its license is good for commercial projects.
The [Apple-CDSA mailing list](http://lists.apple.com/mailman/listinfo/apple-cdsa "Apple-CDSA mailing list") is probably the best place to ask this; CDSA stands for Common Data Security Architecture, which includes all of the security/keychain/signing infrastructure on Mac OS X, including any support for smart-card secu...
Signing data with smartcards on Mac in C++
[ "", "c++", "macos", "cryptography", "smartcard", "" ]
Here's some code I saw once. Can you see what's wrong with it? [updated] ``` public class ResourceManager1 { private final String mutex = ""; Object resource = null; public Object getResource() { synchronized (mutex) { if (resource == null) { re...
Never synchronize on strings, particularly string literals which are interned. You've basically just got a single lock. In general, never synchronize on any reference that might be visible outside your class (including "this") *unless* the purpose of the external visibility is precisely for locking purposes. I usually...
You are using the same String as a mutex for both classes and hence only one of the synchronized blocks can be used at a time, which does not seem to be the intention of the code.
Java synchronisation poll
[ "", "java", "synchronization", "" ]
everybody; I have this problem in asp.net, I have a page where I insert and modify data, before saving I make a validation if it passes I save the data but if not I raise an exception and show it, the function goes like this; ``` protected void btnSave_Click(object sender, EventArgs e) { try { ... if(ValidData()) //...
If JSLiteral is a server side control and it's using view state. Then you'd need to clear the state of the control, when the save is succesful. You could disable the viewstate for the control like JSLiteral.EnableViewState =false;
Are you resetting the value of JSLiteral to empty after you save?
Annoying exception in asp.net
[ "", "c#", "asp.net", "" ]
With wxWidgets I use the following code: ``` HWND main_window = ... ... wxWindow *w = new wxWindow(); wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window); ``` How do I do the same thing in Qt? The `HWND` is the handle of the window I want as the parent window for the new QtWidget.
Use the create method of QWidget. ``` HWND main_window = ... ... QWidget *w = new QWidget(); w->create((WinId)main_window); ```
Have you tried the [`QWinWidget`](http://doc.qt.digia.com/solutions/qtwinmigrate/qwinwidget.html) class from the [Qt/MFC Migration Framework](http://doc.qt.digia.com/solutions/qtwinmigrate/)?
How to create a QWidget with a HWND as parent?
[ "", "c++", "windows", "qt", "wxwidgets", "" ]
I need a 'good' way to initialize the pseudo-random number generator in C++. I've found [an article](http://www.cplusplus.com/reference/clibrary/cstdlib/srand.html) that states: > In order to generate random-like > numbers, srand is usually initialized > to some distinctive value, like those > related with the executi...
The best answer is to use [`<random>`](http://en.cppreference.com/w/cpp/header/random). If you are using a pre C++11 version, you can look at the Boost random number stuff. But if we are talking about `rand()` and `srand()` The best simplest way is just to use `time()`: ``` int main() { srand(time(nullptr)); ...
This is what I've used for small command line programs that can be run frequently (multiple times a second): ``` unsigned long seed = mix(clock(), time(NULL), getpid()); ``` Where mix is: ``` // Robert Jenkins' 96 bit Mix Function unsigned long mix(unsigned long a, unsigned long b, unsigned long c) { a=a-b; a=a...
Recommended way to initialize srand?
[ "", "c++", "random", "srand", "" ]
Say I wanted to have a project, and one-to-many with to-do items, and wanted to re-order the to-do items arbitrarily? In the past, I've added a numbered order field, and when someone wants to change the order, had to update all the items with their new order numbers. This is probably the worst approach, since it's not...
I hate this problem ... and I run into it all the time. For my most recent Django site we had a Newsletter which contained N Articles and, of course, order was important. I assigned the default order as ascending Article.id, but this failed if Articles were entered in something other than "correct" order. On the News...
"added a numbered order field" - good. "update all the items with their new order numbers" - avoidable. Use numbers with gaps. * Floating point. That way, someone can insert "1.1" between 1 and 2. I find that this works nicely, as most people can understand how the sequencing works. And you don't have to worry too m...
in SQL, or Django ORM, what's the conventional way to have an ordered one-to-many?
[ "", "sql", "django", "" ]
Is there a particular scenario where a `WriteOnly` property makes more sense then a method? The method approach feels much more natural to me. What is the right approach? **Using Properties**: ``` Public WriteOnly Property MyProperty As String Set(ByVal value as String) m_myField = value End Set End Prop...
I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them. As an example, setting a list of values in a drop-down on a view and accessing the selected item: ``` public interface IWidgetSelector { void SetAvailableWidget...
For what it's worth, the Microsoft Framework Design Guidelines (as embodied in their FxCop tool) discourage Write-Only Properties and flag their presence as an API design issue, due to the unintuitiveness of that approach.
WriteOnly Property or Method?
[ "", "c#", ".net", "vb.net", "coding-style", "" ]
When selecting a block of text (possibly spanning across many DOM nodes), is it possible to extract the selected text and nodes using Javascript? Imagine this HTML code: ``` <h1>Hello World</h1><p>Hi <b>there!</b></p> ``` If the user initiated a mouseDown event starting at "World..." and then a mouseUp even right af...
You are in for a bumpy ride, but this is quite possible. The main problem is that IE and W3C expose completely different interfaces to selections so if you want cross browser functionality then you basically have to write the whole thing twice. Also, some basic functionality is missing from both interfaces. Mozilla de...
My [Rangy](http://code.google.com/p/rangy) library will get your part of the way there by unifying the different APIs in IE < 9 and all other major browsers, and by providing a `getNodes()` function on its Range objects: ``` function getSelectedNodes() { var selectedNodes = []; var sel = rangy.getSelection(); ...
Get selected text and selected nodes on a page?
[ "", "javascript", "firefox", "xhtml", "firefox-addon", "selection", "" ]
I have a website where all requests are redirected silently (via `.htaccess`) to `index.php` and then PHP is used to show the correct page (by parsing the `REQUEST_URI`). I was wondering if it's possible to submit POST data to a fake address too? I've currently got my form like so... ``` <form action="/send-mail" me...
Try this: ``` # redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,P] ``` "P" acts like "L" in that it stops processing rules but it also tells the module that the request should be passed off to the proxy module intact (meaning POST data is preserved).
You should be able to simply redirect to `index.php`, and then in that script, access `$_SERVER['REQUEST_URI']` to see the original request, with "send-mail" intact. By the way, "can't send as much information" is not the reason to use POST. The reason to use POST is that the request will modify data on your site, ins...
Is it possible to redirect post data?
[ "", "php", "apache", ".htaccess", "" ]
I have a TreeView control showing multiple TreeNodes in an organised heirarchy. I want to stop the user selecting the highest level Nodes (this was achieved by using the BeforeSelect Event). I also want to stop the TreeView from highlighting the top level nodes if the user selects them i.e. stop the TreeView from chang...
In addition to your existing code if you add a handler to the MouseDown event on the TreeView with the code and select the node out using it's location, you can then set the nodes colours. ``` private void treeView1_MouseDown(object sender, MouseEventArgs e) { TreeNode tn = treeView1.GetNodeAt(e.Location); tn....
This code prevents drawing the selection before it is canceled: ``` private void treeView1_MouseDown(object sender, MouseEventArgs e) { treeView1.BeginUpdate(); } private void treeView1_MouseUp(object sender, MouseEventArgs e) { treeView1.EndUpdate(); } ```
C# Stop a Treeview selecting one or more TreeNodes
[ "", "c#", "winforms", "treeview", "treenode", "" ]
I have a basic HTML form that gets inserted into a server side *div* tag based on how many records exist in the database. This HTML form comes out just fine, and everything looks good. But on my action page I cannot seem to access the input elements from the code behind. I have tried using the *Request* scope, but I ha...
If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via JavaScript post). This usually means that your form definition will look like this (I'm going off of memory - make sure you check the HTML elements are correct): ``` <form method="POST" action="page.aspx"> <in...
What I'm guessing is that you need to set those input elements to **runat="server"**. So you won't be able to access the control ``` <input type="text" name="email" id="myTextBox" /> ``` But you'll be able to work with ``` <input type="text" name="email" id="myTextBox" runat="server" /> ``` And read from it by usi...
How to access HTML form input from ASP.NET code behind
[ "", "c#", "asp.net", "html", "forms", "" ]
In the past, I have used XSD.exe to create c# classes from an xsd. Today, I added an XSD to VS.NET 2008 SP1 and it automatically generated a dataset from my xsd, slick but I don't want a dataset. Is there a way to have vs.net automatically execute xsd.exe each time I modify my xsd.
I believe your best bet would be to run xsd.exe as a pre-build event, and setting the build action for your XSD to "None".
Select the \*.xsd file, open Properties Window (F4 key) and delete "Custom Tool" and "Custom Tool Namespace". This will remove the "DataSet" issue. The "c# class from an xsd" issue can be solved by another custom tool. Look at [XsdCondeGenTool](http://weblogs.asp.net/cazzu/archive/2004/05/14/XsdCodeGenTool.aspx) - the...
Have vs.net automatically execute xsd.exe everytime time xsd is modified
[ "", "c#", "xsd", "xsd.exe", "" ]
After reading some threads on misuses of exceptions (basically saying you don't want to unwind the stack if a functions preconditions are incorrect - possibly signalling that all your memory is corrupt or something equally dangerous) I'm thinking about using assert() more often. Previously I have only used assert() as ...
You could build your own assert instead of using the stock C assert.h. Your assert won't be disabled. Look at how assert() is implemented in /usr/include/assert.h (or wherever). It's simply some preprocessor magic eventually calling an "assert fail" function. In our embedded environments, we replace assert() all the ...
I like to define my own assertion macros. I make two -- ASSERT tests always (even for optimized builds) and DASSERT only has an effect for debug builds. You probably want to default to ASSERT, but if something is expensive to test, or assertions inside inner loops of performance-sensitive areas can be changed to DASSER...
assert and NDEBUG
[ "", "c++", "error-handling", "" ]
I've been tasked with rewriting the Javascript engine currently powering my customer's internal website. While reviewing the code I've come across this function *flvFPW1* which I do not recognize, nor can I decipher the code(my Javascript knowledge is modest at best). A Google search gives me a few hits, but most if no...
My own research agrees that it's a dreamweaver extension: I found [code for version 1.44](http://forums.devshed.com/javascript-development-115/apply-onclick-to-all-links-in-template-265457.html) (scroll down some on this page) rather than 1.3: ``` function flvFPW1(){//v1.44 var v1=arguments,v2=v1[2].split(","),v3=(v1....
on your site, type in this in the location bar: ``` javascript:alert(flvFPW1); ``` it will report the function code
flvFPW1() - What does it do?
[ "", "javascript", "" ]
Should I instantiate my worker variables inside or outside my for loop E.g. a) ``` bool b = default(bool); for (int i = 0; i < MyCollection.Length; i++) { b = false; foreach(object myObject in myObjectCollection) { if (object.Property == MyCollection[i].Property) { b = true; break; } ...
Previous answer deleted as I'd misread the code. (Using "default(bool)" anywhere is a bit odd, btw.) However, unless the variable is captured by a delegate etc, I'd expect them to *either* compile to IL which is effectively the same (in terms of both behaviour and performance). As ever, write the most *readable* code...
inside looks cleaner but agree with Jon, the IL will be the same.
Whats The Most Efficient Way To Instantiate Worker Variables
[ "", "c#", "variables", "for-loop", "" ]
When I try this code: ``` a, b, c = (1, 2, 3) def test(): print(a) print(b) print(c) c += 1 test() ``` I get an error from the `print(c)` line that says: ``` UnboundLocalError: local variable 'c' referenced before assignment ``` in newer versions of Python, or ``` UnboundLocalError: 'c' not assign...
Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line, you are trying to reference the local variable `c` befor...
Python is a little weird in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the `print(a)` and `print(b)` statements, there's nothing by that name in the dictionary, so...
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
[ "", "python", "scope", "global-variables", "local-variables", "shadowing", "" ]
I'm creating HTML with a loop that has a column for Action. That column is a Hyperlink that when the user clicks calls a JavaScript function and passes the parameters... example: ``` <a href="#" OnClick="DoAction(1,'Jose');" > Click </a> <a href="#" OnClick="DoAction(2,'Juan');" > Click </a> <a href="#" OnClick="DoAc...
Using POST ``` function DoAction( id, name ) { $.ajax({ type: "POST", url: "someurl.php", data: "id=" + id + "&name=" + name, success: function(msg){ alert( "Data Saved: " + msg ); } }); } ``` Using GET ``` function DoAction( id, name...
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false like this: ``` function DoAction(id, name) { // your code return false; } ```
Passing parameters to a JQuery function
[ "", "javascript", "jquery", "html", "function", "parameters", "" ]
I am having some issues with using the OrderBy extension method on a LINQ query when it is operating on an enum type. I have created a regular DataContext using visual studio by simply dragging and dropping everything onto the designer. I have then created seperate entity models, which are simply POCO's, and I have use...
Can you specify the type `CampaignStatus` directly in your `DataContext` trough the designer? This way the value is automatically mapped to the `enum`.
What is the relationship between the `Campaign` class and `Campaigns`? If `Campaigns` returns the set of `Campaign` object, note you can't normally `select new` a mapped entity. I wonder if it would work any better if you did the OrderBy before the Select? One final trick might be to create a fake composable `[Functi...
Linq To SQL OrderBy, issue when using enums
[ "", "c#", "linq-to-sql", "enums", "" ]
I noticed for a while now the following syntax in some of our code: ``` if( NULL == var){ //... } ``` or ``` if( 0 == var){ //... } ``` and similar things. Can someone please explain why did the person who wrote this choose this notation instead of the common `var == 0` way)? Is it a matter of style, or does...
It's a mechanism to avoid mistakes like this: ``` if ( var = NULL ) { // ... } ``` If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes: ``` if ( NULL = var ) { // not legal, won't compile // ... } ``` Of course this won't work if variable names appear ...
If you mistakenly put ``` if ( var = NULL ) ``` instead of ``` if ( var == NULL ) ``` then there will only be a compiler warning. If you reverse the order: ``` if ( NULL == var ) ``` then there will be a compiler error if you put ``` if ( NULL = var ) ``` Personally, I hate to read code written that way, and I ...
Why put the constant before the variable in a comparison?
[ "", "c++", "c", "syntax", "comparison", "" ]
I'm doing a addin system where the main app loads assemblies Addin1.dll and Addin2.dll on runtime in new AppDomain's. However, in case that Addin1.dll is signed (strong name) with my key and Addin2.dll is not, I want to be able to only load Addin1.dll and reject Addin2.dll. I'm suspecting that it needs to be done by ...
Look into the [Assembly.Load](http://msdn.microsoft.com/en-us/library/ms145229.aspx "Assembly.Load Method (AssemblyName, Evidence)") method that takes an Evidence parameter. You can find an example of how to create an evidence from your public key [here](http://msdn.microsoft.com/en-us/library/system.security.policy.ev...
You can implment a DomainManager and base your load/block decision's on whatever you like. I answered a somewhat related question [here.](https://stackoverflow.com/questions/439173/message-pumps-and-appdomains/924653#924653)
How to load only signed assembly to a new AppDomain?
[ "", "c#", "assemblies", "appdomain", "strongname", "signed", "" ]
I am trying to use regular expressions to find a UK postcode within a string. I have got the regular expression working inside RegexBuddy, see below: ``` \b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b ``` I have a bunch of addresses and want to grab the postcode from them, example below: > 123 Some Road Name...
repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is.. ``` import re s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\ "County\nPA2 6NH\n123 Some Road Name\nTown, City\n...
Try ``` import re re.findall("[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}", x) ``` You don't need the \b.
Python, Regular Expression Postcode search
[ "", "python", "regex", "postal-code", "" ]
I’m working on an in-house app that tracks a bunch of tasks. I wanted to have a simple task monitor that would list the task name and the task’s status. I need this to look just a little nice, I’m no designer so whatever I do is going to suck, but a basic text display won’t work for the project requirements. What I am...
It sounds like what you may be looking for is an [`JList`](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html). You can add your items to the `JList`'s by first adding your "task" to the `JList` object's [`ListModel`](http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html) (see the [Create a Model]...
The standard way of doing this kind of things is to use JTable (or JList) as a container. You don't have to use default renderes fot table cells, but you can specify your own renderer for specific cells. Take a look at [CellRenderer](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableCellRenderer.html)
In Java Swing how can you manage a list of panels allowing multiple panels to be selected?
[ "", "java", "swing", "jpanel", "jlist", "" ]
I have a table where I store customer sales (on periodicals, like newspaper) data. The product is stored by issue. Example ``` custid prodid issue qty datesold 1 123 2 12 01052008 2 234 1 5 01022008 1 123 1 5 01012008 2 444 2 3 ...
Assuming that "latest" is determined by date (rather than by issue number), this method is usually pretty fast, assuming decent indexes: ``` SELECT T1.prodid, T1.issue FROM Sales T1 LEFT OUTER JOIN dbo.Sales T2 ON T2.custid = T1.custid AND T2.prodid = T1.prodid AND T2.datesold > T1.dateso...
Generic SQL; SQL Server's syntax shouldn't be much different: ``` SELECT prodid, max(issue) FROM sales WHERE custid = ? GROUP BY prodid; ```
SQL Query Advice - Most recent item
[ "", "sql", "sql-server", "" ]
Looking for advice (perhaps best practice). We have a MS Word document (Office 2007) that we are extracting text from a cell. We can use the following: ``` string text = wordTable.cell(tablerow.index, 1).Range.Text; ``` The text is extracted; however we seem to get extra characters trailing, for example `\r\a`. No...
I would break it out into a separate method but use the replace implementation since it's the simplest solution. You could always change the implementation later if you run into problem (like the text contains more than one `\r\a` and needs to be preserved) So: ``` private string stripCellText(string text) { re...
I would definitely opt for breaking it out into a separate method personally. it helps with code readability and makes it a lot easier to change if needed in the future.
Advice for extracting word text and handling cellbreak characters
[ "", "c#", "string", "ms-word", "vsto", "" ]
I am creating a Windows service. When an exception occurrs, I handle it appropriately and create a log. I am using the [decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern), as there are many different ways people will be looking at these logs. I have an email logger, a file logger, and a windows event lo...
Its not an answer, but curious why did you choose to not utilize the existing System.Diagnostics.Trace methods. You could implement some type of categorization of log types on top it it perhaps?
Why don't put it in the actual Windows Event log if logger fails?
c# windows-services - How do I handle logging exceptions?
[ "", "c#", "exception", "logging", "windows-services", "decorator", "" ]
Is there a way to update more than one Database having same schema using single ObjectDataSource in C#??? i.e Just by providing more than one connection string is it some how possible to update more than one Database? I need to update/insert same record in multiple Database with same schema using ObjectDataSource in C...
Yes you can do it, since with an ObjectDataSource YOU ae the one writing the code that does the insert. Inside your "Update" and "Delete" methods you can simply perform two database actions, one for each database that you are working with. You can abstract this out to an operation that could be passed a connection to e...
Considering "**Mitchel Sellers**" Suggestion with some changes:- For **ObjectDataSource** create **OnInserting,OnUpdating,OnDeleting** Events in which handle Insert/Update/Delete on all the Databases except the one attached to he ObjectDataSource. e.g If **DataConnectionString1**,**DataConnectionString2** and **Data...
Update more than one database using same ObjectDataSource using C#
[ "", "c#", ".net", "ado.net", "" ]
I know python functions are virtual by default. Let's say I have this: ``` class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" ``` I don't want them to be able to do this: ``` class Aoo(Foo): def r...
You can use a metaclass: ``` class NonOverridable(type): def __new__(self, name, bases, dct): if bases and "roo" in dct: raise SyntaxError, "Overriding roo is not allowed" return type.__new__(self, name, bases, dct) class foo: __metaclass__=NonOverridable ... ``` The metatype'...
Python 3.8 (released Oct/2019) adds `final` qualifier to typing. A `final` qualifier was added to the typing module---in the form of a `final` decorator and a Final type annotation---to serve three related purposes: * Declaring that a method should not be overridden * Declaring that a class should not be subclassed *...
Making functions non override-able
[ "", "python", "" ]
My company currently evaluates the development of a Java FAT client. It should support a dynamic GUI and has as much logic as possible on the server side. Hence the idea came up to send the screen as XML to the FAT client, show it to the user and send the entered data similar to "html form" back in a structure like: `...
When I last looked for such a thing, two options were [Thinlet](http://www.thinlet.com/index.html) and [Apache Jelly](http://commons.apache.org/jelly/libs/swing/index.html). The plus points were that you could separate the wiring and construction of your application from the behaviour. I'm not sure of the viability of...
"It should support a dynamic GUI and has as much logic as possible on the server side." What you're describing is a web app. The client is already written (the browser) and the XML (ish) format is (X)HTML. It would be possible to recreate this process using your own XML format and your own client, but I don't see why...
Java GUI described in XML
[ "", "java", "xml", "user-interface", "" ]
suppose I declare a dynamic array like ``` int *dynArray = new int [1]; ``` which is initialized with an unknown amount of int values at some point. How would I iterate till the end of my array of unknown size? Also, if it read a blank space would its corresponding position in the array end up junked? # Copying In...
No portable way of doing this. Either pass the size together with the array, or, better, use a standard container such as `std::vector`
You don't: wrap the array into a structure that remembers its length: `std::vector`. ``` std::vector v(1); std::for_each( v.begin(), v.end(), ... ); ```
C++ How can I iterate till the end of a dynamic array?
[ "", "c++", "arrays", "" ]
Consider this example table (assuming SQL Server 2005): ``` create table product_bill_of_materials ( parent_product_id int not null, child_product_id int not null, quantity int not null ) ``` I'm considering a composite primary key containing the two product\_id columns (I'll definitely want a unique cons...
As has already been said by several others, it depends on how you will access the table. Keep in mind though, that any RDBMS out there should be able to use the clustered index for searching by a single column as long as that column appears first. For example, if your clustered index is on (parent\_id, child\_id) you d...
"What you query on most often" is not necessarily the best reason to choose an index for clustering. What matters most is what you query on to obtain multiple rows. Clustering is the strategy appropriate for making it efficient to obtain multiple rows in the fewest number of disk reads. The best example is sales histo...
Should a Composite Primary Key be clustered in SQL Server?
[ "", "sql", "database", "database-design", "primary-key", "" ]
I've been working with Vector2's and XNA, and I've come to find that calling the Normalize() member function on a Zero Vector normalizes it to a vector of {NaN, NaN}. This is all well and good, but in my case I'd prefer it instead just leave them as Zero Vectors. Adding this code to my project enabled a cute extension...
This doesn't work because Vector 2 [is actually a struct](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx). This means it gets passed by value and you can't modify the caller's copy. I think the best you can do is the workaround specified by lomaxxx. This illustrates why you should general...
Well, if you're really just *dying* to do this, you could do something like this: ``` public static void NormalizeOrZero(this Vector2 ignore, ref Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); } ``` You would call it this way: ``` v2.NormalizeOrZero(ref v2); ``` It's mighty ugly, but it'll work, ...
How do I access 'this' from within a C# extension method?
[ "", "c#", "pass-by-reference", "this", "" ]
I have a `JTable` with a custom `TableModel` called `DataTableModel`. I initialized the table with a set of column names and no data as follows: ``` books = new JTable(new DataTableModel(new Vector<Vector<String>>(), title2)); JScrollPane scroll1 = new JScrollPane(books); scroll1.setEnabled(true); scroll1.setVisible(t...
Have you implemented the other methods for `TableModel`? If so, how does your implementation look? Maybe you should post your table model code to let us inspect it? BTW: My main error when implementing `TableModel` was to override `getRowCount()` and `getColumnCount()` to `return 0`. This will tell the table that ther...
This is weird problem. You said that `DataTableModel` implements `TableModel`. So. If you does not use abstract class the problem should be in the way how you are handling the events. Are listeners really registered and then notified? If you can, please send link to source of `DataTableModel`. But before, verify that y...
JTable updates not appearing
[ "", "java", "user-interface", "swing", "jtable", "" ]
An interface is a 100% abstract class, so we can use an interface for efficient programming. Is there any situation where an abstract class is better than an interface?
Abstract classes are used when you do intend to create a concrete class, but want to make sure that there is some **common state** in all the subclasses or a possible **common implementation** for some operations. Interfaces cannot contain either.
Yes, there is a place for both abstract classes and interfaces. Let's go with a concrete example. We'll look into how to make a `CheckingAccount` and `SavingsAccount` from an abstract `AbstractBankAccount` and see how we can use an interface differentiate the two types of accounts. To start off, here's an abstract cl...
Need for Abstract Class as well as Interface?
[ "", "java", "interface", "abstract-class", "" ]
Greetings, I have data stored on mysql with delimiter "," in 1 table. I have rows and column stored on database too. Now i have to output the data using rows and column number stored on database to draw the table. Rows and column number are user input, so it may varies. Let say, there is number 3 on column and 3 on ...
You can turn the comma separated values from your data column into an array using the explode() function: ``` <?php $result = mysql_query('SELECT rows, columns, data from table_name where id=1'); $record = mysql_fetch_assoc($result); $rows = $record['rows']; $columns = $record['columns']; $data = explode('...
This won't help you solve this very problem, but a word of good advice: never EVER write comma seperated values into a database field. You can't sensibly query information stored like this, and your application code will be cluttered with ugly conversions. Instead, use a seperate table with a reference to the main tabl...
PHP MYSQL - Explode help
[ "", "php", "mysql", "explode", "" ]
Is there a way in Python, to have more than one constructor or more than one method with the *same name*, who differ in the *number of arguments* they accept or the *type(s) of one or more argument(s)*? If not, what would be the best way to handle such situations? For an example I made up a color class. *This class s...
In general, use factory methods, marked up as `@classmethod`s. They'll also work correctly on subclasses. From a design perspective, they are more explicit, especially when given a good name. In this case, mixing everything together is probably more convenient, but it also makes the contract for your constructor more ...
You can have the factory methods, it is fine. But why not just call it as it is? ``` Color(r, g, b) Color(*[r, g, b]) Color(**{'r': r, 'g': g, 'b': b}) ``` This is the python way. As for the from object constructor, I would prefer something like: ``` Color(*Color2.as_list()) ``` *Explicit is better than implicit* -...
How to handle constructors or methods with a different set (or type) of arguments in Python?
[ "", "python", "" ]
I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this: ``` int i = true; ``` Is it "alwa...
bool is a fundamental datatype in C++. Converting `true` to an integer type will yield 1, and converting `false` will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like ``` enum bool { false, true }; ``` So did the Windows API. Starting with C99, we have `_Bool` as a...
Yes, bool is a built-in type. WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.
Is 'bool' a basic datatype in C++?
[ "", "c++", "" ]
I've been watching Douglas Crockford's talks at YUI Theater, and I have a question about JavaScript inheritance... Douglas gives this example to show that "Hoozit" inherits from "Gizmo": ``` function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return th...
The reason is that using `Hoozit.prototype = Gizmo.prototype` would mean that modifying Hoozit's prototype object would also modify objects of type Gizmo, which is not expected behavior. `Hoozit.prototype = new Gizmo()` inherits from Gizmo, and then leaves Gizmo alone.
The other answers address this, but if you DO want to inherit the prototype, you can use some parasitic magic: ``` Object.prototype.inherit = function(p) { NewObj = function(){}; NewObj.prototype = p; return new NewObj(); }; // Paraphrasing of Nicholas Zakas's Prototype Inheritance helper function inheri...
Prototypal inheritance in JavaScript
[ "", "javascript", "inheritance", "prototypal-inheritance", "" ]
In C#, it is possible to retrieve assembly related information like product name, version etc using reflection: ``` string productName = Assembly.GetCallingAssembly().GetName().Name; string versionString = Assembly.GetCallingAssembly().GetName().Version.ToString(); ``` How do I do the equivalent if the executing asse...
Walking the stack is not necessary to find out what process you are in. You simply make a single Win32 API call: ``` HMODULE hEXE = GetModuleHandle(NULL); ``` According to the [documentation for this call](http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx): > If this parameter is NULL, GetModuleHandle ret...
you could use the following code in VB.Net to retrieve extended document properties: ``` Sub Main() Dim arrHeaders(41) Dim shell As New Shell32.Shell Dim objFolder As Shell32.Folder objFolder = shell.NameSpace("C:\tmp\") For i = 0 To 40 arrHeaders(i) = objFolder.GetDetailsOf(objFolder.It...
Retrieving product information from an unmanaged executing application in C#/.NET
[ "", "c#", ".net", "com", "unmanaged", "" ]
**Description |** A Java program to read a text file and print each of the unique words in alphabetical order together with the number of times the word occurs in the text. The program should declare a variable of type `Map<String, Integer>` to store the words and corresponding frequency of occurrence. Which concrete ...
[`TreeMap`](http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html) seems a no-brainer to me - simply because of the "in alphabetical order" requirement. `HashMap` has no ordering when you iterate through it; `TreeMap` iterates in the natural key order. EDIT: I think Konrad's comment may have been suggesting "us...
TreeMap beats HashMap because TreeMap is already sorted for you. However, you might want to consider using a more appropriate data structure, a bag. See [Commons Collections](http://commons.apache.org/collections) - and the [TreeBag](http://commons.apache.org/collections/api-3.2/org/apache/commons/collections/bag/Tree...
Which data structure would you use: TreeMap or HashMap? (Java)
[ "", "java", "data-structures", "dictionary", "hashmap", "treemap", "" ]
I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli\_Karlsson?= and ...
You can use the python email library (python 2.5+) to avoid these problems: ``` import email import poplib import random from cStringIO import StringIO from email.generator import Generator pop = poplib.POP3(server) mail_count = len(pop.list()[1]) for message_num in xrange(mail_count): message = "\r\n".join(pop...
There is a better way to do this, but this is what i ended up with. Thanks for your help guys. ``` import poplib, quopri import random, md5 import sys, rfc822, StringIO import email from email.Generator import Generator user = "email@example.com" password = "password" server = "mail.example.com" # connects try: ...
Trouble with encoding in emails
[ "", "python", "email", "encoding", "" ]
Do you localize your javascript to the page, or have a master "application.js" or similar? If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages? EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/...
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can de...
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do. All shared JS code lives in the `SITE/javascripts` directory, but it's loaded in 'tiers' For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.ne...
Where do you put your javascript?
[ "", "javascript", "" ]
Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, *now*. Too late. Okay. Take a deep breath. Here are the rules. Take *two* thirty sided dice (yes, [they do exist](http://paizo.com/store/byCompany/k/koplow/dice/d30)) and roll them simultaneously. * Add the ...
I had to first rewrite your code before I could understand it: ``` def OW60(sign=1): r1 = random.randint (1, 30) r2 = random.randint (1, 30) val = sign * (r1 + r2) islow = (r1<=5) + (r2<=5) ishigh = (r1>=26) + (r2>=26) if islow == 2 or ishigh == 2: return val + OW60(1) elif islo...
I've done some basic statistics on a sample of 20 million throws. Here are the results: ``` Median: 17 (+18, -?) # This result is meaningless Arithmetic Mean: 31.0 (±0.1) Standard Deviation: 21 (+1, -2) Root Mean Square: 35.4 (±0.7) Mode: 36 (seemingly accurate) ``` The errors were determined experimentally. The arit...
Calculate exact result of complex throw of two D30
[ "", "python", "math", "statistics", "puzzle", "" ]
I have a third-party library in my SVN repository and I'd like to associate source/javadoc with it locally in Eclipse. I.e., there should be some local setting (for example, an entry in the `local.properties` file) that associates the source/javadoc with the JAR file, but which doesn't introduce local dependencies into...
I believe this would be better achieved through: * the creation of a linked folder combined with * the declaration of a linked resource The linked resource defines a path variable which would be equals to `/my/path/to/lib/src` ![Eclipse Linked Resources](https://i.stack.imgur.com/YPlVi.jpg) The linked folder would ...
I just figured out a simple answer to this (in Indigo) after working on it in the background and free moments for a couple of days. The easiest way I've found is to expand your project in the Project Explorer, go into your Referenced Libraries, right-click the appropriate referenced JAR and click Properties. In there y...
Eclipse: Attach source/javadoc to a library via a local property
[ "", "java", "eclipse", "jar", "javadoc", "" ]
So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following **working** code: ``` class Test { private int privateInt; [...] public boolean equals(Object obj) { [...] Test t = (Test) obj; if ( t.privateInt == privateInt )...
It's accessible from different instances of the same class. According to [this page](http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html) (bolding mine): > At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same me...
Mike's quite correct; you are confusing objects (instances of a class) with the class itself. The members are private to the *class*, not any particular *instance* of the class. I recall being just as surprised about this when I was new to Java.
Java Private Field Visibility
[ "", "java", "language-features", "visibility", "" ]
I made an html file called test.html then I navigated to it as "<http://site.com/test.html?test1=a>" but the textbox stayed blank. Why is this? Super simple code ``` <html> <head> <title>Test</title> </head> <body > <input type=text name="test1"> </body> </html> ```
The file should be a PHP file, so test.php. Then maybe something like this: ``` <html> <head> <title>Test</title> </head> <body> <input type="text" name="test1" value="<?php echo htmlspecialchars($_GET['test1'], ENT_QUOTES); ?>"> </body> </html> ``` The reason it stays blank in your example is because there ...
HTML is just another file extension to a webserver, it's not going to do any kind of processing unless you've done something to make that so. Would you expect to open <http://site.com/foo.txt?contents=helloworld> and see "helloworld" in the browser? I suggest you google up some tutorials (w3schools is usually good for...
Pass variable into an input
[ "", "php", "html", "" ]
I came across a problem in my current application that required fiddling with the query string in a base `Page` class (which all my pages inherit from) to solve the problem. Since some of my pages use the query string I was wondering if there is any class that provides clean and simple query string manipulation. Examp...
Use `HttpUtility.ParseQueryString`, as someone suggested (and then deleted). This will work, because the return value from that method is actually an `HttpValueCollection`, which inherits `NameValueCollection` (and is internal, you can't reference it directly). You can then set the names/values in the collection norma...
I was hoping to find a solution built into the framework but didn't. (those methods that are in the framework require to much work to make it simple and clean) After trying several alternatives I currently use the following extension method: (post a better solution or comment if you have one) ``` public static class ...
A clean way of generating QueryString parameters for web requests
[ "", "c#", ".net", "asp.net", "url", "" ]
How can you access and display the row index of a gridview item as the command argument in a buttonfield column button? ``` <gridview> <Columns> <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument=" ? ? ? " /> ..... ```
Here is a very simple way: ``` <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument='<%# Container.DataItemIndex %>' /> ```
[MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx) says that: > The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command butto...
ASP.NET GridView RowIndex As CommandArgument
[ "", "c#", "asp.net", "gridview", "" ]
Background: I'm currently debugging an application written over a custom-built GUI framework in C++. I've managed to pin down most bugs, but the bugs I'm having the most trouble with tend to have a common theme. All of them seem to be to do with the screen refreshing, redrawing or updating to match provided data. This ...
I agree with dual monitors or even remote debugging to reduce interfering with the messages. I also highly recommend Spy utilities. These let you see what messages are being sent in the system. One such program is Winspector. <http://www.windows-spy.com/>
This may not help, but I've found using dual monitors useful in this scenario. I have the debugger on one screen and the application on another. I can then step thru the code and see the application refreshing or doing whatever it is on the other screen. There is still issues with focus doing this way, but at least I c...
Debugging GUI Applications in C++
[ "", "c++", "debugging", "user-interface", "" ]
I have the following string: ``` <SEM>electric</SEM> cu <SEM>hello</SEM> rent <SEM>is<I>love</I>, <PARTITION />mind ``` I want to find the last "SEM" start tag before the "PARTITION" tag. not the SEM end tag but the start tag. The result should be: ``` <SEM>is <Im>love</Im>, <PARTITION /> ``` I have tried this regu...
And here's your goofy Regex!!! ``` (?=[\s\S]*?\<PARTITION)(?![\s\S]+?\<SEM\>)\<SEM\> ``` What that says is "While ahead somewhere is a PARTITION tag... but while ahead is NOT another SEM tag... match a SEM tag." Enjoy! Here's that regex broken down: ``` (?=[\s\S]*?\<PARTITION) means "While ahead somewhere is a PAR...
Use [String.IndexOf](http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx) to find PARTITION and [String.LastIndexOf](http://msdn.microsoft.com/en-us/library/system.string.lastindexof.aspx) to find SEM? ``` int partitionIndex = text.IndexOf("<PARTITION"); int emIndex = text.LastIndexOf("<SEM>", partition...
Finding the last occurrence of a word
[ "", "c#", ".net", "regex", "" ]
Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?
I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter. <http://www.emacswiki.org/emacs/PythonMode#toc10> ``` (setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" ...
never used it myself, but I do follow the ipython mailing list, and there was a [thread](http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/thread.html) a couple months back. maybe this will help <http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html> It's also a very res...
Emacs 23 and iPython
[ "", "python", "emacs", "ipython", "emacs23", "" ]
I have a page which has a rectangular area with text and icons in it and the whole thing is clickable. The anchor tag is set to display: block. One of the icons has an onclick handler. If a person clicks on an icon, I just want the icon's onclick handler to run and not to actually activate the containing anchor tag. F...
I would just use a `<span>`, but I think returning `false` from the event handler should also do the trick.
[This post](http://www.openjs.com/articles/prevent_default_action/) has a few items yours doesn't (like e.returnValue and e.preventDefault) but from the text it appears those are FF specific functions. Might be worth a shot though.
Why can't I trap a mouse click in IE?
[ "", "javascript", "internet-explorer", "" ]
The *VS2008 SP1* documentation talks about **`std::tr1::mem_fun`**. So why, when I try and use **`std::tr1::mem_fun`**, why do I get this compile error?: ``` 'mem_fun' : is not a member of 'std::tr1' ``` At the same time, I can use **`std::tr1::function`** without problems. Here is the sample code I am trying to co...
Change it to this: ``` std::tr1::function<void (int)> f = std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1); f(2); ``` The binder requires the int argument. So you have to give it a placeholder which stands for the integer argument that the generated function object needs. Btw: I'm...
I am no expert on either TR1 or VS2008, but a quick googling suggests that the function you're looking for is std::tr1::mem\_fn instead. (At least, that's what Boost calls it in their [TR1 implementation](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_tr1/subject_list.html#boost_tr1.subject_list.mem_fn), and that'...
How do I use std::tr1::mem_fun in Visual Studio 2008 SP1?
[ "", "c++", "std", "tr1", "mem-fun", "" ]
I have a digital certificate that identifies a user. I need to use it to Digitally sign pdf files. Does anyone have an example that does not uses a third party component? I need to get this done but it would be nice to fully understand how things are done. C# Examples please :)
The open source [iTextSharp](http://itextsharp.sourceforge.net/) library will allow you to do this. Here's a [post](http://www.codeproject.com/Articles/14488/E-signing-PDF-documents-with-iTextSharp) explaining how to digitally sign a pdf file. If you don't want to use a third party library then you can implement it you...
Proper PDF signing is a *very* sophisticated task. There exist a number of files that don't conform to the PDF specification (broken xrefs etc) and your code must handle all of them. Then various Acrobat versions treat certain things in signed fields differently. So if you need to do the task (rather than study how it ...
Digitally sign PDF files
[ "", "c#", "pdf", "digital-signature", "" ]
I have an enum ``` public enum FileExtentions { mp3, mpeg } ``` And I have a FileInfo of which I want to check if the extension is in the previous enum. I was hoping I could do a ``` FileExtensions.Any(e=>e.ToString().Equals(file.Extension)); ``` But that would have been too awesome. Any ideas?
What's the reason behind `Any` … `Equals`? Did you overlook `Contains`? ``` bool result = Enum.GetNames(typeof(FileExtensions)).Contains("mp3"); ```
While pressing submit I thought of the answer myself: ``` Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension)) ```
Check if an enum has a field that equals a string
[ "", "c#", "enums", "" ]
Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.). I also want to be able to define a transparent color (not alpha channel) for this image. **The GdiPlus solution seems to be limited to images of width divisible by 4**. Anything else fails dur...
I read and write PNGs using [libpng](http://www.libpng.org/pub/png/libpng.html) and it seems to deal with everthing I throw at it (I've used it in unit-tests with things like 257x255 images and they cause no trouble). I believe the [API](http://www.libpng.org/pub/png/libpng-1.2.5-manual.html) is flexible enough to not ...
[LodePNG](https://lodev.org/lodepng/) ([GitHub](https://github.com/lvandeve/lodepng)) is a lib-less PNG encoder/decoder.
Convert bitmap to PNG in-memory in C++ (win32)
[ "", "c++", "winapi", "png", "" ]
What is the best way to limit the amount of text that a user can enter into a 'textarea' field on a web page? The application in question is ASP .NET, but a platform agnostic answer is preferred. I understand that some amount of javascript is likely needed to get this done as I do not wish to actually perform the 'pos...
use a RegularExpressionValidator Control in ASP.Net to validate number of character along with with usual validation
``` function limit(element, max_chars) { if(element.value.length > max_chars) element.value = element.value.substr(0, max_chars); } ``` As javascript, and... ``` <textarea onkeyup="javascript:limit(this, 80)"></textarea> ``` As XHTML. Replace 80 with your desired limit. This is how I do it anyway. Note ...
What is the best way to limit the amount of text that can be entered into a 'textarea'?
[ "", "asp.net", "javascript", "html", "" ]
I have an ATL control that I want to be Unicode-aware. I added a message handler for WM\_UNICHAR: ``` MESSAGE_HANDLER( WM_UNICHAR, OnUniChar ) ``` But, for some reason, the OnUniChar handler is never called. According to the documentation, the handler should first be called with "UNICODE\_NOCHAR", on which the handl...
What are you doing that you think should generate a WM\_UNICHAR message? If your code (or the ATL code) ultimately calls CreateWindowW, then your window is already Unicode aware, and WM\_CHAR messages will be UTF-16 format. The documentation is far from clear on when, exactly, a WM\_UNICHAR message gets generated, bu...
My experience today is that Spy++ does not give correct results for WM\_CHAR in a Unicode proc. I am getting ASCII translations or '?' showing in the Messages list, even if I view Raw (not Decoded) arguments. The debugger shows wParam to be the Unicode code point though.
Why is my WM_UNICHAR handler never called?
[ "", "c++", "com", "unicode", "atl", "" ]
I want to get a list of all Django auth user with a specific permission group, something like this: ``` user_dict = { 'queryset': User.objects.filter(permisson='blogger') } ``` I cannot find out how to do this. How are the permissions groups saved in the user model?
If you want to get list of users by permission, look at this variant: ``` from django.contrib.auth.models import User, Permission from django.db.models import Q perm = Permission.objects.get(codename='blogger') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() ```
This would be the easiest ``` from django.contrib.auth import models group = models.Group.objects.get(name='blogger') users = group.user_set.all() ```
How to get a list of all users with a specific permission group in Django
[ "", "python", "django", "dictionary", "permissions", "" ]
``` <?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; echo preg_replace($patterns, $replacements, $string); ?> ``` Ok guys, Now I have the above c...
You can use pipes for ["Alternation"](http://perldoc.perl.org/perlre.html#Regular-Expressions): ``` $patterns[0] = '/quick|lazy|dog/'; ```
why not use str\_replace ? ``` $output = str_replace(array('quick', 'brown', 'fox'), array('lazy', 'white', 'rabbit'), $input) ```
multi words PHP arrays replacement
[ "", "php", "arrays", "" ]
I have data bound `DataGridView` in a desktop app with columns that have their `ToolTipText` property set, yet no tool tip is displayed when I hover over grid view (cells or cell headers). The `ShowCellToolTips` property of the grid view is `true`, and I have verified using break points that it is not changed programm...
We ended up using a ToolTip widget and the `CellMouseEnter`, `CellMouseLeave` events to show it appropriately. Not optimal, but it works around the odd behaviour we were experiencing.
It appears from your question that you set the tooltip text of the columns. Columns tooltip text only appears when floating over the headers. To show tooltip text on the cells you have to hookup the `CellToolTipTextNeeded` event and set the value of `e.ToolTipText` in the event args
DataGridView ToolTipText not showing
[ "", "c#", "visual-studio", "visual-studio-2008", "datagridview", "desktop-application", "" ]
How can I change `CSS` from `javascript`. I'm using `jQuery-ui Dialog` and I want to change the style of a `DIV` from javascript. Thanks
Check out [the jQuery documentation](http://docs.jquery.com/CSS/css). If you want anything it will be there. Anyhow, if you want to add styles to elements, you need to use the `css` function, which has a few variants. ``` $(selector).css(properties); // option 1 $(selector).css(name, value); // option 2 ``` So if y...
*This answer works even without jQuery.* So you have something like this: ``` <style type="text/css"> .foo { color: Red; } .bar { color: Blue; } </style> <div class="foo" id="redtext"> some red text here </div> ``` If you wish to change just some attributes, you can always find the element using ``` var div...
How to change css properties of html elements using javascript or jquery
[ "", "javascript", "jquery", "css", "jquery-ui", "jquery-ui-dialog", "" ]
In my C# winforms app, I have a datagrid. When the datagrid reloads, I want to set the scrollbar back to where the user had it set. How can I do this? EDIT: I'm using the old winforms DataGrid control, not the newer DataGridView
You don't actually interact directly with the scrollbar, rather you set the `FirstDisplayedScrollingRowIndex`. So before it reloads, capture that index, once it's reloaded, reset it to that index. **EDIT:** Good point in the comment. If you're using a `DataGridView` then this will work. If you're using the old `DataGr...
Yep, definitely [FirstDisplayedScrollingRowIndex](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.firstdisplayedscrollingrowindex.aspx). You'll need to capture this value after some user interaction, and then after the grid reloads you'll want to set it back to the old value. For instance, if...
How can I set the position of my datagrid scrollbar in my winforms app?
[ "", "c#", "winforms", "datagrid", "" ]
I want to exceute a simple command which works from the shell but doesn't work from Java. This is the command I want to execute, which works fine: ``` soffice -headless "-accept=socket,host=localhost,port=8100;urp;" ``` This is the code I am excecuting from Java trying to run this command: ``` String[] commands = ne...
I would like to say how I solved this. I created a sh script that basically run the command of soffice for me. Then from Java I just run the script, and it works fine, like this: ``` public void startSOfficeService() throws InterruptedException, IOException { //First we need to check if the soffice process is...
I'm not sure if I'm not mistaken, but as far as I see you're generating the commands but never passing them to the "execute" method... you're executing "". Try using Runtime.getRuntime().exec(commands) =)
Problem with starting OpenOffice service (soffice) from Java (command working in commandline, but not from Java)
[ "", "java", "command", "openoffice.org", "runtime.exec", "soffice", "" ]
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is: ``` "$C/test/testing" ``` What I want to do is evaluate the environment variables in the string so that they're r...
Use [os.path.expandvars](http://docs.python.org/library/os.path.html#os.path.expandvars) to expand the environment variables in the string, for example: ``` >>> os.path.expandvars('$C/test/testing') '/stackoverflow/test/testing' ```
In Python 3 you can do: ``` '{VAR}'.format(**os.environ)) ``` for example ``` >>> 'hello from {PWD}'.format(**os.environ)) hello from /Users/william ```
How to evaluate environment variables into a string in Python?
[ "", "python", "filesystems", "environment-variables", "" ]
I am trying to write operator overload for custom class and don't know how to handle null comparison. ``` Class Customer { int id; public static bool operator ==(Customer a, Customer b) { //When both a and b are null don't know how to compare as can't use == in here as //it will fall into ...
``` if (Object.ReferenceEquals(a,b)) return true; ``` ReferenceEquals() checks if they are pointing to the exact same object (or if they are both null) (As a general rule, it's good to start an Equals() method with a call to ReferenceEquals, particularly if the rest of the method is complicated. It will make thi...
I'm not 100% sure I understand the problem, but you should be able to do: ``` if (((object)a == null) && ((object)b == null)) { return true; } ``` Without any problems.
operator overload problem
[ "", "c#", ".net", "" ]
Extension method is a really helpful feature that you can add a lot of functions you want in any class. But I am wondering if there is any disadvantage that might bring troubles to me. Any comments or suggestions?
* The way that extension methods are imported (i.e. a whole namespace at a time) isn't granular. You can't import one extension from a namespace without getting all the rest. * It's not immediately obvious from the source code where the method is defined. This is also an *advantage* - it means you can make your code lo...
Couple of things: * It's not always clear as to where the extension method comes from unless you are inside VS.NET * Extension methods can't be resolved via reflection or C# 4.0's dynamic lookup
Disadvantages of extension methods?
[ "", "c#", "extension-methods", "" ]
How can I remove duplicate values from a multi-dimensional array in PHP? Example array: ``` Array ( [0] => Array ( [0] => abc [1] => def ) [1] => Array ( [0] => ghi [1] => jkl ) [2] => Array ( [0] => mno [1] => pql ) [3] => Arr...
Here is another way. No intermediate variables are saved. We used this to de-duplicate results from a variety of overlapping queries. ``` $input = array_map("unserialize", array_unique(array_map("serialize", $input))); ```
Since 5.2.9 you can use [`array_unique()`](https://secure.php.net/manual/en/function.array-unique.php) if you use the `SORT_REGULAR` flag like so: ``` array_unique($array, SORT_REGULAR); ``` This makes the function compare elements for equality as if `$a == $b` were being used, which is perfect for your case. **Outp...
How to remove duplicate values from a multi-dimensional array in PHP
[ "", "php", "arrays", "duplicate-data", "" ]
So, I've had a fair amount of experience programming database driven web apps using php and coldfusion (not together, at different times) and I'm starting to look into the asp.net world (I have a project coming up at work that is all asp.net/c#.) My question is: there seems to be *a lot* of stuff to get mired in and i...
Good question! I'm assuming that you can pick up the C# syntax as you go so I'll focus on the big picture. To get started with a WebForms application, you *must* understand the page lifecycle and the application lifecycle. This is your first priority. The model used by ASP.NET is based on Windows form-based programmin...
Design an application. What you *need* to know should bubble up to the top fairly quickly.
I'm new to .NET - what should I concentrate on and what should I ignore?
[ "", "c#", ".net", "data-binding", "master-pages", "" ]
``` class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() ``` I would expect a return of : ``` 2 2 2 ``` But I get : ``` 2 4 6 ``` Why is this? I've foun...
*doh* I just figured out why. In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the **init** block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It see...
What you probably want to do is: ``` class Ball: def __init__(self): self.a = [] ``` If you use just `a = []`, it creates a local variable in the `__init__` function, which disappears when the function returns. Assigning to `self.a` makes it an instance variable which is what you're after. For a semi-related g...
Why do new instances of a class share members with other instances?
[ "", "python", "scope", "mutable", "" ]
I am having a frame-based webpage with 3 frames. A topliner, a navigation on the left side and a content frame on the bottom right side. Now, I want to show up a popup-menu when the user right-clicks on the content-frame. Because a div-container can not go out of the frame, my idea was, placing the whole frame-page in...
If you are only planning to support IE - you can try using a new modal window by calling window.showModalDialog. You can position the new window anywhere on the screen. There are many drawbacks to using a new window in general and a modal one at that... By the way - FF 3 and up also [supports window.showModalDialog]...
You say it's an enterprise application - do you have to support all major browser, or is IE enough? I'm asking this because IE has a function that works exactly like you need: ``` window.createPopup(...) ``` <http://msdn.microsoft.com/en-us/library/ms536392(VS.85).aspx> The pop-up will be visible even outside the b...
Frame position in JavaScript
[ "", "javascript", "popup", "frame", "mouse-position", "" ]
The comment to [this answer](https://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int#200099) got me wondering. I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension. Am I wrong about that? Is it possible to write a valid C program that...
In general, yes C code is considered C++ code. But C is not a proper subset in a strict sense. There are a couple of exceptions. Here are some valid things in C that are not valid in C++: ``` int *new;//<-- new is not a keyword in C char *p = malloc(1024); //void * to char* without cast ``` There are more examples ...
Also note that C99 adds several features which aren't permitted in C++ (or are only supported using vendor extensions), such as builtin `_Complex` and `_Imaginary` data types, variable-length arrays (arrays sized at runtime rather than compile time), flexible array members (arrays declared as the last member of a struc...
Is C code still considered C++?
[ "", "c++", "c", "" ]
I develop tools in Autodesk Maya. Many of the tools I build have simple windowed GUIs for the animators and modellers to use. These GUIs often contain what you'd normally expect to see in any basic window; labels, lists, menus, buttons, textfields, etc. However, there are limitations to the complexity of the UIs you ca...
I'm not sure if this is germane, but some googling turns up that PyQt is pretty popular inside of Maya. You could try the technique [here](http://www.highend3d.com/boards/lofiversion/index.php/t236041.html) or [here](http://www.highend3d.com/boards/index.php?showtopic=242116) (explained [here](http://groups.google.com/...
I don't know if there is a way around a mainloop for the gui, since it is needed to handle all event chains and redraw queues. But there are several means of inter-process communication, like pipes or semaphores. Maybe it is an option to split your Maya extension into the actual plugin, being tight into maya, and a se...
Using external GUI libraries to make user interfaces in Autodesk Maya
[ "", "python", "scripting", "wxpython", "wxwidgets", "maya", "" ]
Is there a widely accepted class for dealing with URLs in PHP? Things like: getting/changing parts of an existing URL (e.g. path, scheme, etc), resolving relative paths from a base URL. Kind of like a two-way [parse\_url()](http://php.net/parse_url), encapsulated with a bunch of handy functions. Does something like t...
You've got the [Net\_URL2](http://pear.php.net/package/Net_URL2/docs) package over at PEAR, which appears to have replaced the [original Net\_URL](http://pear.php.net/package/Net_URL/docs). I have no first hand experience with it, but I'll almost always take a PEAR package over "random library found on website".
This **[URL.php class](http://www.phpclasses.org/browse/file/3008.html)** may be a good start (not sure it is 'widely' accepted though). > URL class intended for http and https schemes > > This class allows you store absolute or relative URLs and access it's various parts (scheme, host, port, part, query, fragment). >...
Is there a good pre-existing class for dealing with URLs in PHP?
[ "", "php", "url", "" ]
I have the following table ``` custid ordid qty datesold 1 A2 12 2008-01-05 2 A5 5 2008-01-02 1 A1 5 2008-01-01 2 A7 3 2007-02-05 ``` What't the best way of getting the previous order for every customer? Thanks
If by "previous" you mean "the one before the latest": ``` SELECT TOP 1 ordid FROM orders WHERE custid = @custid and datesold < (SELECT MAX(datesold) FROM orders i where i.custid = orders.custid) ORDER BY datesold DESC ``` Of course `datesold` has to be a DATETIME with distinct enough values for this to wor...
A common solution for this kind of problem is to choose the Max(datesold) and get the latest that way. This is ok if the custid/datesold combination is unique, but if there were two orders on the same day, it can cause duplicates. If you have SQL 2005 or higher, you can use the Row\_Number function to rank each custom...
SQL Query Advice - Get Previous Customer Order
[ "", "sql", "sql-server", "" ]
I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this. Let me el...
Maybe I'm not understanding correctly, but it seems that git would *be* the solution here, since git's branches don't need separate paths. Create a branch for each working version of your eggs module. Then when you checkout that branch, the entire module is changed to a state matching the version of your sub-module. Y...
[Relative imports](http://www.python.org/doc/2.5.2/tut/node8.html#SECTION008420000000000000000) ([PEP 328](http://www.python.org/dev/peps/pep-0328/)) might help: ``` eggs/ __init__.py foo.py bar.py # foo.py from __future__ import absolute_import from . import bar ``` See [How do you organize Python modules?](h...
How do I work with multiple git branches of a python module?
[ "", "python", "git", "module", "" ]
I was thinking along the lines of using `typeid()` but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)
You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help. I am assuming you have a situation like this: ``` class Base; class A ...
``` class Base { public: virtual ~Base() {} }; class D1: public Base {}; class D2: public Base {}; int main(int argc,char* argv[]); { D1 d1; D2 d2; Base* x = (argc > 2)?&d1:&d2; if (dynamic_cast<D2*>(x) == nullptr) { std::cout << "NOT A D2" << std::endl; } if (dynamic_cast<D1*>(x) == nullp...
How do I check if an object's type is a particular subclass in C++?
[ "", "c++", "class", "subclass", "identification", "" ]
I am asking about the common techniques which are used in c# to support multilingual interface in windows forms
Everything I said here: [Internationalizing Desktop App within a couple years... What should we do now?](https://stackoverflow.com/questions/270829/internationalizing-desktop-app-within-a-couple-years-what-should-we-do-now) applies to this question.
I would also recommend to check out this tool: [Multilizer](http://www.multilizer.com/). I have been using it in my CBuilder/Delphi projects.
Develop multilingual windows application C#
[ "", "c#", "winforms", "internationalization", "multilingual", "" ]
This is a really basic question but... I have some code like this ``` var arr = Array('blah.jpg','ha.jpg'); for (var i=0; i<array.length; i++) { $('div#blah' + i).click(function() { $('img').attr('src', arr[i]); }); } ``` This should bind the div with `id="blah0"` to change all images to `'blah.jpg'` ...
Declare a new variable inside a function that creates a new click handler that gets the current value of i as a parameter: ``` function makeClickHandler(arr, local_i) { return function() { $('img').attr('src', arr[local_i]); }; } var arr = Array('blah.jpg','ha.jpg'); for (var i=0; i<array.length; i++)...
In this particular case you should be using a closure: ``` for (var i=0; i<10; i++) { (function(j){ $('div#blah'+j).click(function() { alert(j)); }); })(i); } ``` `(function(){ /* code */ })()` denotes a self executing function, which implies that it will use and evaluate the value of i immedi...
How do I use the value of a variable at declaration time in a JavaScript anonymous function?
[ "", "javascript", "jquery", "closures", "" ]
EDIT: I'm told that making you guys read means I get less attention. My apologies. Here's a simpler version: Bill got $100 dollars worth of items from a store. He wants to return enough of the items to get exactly $30 dollars back. The store has a Point of Return system that will help him do this. Here is the data...
If the number of items are small enough you can brute force this with SQL. This might be a quick to write solution, but you probably want to do something smarter. Sounds like the "[knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem)" which is NP complete. If the number of items is large, you will need to ...
You're asking for all subsets which sum up to exactly $30. This sounds a lot like the [subset sum problem](http://en.wikipedia.org/wiki/Subset_sum_problem), and [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem), so I strongly doubt you can do this with a simple query. You'd probably have to turn to T-S...
MySQL finding subtotals
[ "", "sql", "mysql", "group-by", "aggregate", "subtotal", "" ]
Hopefully a nice simple one. I've got a php3 website that I want to run on php 5.2 To start with I'd just like to have every reference to the current "index.php3" \_within\_each\_file\_ (recursively) changed to "index.php" and then move on to worrying about globals etc. K. Go! :) Update: Thanks a lot! I realise th...
``` find -type f -exec perl -pi -e 's/\bindex\.php3\b/index.php/g' {} \; ```
How about: ``` for file in *.php3 do sed 's/\.php3/.php/g' $file > ${file%3} done ``` The for/do/done loop deals with each .php3 file in turn, editing the file and replacing each string `.php3` with `.php`, and copying the file from something.php3 to something.php. *Added for amended question:* ``` for file in ...
How do I replace 'php3' with 'php' inside every file in a directory
[ "", "php", "regex", "string", "bash", "replace", "" ]
I'm working on a little web crawler that will run in the system tray and crawl a web site every hour on the hour. What is the best way to get .NET to raise an event every hour or some other interval to perform some task. For example I want to run an event every 20 minutes based on the time. The event would be raised a...
[System.Timers.Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx). If you want to run at specific times of the day, you will need to figure out how long it is until the next time and set that as your interval. This is just the basic idea. Depending on how precise you need to be you can d...
You may find help from Quartz.net <http://quartznet.sourceforge.net/>
How can I raise an event every hour (or specific time interval each hour) in .NET?
[ "", "c#", ".net", "scheduled-tasks", "" ]
I understand that [Firefox](http://www.mozilla.com/en-US/) addins can be created in Javascript and Chrome. How do they run advanced graphics applications such as [CoolIris](http://www.cooliris.com/) ? [![alt text](https://i.stack.imgur.com/CqFWU.png)](https://i.stack.imgur.com/CqFWU.png) (source: [cooliris.com](htt...
Cooliris uses native compiled code utilizing graphics acceleration on the platforms it supports. You can get a full screen GUI if you use Flash, but the user is informed about it (try watching a YouTube vid in fullscreen) and also the user can't do everything they can otherwise, like type using the keyboard.
*"Firefox addins can be created in Javascript*", It could be true *"All Firefox Add ins are created using javascript"* might not be not true Javascript is not the only way you can create Firefox addin, Just like Google toolbar may not have been created using javascript.Cooloris uses something more than javascript. Coo...
How do firefox extensions make use of the whole screen in 3D (eg. CoolIris)?
[ "", "javascript", "firefox", "add-in", "google-chrome", "cooliris", "" ]