Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to make a form move (using the titlebar) from a button click. I thought this would be simple using SendMessage: ``` Const WM_LBUTTONDOWN As Integer = &H201 Button1.Capture = False Cursor.Position = Me.Location + New Size(50, 8) SendMessage(Me.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), IntPtr.Zero) ``` H...
You would need `WM_`**`NC`**`LBUTTONDOWN` (and pass `HTCAPTION` as `wParam`). I'm still not entirely sure this would accomplish what you're trying to do, though. Typically, the way to allow the user to move your form when clicking somewhere other than the title bar is to process the `WM_NCHITTEST` message and return `...
The `LParam` value for the `wm_LButtonDown` message receives the mouse position in *client* coordinates. The title bar is in the non-client area, so use the [`wm_NCLButtonDown` message](http://msdn.microsoft.com/en-us/library/ms645620.aspx). I've seen that message given as an answer to this question before, but there's...
Programmatically start moving a form
[ "", "c#", "vb.net", "winforms", "sendmessage", "" ]
I am trying to create a winForms user control. But I want would like a User control that - when placed on the form -- doesn't take any form space. Instead, it lodges itself nicely below like OpenFileDialog does. First, what kind of user-created thing is this? Is it still called a "user control"? If not, that may expla...
Controls that appear in the "component tray", like the Windows Forms Timer control, inherit from Component. To create one with some automatic boilerplate code, right-click on a project and click Add... | Component
I believe you're talking about creating a [Component](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx).
How to create a specific type of user control
[ "", "c#", "winforms", "user-controls", "controls", "components", "" ]
Problem 1: I have a simple winforms app and I want to DataBind my Person.Name property to a textbox. Name is of type StringField. I originally defined the Name property as String. The data binding works great on value types such as String. I would like the StringField.Value property to be the default property of Strin...
You could create an implicit operator overload. Then you can create `StringField` from strings like this: ``` StringField field = "value of new object"; string value=(string)field; ``` Know that this creates a new `StringField` object. I wouldn't necessarily advice you to do this. ``` [System.Diagnostics.DebuggerDis...
Re data-binding, for *some* binding targets (`PropertyGrid`, `DataGridView`, etc), you can do this with a `TypeConverter` (see below). Unfortunately, this doesn't seem to work with `TextBox`, so I think your best option is to simply add a shim property (as already suggested): ``` string NameString { get { return Na...
C# Assigning default property for class and operator =
[ "", "c#", "properties", "default", "" ]
Basic premise: I have a Room which publishes an event when an Avatar "enters" to all Avatars within the Room. When an Avatar leaves the Room I want it to remove all subscriptions for that room. How can I best unsubscribe the Avatar from all events in the room before I add the Avatar to a new Room and subscribe to the...
Each delegate has a method named `GetInvocationList()` that returns all the actual delegates that have been registered. So, assuming the delegate Type (or event) is named say `MyDelegate`, and the handler instance variable is named `myDlgHandler`, you can write: ``` Delegate[] clientList = myDlgHandler.GetInvocationLi...
Probably the simplest way to accomplish this would be to store all of your subscribed events for an avatar in an `ArrayList` of delegates to the events. When the avatar leaves the room, simply loop through the list of delegates performing a standard remove (`-=`).
How do I unsubscribe all handlers from an event for a particular class in C#?
[ "", "c#", ".net", "events", "" ]
I used to code in C language in the past and I found the `scanf` function very useful. Unfortunately, there is no equivalent in C#. I am using using it to parse semi-structured text files. I found an interresting example of `scanf` implementation [here](http://www.codeproject.com/KB/recipes/csscanf.aspx). Unfortunate...
If regular expressions aren't working for you, I've just posted a `sscanf()` replacement for .NET. The code can be viewed and downloaded at <http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net>.
Since the files are "semi-structured" can't you use a combination of ReadLine() and TryParse() methods, or the Regex class to parse your data?
Looking for C# equivalent of scanf
[ "", "c#", "scanf", "" ]
I've got a problem with inheritance and generics. This is the code that illustrates my problem: ``` namespace TestApplication { public class MyClass<T> { private T field; public MyClass(T field) { this.field = field; } } public class MyIntClass : MyClass<in...
You can only cast from a base class to a derived class if the object is actually of type derived class. I mean, you can't cast an instance of base (`MyClass<int>`) to `MyIntClass`. You can, however cast it if it was actually of type `MyIntClass` stored as an `MyClass<int>` instance. ``` MyClass<int> foo = new MyIntCla...
The other answers so far are correct, but I'd like to point out that your example has *nothing* to do with generics. It's the equivalent of: ``` using System; class Base {} class Child : Base {} class Test { static void Main() { Base b = new Base(); // This will throw an exception Ch...
C# - Problem with generics and inheritance
[ "", "c#", "generics", "inheritance", "casting", "" ]
I'm looking for something similar to the [Proxy pattern](http://en.wikipedia.org/wiki/Proxy_pattern) or the [Dynamic Proxy Classes](http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html), only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercep...
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method. If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by [manipulations on the byte code level](http:/...
The design pattern you are looking for is: Differential Execution. I do believe. [How does differential execution work?](https://stackoverflow.com/questions/371898/how-does-differential-execution-work#381861) Is a question I answered that deals with this. However, may I suggest that you use a callback instead? You w...
In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?
[ "", "java", "design-patterns", "proxy-classes", "" ]
I am storing objects in a buffer. Now I know that I cannot make assumptions about the memory layout of the object. If I know the overall size of the object, is it acceptible to create a pointer to this memory and call functions on it? e.g. say I have the following class: ``` [int,int,int,int,char,padding*3bytes,unsi...
You can create a constructor that takes all the members and assigns them, then use placement new. ``` class Foo { int a;int b;int c;int d;char e;unsigned short int*f; public: Foo(int A,int B,int C,int D,char E,unsigned short int*F) : a(A), b(B), c(C), d(D), e(E), f(F) {} }; ... char *buf = new char[sizeof(Fo...
Non-virtual function calls are linked directly just like a C function. The object (this) pointer is passed as the first argument. No knowledge of the object layout is required to call the function.
Managing C++ objects in a buffer, considering the alignment and memory layout assumptions
[ "", "c++", "runtime", "compiler-construction", "" ]
I don't mean "Basic SQL", but strongly the specs and the difference between the specs and the implementations between great databases (like SQL Server, Oracle, etc).
[![](https://i.stack.imgur.com/yYGdf.jpg)](https://i.stack.imgur.com/yYGdf.jpg) (source: [amazon.com](http://images-eu.amazon.com/images/P/0596004818.01.jpg)) --- [SQL In a Nutshell](https://shop.oreilly.com/product/9780596518851.do) by O'Reilly and Associates. It covers all 5 major SQL Dialects, the differences be...
The number one way of learning the differences is to work in the various databases. SQL Server, Oracle, and MySql all offer free (express) editions. Also, if you want to step up a bit you can get the developer version of SQL Server for about $50. Oracle: <http://www.oracle.com/technology/products/database/xe/index.ht...
What the best resource to learn ANSI SQL?
[ "", "sql", "sql-server", "specifications", "ansi-sql", "" ]
I'm just beginning to use Regex so bear with my terminology. I have a regex pattern that is working properly on a string. The string could be in the format "text [pattern] text". Therefore, I also have a regex pattern that negates the first pattern. If I print out the results from each of the matches everything is show...
It can be as simple as:- ``` string newString = Regex.Replace("abc", "b", "<td>${0}</td>"); ``` Results in `a<td>b</td>c`. In your case:- ``` Regex r = new Regex(negRegexPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); text = r.Replace(text, "<td>${0}</td>"); ``` Will replace all occurance of negRege...
Although I agree that the Regex.Replace answer above is the best choice, just to answer the question you asked, how about replacing from the last match to the first. This way your string grows beyond the "previous" match so the earlier matches indexes will still be valid. ``` for (int i = mc.Count - 1; i > 0; --i) ```
Using Regex to edit a string in C#
[ "", "c#", ".net", "regex", "" ]
Please pardon my C#.Net newbie status. If this is obvious and I missed it from the docs, a link to the relevant page or sample code would be appreciated. I am working on an application that will accept a TCP socket connection from a Java application. (Yes, Java is required on that part. It's a Sun SPOT device and Java...
The way we've solved this is to have a combination of sentinel characters and fixed width fields. The first two bytes are a length header for the entire packet. Then, I read the packet into a byte[] buffer and then rely on our own packet structure to know that, for instance, the first two bytes are each to be interpret...
"If the Java app writes data to the stream or there is a backlog of data (The Java app will be passing data rather quickly.) how can I make sure that I am reading only one packet of data at a time?" Be careful not to assume that you have any control over what data ends up in which packet. If you try to send the byte d...
What's the best way to monitor a socket for new data and then process that data?
[ "", "c#", "multithreading", ".net-3.5", "sockets", "sunspot", "" ]
As a sort of follow up to the question called [Differences between MSIL and Java bytecode?](https://stackoverflow.com/questions/95163/differences-between-msil-and-java-bytecode), what is the (major) differences or similarity in how the Java Virtual Machine works versus how the ~~.NET Framework~~ Common Language Runtime...
There are a lot of similarities between both implementations (and in my opinion: yes, they're both "virtual machines"). For one thing, they're both stack-based VM's, with no notion of "registers" like we're used to seeing in a modern CPU like the x86 or PowerPC. The evaluation of all expressions ((1 + 1) / 2) is perfo...
Your first question is comparing the JVM with the .NET Framework - I assume you actually meant to compare with the CLR instead. If so, I think you could write a small book on this (**EDIT:** looks like Benji already has :-) One important difference is that the CLR is designed to be a language-neutral architecture, unl...
Java's Virtual Machine and CLR
[ "", "java", ".net", "bytecode", "cil", "vm-implementation", "" ]
I have a table, with 2 important columns DocEntry, WebId Sample data is like ``` DocEntry WebId 1 S001 2 S002 3 S003 4 S005 ``` Now as we can notice here, in column WebId, S004 is missing. How can we locate such missing numbers, with a query. Further explanation: The web id should ...
A very simple approach :) ``` mysql> select * from test; +----------+-------+ | DocEntry | WebId | +----------+-------+ | 1 | S001 | | 2 | S002 | | 3 | S003 | | 4 | S005 | | 5 | S006 | | 6 | S007 | | 7 | S008 | | 8 | S010 | +----------+-------+ 8 rows in ...
There's a standard trick for generating integers that requires you to create a 10 row utility table viz: ``` create table Pivot (i int) insert into Pivot values (0) insert into Pivot values (1) insert into Pivot values (2) /* ... down to */ insert into Pivot values (9) ``` Once you've done this, then, for example...
Find missing values
[ "", "sql", "" ]
Do Pagemethods and Json have security risks?(I dont use cookies).Forexample i have a pagemethod and i am sending user id as a parameter but i dont want to show it to user.Can user get user id from pagemethod?
yes they can (see the user id). Any communication between the server and client can be seen by the user. Take a look with fiddler or firebug to see what goes on. You can treat it the same as any regular get or post request. I know of no reason why not to use it. Without knowing any of the background I can't give a def...
It has the same security risks as a regulat GET and POST, it is just another format to send the data back and forth. If you were using a regular POST, anyone would be able to see the userid just the same. So if you don't want to have people messing up with the userid you could add some sort of encrypted string depende...
JSON Security
[ "", "asp.net", "javascript", "security", "json", "" ]
I'm writing (in C#) a simple parser to process a scripting language that looks a lot like classic C. On one script file I have, the regular expression that I'm using to recognize /\* block comments \*/ is going into some kind of infinite loop, taking 100% CPU for ages. The Regex I'm using is this: ``` /\*([^*]|[\r\n...
Some problems I see with your regex: There's no need for the `|[\r\n]` sequences in your regex; a negated character class like `[^*]` matches everything except `*`, including line separators. It's only the `.` (dot) metacharacter that doesn't match those. Once you're inside the comment, the only character you have to...
No no no! Hasn't anyone else read Mastering Regular Expressions (3rd Edition)!? In this, Jeffrey Friedl examines this exact problem and uses it as an example (pages 272-276) to illustrate his "unrolling-the-loop" technique. His solution for most regex engines is like so: `/\*[^*]*\*+(?:[^*/][^*]*\*+)*/` However, if t...
Improving/Fixing a Regex for C style block comments
[ "", "c#", "c", "regex", "parsing", "comments", "" ]
I have an extension method on the HttpApplicationState object for getting my IoC container out of the application. This same code will also create the container if it doesn't exist. I have 2 questions: 1. Is my code actually thread safe as I intend it to be 2. Is this considered the best practice for dealing with the...
You need to put ``` var container = application[GlobalContainerKey] as IUnityContainer; ``` in the lock as well, otherwise many threads may create a new container in sequence. ``` private const string GlobalContainerKey = "UnityContainerKey"; private const object lockObject = new object(); public static IUnityConta...
Technically, that won't work given the EMCA specification. Jon Skeet goes into this in his C# FAQ: <http://www.yoda.arachsys.com/csharp/singleton.html> Specifically, see the section with the "Third version" I would read further down and use his suggestion for how to implement the singleton to see how to implement wh...
ASP.NET Threading - Double checked locking
[ "", "c#", "asp.net", "multithreading", "" ]
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate pa...
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/\*" by adding this to your `UrlMappings.groovy` file: ``` "/js/$action"{ controller = "javascript" } ``` then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, a...
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of ``` "/js/$action" ``` because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to. I...
Executing groovy statements in JavaScript sources in Grails
[ "", "javascript", "grails", "groovy", "" ]
I'm not considering this - I'm comfortable with C# and VB, but an expert in neither. But, some on my team have expressed an intention to do this since we're moving toward C# as a standard.
Hell's no. Just an absolute waste of time. I would use VB over C# (or C# over VB) only if the language enabled functionality that was not available in the other. For example, making late bound calls to COM interop objects is much easier in VB than it is in C# (although that is going to change in C# 4.0). That being ...
Sounds like a recipe for disaster or at least countless WTF-moments with no actual gains. .net Assemblies are compatible regardless of language (it's all IL at the end anyway), so there is no gain from that.
Would you develop in VB and then convert your code to C# just to have your entire team use one language?
[ "", "c#", "vb.net", "preferences", "" ]
I'm using SQL Server 2005. The query would look like this ``` Select col1, col2, col3 from <subquery> where (col1,col2) in <subquery> ``` SQL Server doesn't seem to like that. Any way of implementing that that anyone knows of that doesn't involve converting to varchars or anything else messy? This is the actual que...
You have to separate in two clauses ``` where col1 in (...) AND col2 in (...) ``` or you could refactor it a little bit ``` select * FROM ( SELECT NEWID() AS guid, UserID, RoleId, ClubId, 0 AS GroupRole FROM dbo.Portal_UserRoles UNION SELECT NEWID() AS guid, dbo.Portal_UserGroups.UserId, dbo.Portal...
The standard, classic way to do what you seek is an EXISTS clause: ``` SELECT * FROM ( SELECT NEWID() AS guid, UserID, RoleId, ClubId, 0 AS GroupRole FROM dbo.Portal_UserRoles UNION SELECT NEWID() AS guid, dbo.Portal_UserGroups.UserId, dbo.Portal_Grou...
"Where IN" with multiple columns (SQL Server)
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?
Based on your description in the comments, you'd simply do an array concat: ``` var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}]; var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}]; jsonArray1 = jsonArray1.concat(jsonArray2); // jsonArray1 = [{'name': "doug", 'id':5}, {'nam...
The actual way is using JS Object.assign. ``` Object.assign(target, ...sources) ``` [MDN Link](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) There is another object spread operator which is proposed for ES7 and can be used with Babel plugins. ``` Obj = {...sourceObj1,...
Concatenate two JSON objects
[ "", "javascript", "json", "" ]
Does anyone know of a c++ library for taking an image and performing image recognition on it such that it can find letters based on a given font and/or font height? Even one that doesn't let you select a font would be nice (eg: readLetters(Image image).
I've been looking into this a lot lately. Your best is simply Tesseract. If you need layout analysis on top of the OCR than go with Ocropus (which in turn uses Tesseract to do the OCR). Layout analysis refers to being able to detect position of text on the image and do things like line segmentation, block segmentation,...
While I cannot recommend one in particular, the term you are looking for is OCR (Optical Character Recognition).
C++ Library for image recognition: images containing words to string
[ "", "c++", "fonts", "ocr", "image-recognition", "" ]
I was browsing around for programming troubleshooters, and I was wondering what the alternate would be for Socket Programming; if there is one.
Assuming you have control over the protocol being used, you could go for a higher level of abstraction like .NET's Remoting or WCF.
[TCPClient](https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) and [UDPClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx) abstract you from the underlying sockets to some degree. They're nice to work with.
What are the alternatives to Socket Programming?
[ "", "c#", "sockets", "" ]
When programming in C++ against the browser's [DOM](http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.w3.org%2FDOM%2F&ei=eUhrSaTCDpyY9QSMr5imBw&usg=AFQjCNH0daWhsLwlt2sAqQJ71Vx8WtrHug&sig2=9eYS8DOTG8VOj3tJSKjyvg) each engine has a different set of interfaces, IE has the COM based [MSHTML](<htt...
Your best bet seems to be to define your own interface and write different adapters. In the likeliness that your C++ code won't be employing all DOM traversing capabilities, your interface will only have to define a compact set of traversal functions. As a bonus of defining your own interface, you can easily write a m...
I've never seen one. For my software, I simple wrote the extension in Firefox's javascript, and then created an Internet Explorer BHO (which I haven't finished yet).
Browser agnostic C++ DOM interface
[ "", "c++", "dom", "cross-browser", "" ]
I want to be able to pass something into an SQL query to determine if I want to select only the ones where a certain column is null. If I was just building a query string instead of using bound variables, I'd do something like: ``` if ($search_undeleted_only) { $sqlString .= " AND deleted_on IS NULL"; } ``` but I...
Yes; a related trick is if you have X potential filters, some of them optional, is to have the template say `" AND ( ?=-1 OR some_field = ? ) "`, and create a special function that wraps the execute call and binds all the second ?s. (in this case, -1 is a special value meaning 'ignore this filter'). Update from Paul T...
So you're relying on short-circuiting semantics of boolean expressions to invoke your `IS NULL` condition? That seems to work. One interesting point is that a constant expression like `1 = 0` that did not have parameters should be factored out by the query optimizer. In this case, since the optimizer doesn't know if t...
How can I select rows that are null using bound queries in Perl's DBI?
[ "", "sql", "perl", "dbi", "" ]
Is there a way to show the console in a Windows application? I want to do something like this: ``` static class Program { [STAThread] static void Main(string[] args) { bool consoleMode = Boolean.Parse(args[0]); if (consoleMode) { Console.WriteLine("consolemode started"); ...
What you want to do is not possible in a sane way. There was a similar question [so look at the answers](https://stackoverflow.com/questions/338951/output-to-command-line-if-started-from-command-line#339216). Then there's also an [insane approach](http://www.rootsilver.com/2007/08/how-to-create-a-consolewindow) (site ...
This is a tad old (OK, it's VERY old), but I'm doing the exact same thing right now. Here's a very simple solution that's working for me: ``` [DllImport("kernel32.dll", SetLastError = true)] static extern bool AllocConsole(); [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll...
Show Console in Windows Application?
[ "", "c#", "winforms", "console", "" ]
(I still feel like a complete newbie in MS Visual environments... so please bear with!) I'm using Microsoft Visual C# 2008 Express Edition. I have a project and in that project are two different forms. The .cs file for each form starts out: ``` using System; using System.Collections.Generic; using System.ComponentMo...
If you do something like: ``` namespace MyNameSpace { public class myclass { public myMethod() { // Code } } } ``` You will be able to instantiate and access it. If you change it to: ``` namespace MyNameSpace { public class myclass { public static myMet...
The short answer is that everything needs to be inside a class; I'd suggest you sit down with [a basic tutorial](http://www.csharp-station.com/Tutorial.aspx) to help you get to grips with the basics...
How do I add common C# code to a Visual C# 2008 Express project/solution?
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
I'd like to create a derived control from System.Windows.Forms.ComboBox that is bound to a list of objects that I retrieve from the database. Idea is other developers can just drop this control on their form without having to worry about the datasource, binding, unless they want to. I have tried to extend combobox and...
DesignMode property doesn't work in a constructor. From googling for a while, found this LicenseManager thing. ``` if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { // Do your database/IO/remote call } ``` However LicenseManager only works in constructors. For eventhandlers use DesignMode. Source: <...
The problem is that the designer actually does some compilation and execution in a slightly different context than normally running the program does. In the constructor, you can wrap your code in: ``` if (!DesignMode) { //Do this stuff } ``` That will tell the designer to not run any of your initialization code wh...
How to create a derived ComboBox with pre-bound datasource that is designer friendly?
[ "", "c#", "winforms", "combobox", "datasource", "designer", "" ]
Are there any nvl() equivalent functions in SQL? Or something close enough to be used in the same way in certain scenarios? --- UPDATE: no if statements no case statements no isnull no coalesce --- ``` select nvl (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; (expression) SODIUFOSDIUF...
You seem to be using Informix. AFAIK, there is DECODE there: `DECODE(field, NULL, 'it is null, man', field)` should give you same result as `NVL(field, 'it is null, man')` Please post exact name and version of the RDBMS you are using.
[ISNULL](http://msdn.microsoft.com/en-us/library/ms184325.aspx) (for a single replace) or [COALESCE](http://msdn.microsoft.com/en-us/library/ms190349.aspx) (Returns the first nonnull expression among its arguments.)
SQL nvl equivalent - without if/case statements & isnull & coalesce
[ "", "sql", "syntax", "informix", "null", "" ]
I have a `DataSet` populated from Excel Sheet. I wanted to use SQLBulk Copy to Insert Records in `Lead_Hdr` table where `LeadId` is PK. I am having following error while executing the code below: > The given ColumnMapping does not match up with any column in the > source or destination ``` string ConStr=Configuratio...
Well, is it right? Do the column names exist on both sides? To be honest, I've never bothered with mappings. I like to keep things simple - I tend to have a staging table that looks like the input on the server, then I `SqlBulkCopy` into the staging table, and finally run a stored procedure to move the table from the ...
I've encountered the same problem while copying data from access to SQLSERVER 2005 and i found that the column mappings are case sensitive on both data sources regardless of the databases sensitivity.
SqlBulkCopy Not Working
[ "", "c#", "asp.net", "sqlbulkcopy", "" ]
Here's the setup I have in a vs2008 solution: Data layer in a project named MyProject.Data Web application in a project named MyProject.Web MyProject.Web has a reference to MyProject.Data In MyProject.Web I have a class I use called "MySite.Utils" I want to be able to use MySite.Utils in MyProject.Data but I can't...
You need to move MySite.Utils to MyProject.Data by the sound of it
The best fix is to simplify things... for example, is that utility code *data* utility code, or *ui* utility code. Perhaps split it into 2 dlls; that might make things simpler. After that, interfaces are a reasonable option, but you might need some IoC framework to provide the implementations. IoC is the most common w...
vs2008 circular references (c#)
[ "", "c#", "asp.net", "visual-studio-2008", "" ]
Is it a good concept to use multiple inheritance or can I do other things instead?
Multiple inheritance (abbreviated as MI) *smells*, which means that *usually*, it was done for bad reasons, and it will blow back in the face of the maintainer. ## Summary 1. Consider composition of features, instead of inheritance 2. Be wary of the Diamond of Dread 3. Consider inheritance of multiple interfaces inst...
From an [interview with Bjarne Stroustrup](http://www.artima.com/intv/modern.html): > People quite correctly say that you don't need multiple inheritance, because anything you can do with multiple inheritance you can also do with single inheritance. You just use the delegation trick I mentioned. Furthermore, you don't...
Why should I avoid multiple inheritance?
[ "", "c++", "oop", "multiple-inheritance", "" ]
E,g ``` class Test { public: void setVal(const std::string& str) { this.isVal = str; //This will error out } private: string isVal; }; ```
In C++, `this` is a pointer (as opposed to a reference). So you have to say `this->isVal` instead.
Adding to [Chris's answer](https://stackoverflow.com/questions/467851/why-cant-we-use-this-inside-the-class#467853), you can also do: ``` (*this).isVal = str; ``` However, it's better to do what Chris said, as it is more orthodox. This is just illustrating that you need to de-reference the pointer before calling meth...
Why can't we use "this" inside the class?
[ "", "c++", "" ]
As an example, when inserting a record into a table with a unique index, is it best to test first? *e.g.*, ``` $mysqli->query('SELECT email FROM tblUser WHERE email = 'foo@bar.org'); ``` then make sure 0 rows are returned, *then* do the insert? ``` $mysqli->query('INSERT INTO tblUser ...'); ``` Or is it better to j...
It's better to insert and handle any duplicate key errors. The reason is that if you test first, some other client can still insert the value in the brief moment between your test and your insert. So you'd need to handle errors anyway.
Broadly speaking, there are three ways to handle this situation with a single query (fewer queries is usually a good thing to shoot for), but none of them is a universal "best way". Which you should use depends on your needs. The first is, as you mention, running the `INSERT …` blindly and handling any errors PHP. Thi...
MySQL Insert: Test first?
[ "", "php", "mysql", "database", "" ]
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string. How do I do this in C++?
Mehrdad Afshari's [answer](https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c#440147) would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders: ``` #include <ctime> #include <iostream> #include <unistd.h> std::string ...
Here's my adaptation of Ates Goral's answer using C++11. I've added the lambda in here, but the principle is that you could pass it in and thereby control what characters your string contains: ``` std::string random_string( size_t length ) { auto randchar = []() -> char { const char charset[] = ...
How do I create a random alpha-numeric string in C++?
[ "", "c++", "string", "random", "" ]
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure: ``` Server -server.py -Models --user.py ``` Here's the contents of server.py: ``` from ...
I believe you need to create a file called `__init__.py` in the Models directory so that python treats it as a module. Then you can do: ``` from Models.user import User ``` You can include code in the `__init__.py` (for instance initialization code that a few different classes need) or leave it blank. But it must be...
You have to create `__init__.py` on the `Models` subfolder. The file may be empty. It defines a package. Then you can do: ``` from Models.user import User ``` Read all about it in python tutorial, [here](http://docs.python.org/tutorial/modules.html#packages). There is also a good article about file organization of ...
Can't get Python to import from a different folder
[ "", "python", "python-2.x", "" ]
I'm writing an application where a user provides a connection string manually and I'm wondering if there is any way that I could validate the connection string - I mean check if it's correct and if the database exists.
You could try to connect? For quick (offline) validation, perhaps use `DbConnectionStringBuilder` to parse it... ``` DbConnectionStringBuilder csb = new DbConnectionStringBuilder(); csb.ConnectionString = "rubb ish"; // throws ``` But to check whether the db exists, you'll need to try to connect. Simplest if ...
Try this. ``` try { using(var connection = new OleDbConnection(connectionString)) { connection.Open(); return true; } } catch { return false; } ```
How to check if connection string is valid?
[ "", "c#", "connection-string", "" ]
Is there some way to make c++ dlls built with diffrent compilers compatible with each other? The classes can have factory methods for creation and destruction, so each compiler can use its own new/delete (since diffrent runtimes have there own heaps). I tried the following code but it crashed on the first member metho...
You should be able to mix modules built with different compilers if you lower your expectations and stick to simple functions. The way classes and virtual functions behave is defined by the C++ standard, but the way that's implemented is up to the compiler. In this case, I know that VC++ builds objects which have virt...
You're almost certainly asking for trouble if you do this - while other commenters are correct that the C++ ABI may be the same in some instances, the two libraries are using different CRTs, different versions of the STL, different exception throwing semantics, different optimizations... you're heading down a path towa...
Dll compatibility between compilers
[ "", "c++", "dll", "compiler-construction", "binary-compatibility", "" ]
Following code, when compiled and run with g++, prints '1' twice, whereas I expect '1' to be printed only once, since I am dumping a single structure to the file, but while reading back it seems to be reading two structures. Why? ``` #include <iostream.h> #include <fstream.h> int main(){ struct student { ...
`eof` only gets set after a read fails, so the read runs twice, and the second time, it doesn't modify the buffer. Try this: ``` while(filin.read((char*)&tmpStu,sizeof(tmpStu))) { cout << tmpStu.rollNo << endl; } ``` Or ``` while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof()) { cout << tmpStu.rollNo << ...
Your while loop is executing twice because the EOF condition is not true until the first attempt to read beyond the end of the file. So the cout is executed twice.
C++ file handling (structures)
[ "", "c++", "file", "file-io", "fstream", "" ]
I have a `List<List<int>>`. I would like to convert it into a `List<int>` where each int is unique. I was wondering if anyone had an elegant solution to this using LINQ. I would like to be able to use the Union method but it creates a new List<> everytime. So I'd like to avoid doing something like this: ``` List<int>...
``` List<List<int>> l = new List<List<int>>(); l.Add(new List<int> { 1, 2, 3, 4, 5, 6}); l.Add(new List<int> { 4, 5, 6, 7, 8, 9 }); l.Add(new List<int> { 8, 9, 10, 11, 12, 13 }); var result = (from e in l from e2 in e select e2).Distinct(); ``` ### Update 09.2013 But these days I would a...
``` List<int> result = listOfLists .SelectMany(list => list) .Distinct() .ToList(); ```
Convert List<List<T>> into List<T> in C#
[ "", "c#", "linq", "generics", "list", "union", "" ]
Would like to create a strong password in C++. Any suggestions? * I assume it should use alpha (upper and lower), numeric, special characters. * It would be good to be able to specify a minimum length. * It would be great to avoid characters that are hard to visually distinguish like "O" and "O" * It would b...
[APG](http://www.adel.nursat.kz/apg/download.shtml) (Automated Password Generator) implements all but your last requirement (no dictionary words / usernames / repeated characters). It includes both pronounceable and fully random password generation algorithms. Pronounceable passwords look something like this: ``` yevG...
There's a few ways. The easy isn't necessarily the best Create a string representing all the characters you want to define (meaning, no O's or 0s's, whatever), then fill a random-length string with random characters from that set. The next step is to keep generating until you pass all assertions. That is, check for d...
How do I create a strong password string in C++?
[ "", "c++", "string", "passwords", "" ]
I'm writing a Java Swing application using the Metal look-and-feel. Every time there is a JButton in my application the user uses the Tab key to move the focus to the button and then hits the Enter key. Nothing happens! If he hits the Space key the button events are fired. How do I assign the Enter key to trigger the s...
I found the following: <http://tips4java.wordpress.com/2008/10/25/enter-key-and-button/> Where Rob Camick writes that when using JDK5 and later you simply add... ``` UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); ``` ...to the application to solve the problem. This did the trick for me! And I can'...
Here is complete example. Richard was close, but you also need to map pressed ENTER to action, not just released. To make it work for ALL buttons, I have put this mapping to default input map for buttons. Add imports, and it should be runnable. --- ``` public class Main implements Runnable { public static void ma...
How do I assign Enter as the trigger key of all JButtons in my Java application?
[ "", "java", "swing", "events", "jbutton", "" ]
How come, in Java, I can write ``` List<?> list = new LinkedList<Double>(); ``` but not ``` List<Container<?>> list = new LinkedList<Container<Double>>(); ``` where Container is just something like ``` public class Container<T> { ... } ``` This came up because I have a method that accepts a `List<Container<?>>`, ...
Each parameterization must be wildcarded: ``` List<? extends Container<?>> list = new LinkedList<Container<Double>>(); ``` Edit: I was searching through [Angelika Langer's FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) for an explanation, but didn't find one (it's probably there, but hiding some...
> Edit: I was searching through Angelika Langer's FAQ for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages). Thank you very much for the answer. I found an explanation in the FAQ, and after some squinting at it I think I get it. <http://www.angelikalanger.com/GenericsFAQ...
Java generics: List<Container<?>> = new LinkedList<Container<Double>>() is prohibited?
[ "", "java", "generics", "" ]
Refering to a previously asked [question](https://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python "question"), I would like to know how to get the title of the current active document. I tried the script mention in the answers to the question above. This works, but only gi...
As far as I know your best bet is wrapping an AppleScript. But AppleScript is magic to me so I leave it as an exercise for the questioner :-) This might help a little: [A script to resize frontmost two windows to fill screen - Mac OS X Hints](http://hints.macworld.com/article.php?story=20060105082728937)
In Objective-C, the short answer, using a little Cocoa and mostly the [Carbon Accessibility API](https://developer.apple.com/library/mac/documentation/Accessibility/Reference/AccessibilityCarbonRef/Reference/reference.html) is: ``` // Get the process ID of the frontmost application. NSRunningApplication* app = [[NSWor...
Get the title of the current active Window/Document in Mac OS X
[ "", "python", "objective-c", "macos", "" ]
Here's the thing: I have two applications, written in C++ and running on two machines with different OS (one Linux and one Windows). One of this process is in charge of updating an XML file on a NAS (Network Attached Storage) while the other one reads this file. Is it possible to synchronize these two processes in ord...
You could create a lock file on the server that is created before you do a write, wait then write and delete on completion., Have the read process check for the token before reading the file. **Edit**: To address the comments, you can implement a double-checked locking type pattern. Have both reader and writer have a ...
Thank you all for your answers. At last we managed to resolve our problem, not by using locking commands of the OS (because we were not sure they would propagate correctly to the OS of the NAS head), but by creating lock directories instead of lock files. Directory creation is an atomic operation, and returns an error...
How can I synchronize two processes accessing a file on a NAS?
[ "", "c++", "concurrency", "synchronization", "mutex", "nas", "" ]
We have a table that looks roughly like this: ``` CREATE TABLE Lockers { UserID int NOT NULL PRIMARY KEY (foreign key), LockerStyleID int (foreign key), NameplateID int (foreign key) } ``` All of the keys relate to other tables, but because of the way the application is distributed, it's easier for us to pass ...
This missing feature seems to annoy a lot of people. * Good news: MS will address the issue with .NET 4.0. * Bad news: for now, or if you're stuck on 3.5 you have to do a little bit of work, but it IS possible. You have to do it like this: ``` Locker locker = new Locker(); locker.UserReference.EntityKey = new System...
What I've been doing to make things easy is adding the foreign key property myself in the partial class: ``` public int UserID { get { if (this.User != null) return this.User.UserID; } set { this.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", value); ...
Entity Framework: Setting a Foreign Key Property
[ "", "c#", "ado.net-entity-data-model", "" ]
I am having a similar issue to [this person](https://stackoverflow.com/questions/28387/sql-server-2k5-memory-consumption). The primary difference being the application is NOT meant for a developer environment, and therefore I need to know how to optimize the space used by Sql Server (possibly per machine based on specs...
Some applications allocate a lot of memory at startup, and then run their own memory management system on it. This can be good for applications that have particular allocation patterns, and that feel they can do a better job than the more generic memory manager provided by the runtime system. Many games do this, since...
It will depend on a few things - in particular the Operating System, and the language used. For instance, under MacOS Classic, it was impossible to have more memory allocated after startup - we used to have to go and modify how much memory was allocated using the Finder, and then restart the application. Those were th...
Requesting memory for your application
[ "", "c#", "sql-server-2005", "memory-management", "" ]
In C#, what makes a field different from a property, and when should a field be used instead of a property?
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class. ``` public class MyClass { ...
Object orientated programming principles say that, the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. Therefore we wrap fields with Properties (or methods in Java's case) to give us the ability to change th...
What is the difference between a field and a property?
[ "", "c#", "oop", "properties", "field", "" ]
I'm trying to convert an Enum array to an int array: ``` public enum TestEnum { Item1, Item2 } int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32)); ``` For some reason Convert.ToInt32 doesn't work when used in Array.ConvertAll, so I had to make some changes: ``` ...
Just cast using an anonymous method: ``` int[] result = Array.ConvertAll<TestEnum, int>( enumArray, delegate(TestEnum value) {return (int) value;}); ``` or with C# 3.0, a lambda: ``` int[] result = Array.ConvertAll(enumArray, value => (int) value); ```
Luckily for us, C# 3.0 includes a `Cast` operation: ``` int[] result = enumArray.Cast<int>().ToArray(); ``` If you stop using arrays and start using `IEnumerable<>`, you can even get rid of the `ToArray()` call.
Convert an array of 'enum' to an array of 'int'
[ "", "c#", ".net", "" ]
I often find myself writing a property that is evaluated lazily. Something like: ``` if (backingField == null) backingField = SomeOperation(); return backingField; ``` It is not much code, but it does get repeated a lot if you have a lot of properties. I am thinking about defining a class called LazyProperty: ``...
Just to be overly pedantic: Your proposed solution to avoid repeating code: ``` private LazyProperty<HeavyObject> first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value }); public HeavyObject First { get { return first; } } ``` Is actually more characters than the code that y...
**Don't do it at all.** Generally using this kind of lazy initialized properties is a valid design choice in one case: when `SomeOperation();` is an expensive operation (in terms of I/O, like when it requires a DB hit, or computationally) AND when you are certain you will often NOT need to access it. That said, by de...
Implementing a "LazyProperty" class - is this a good idea?
[ "", "c#", ".net", "lazy-evaluation", "" ]
I intend to develop a small (Java) application for managing my finances. I believe I need to use an embedded database, but I have no experience regarding this issue. I tried to look at [some of the available products](http://java-source.net/open-source/database-engines), but I can't decide which one would be more suita...
Either * [HSQLDB](http://hsqldb.org/) - Used by OpenOffice, tested and stable. It's easy to use. If you want to edit your db-data, you can just open the file and edit the insert statements. or * [H2](http://www.h2database.com/html/main.html) - Said to be faster (by the developer, who originally designed hsqldb, too)...
I use [Apache Derby](http://db.apache.org/derby/) for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've h...
Java Embedded Databases Comparison
[ "", "java", "database", "comparison", "embedded-database", "" ]
I'm reading a [post](http://savoysoftware.com/blog/?p=114) about iPhone programming and I've noticed that the talk about Objective C++, the code shown in the post looks mainly like Objective-C but there also are several snippets in C++. Is it really possible to program Cocoa from C++?
In addition to the other comments, I would add that Objective-C++ is not exactly the same as "program Cocoa from C++" because there is no C++ to Cocoa bridge involved. In Objective-C++, you program the Cocoa API entirely with Objective-C objects/syntax. The Cocoa API remains unchanged, so you need to communicate with ...
Yes. Basically, Objective-C is a set of Smalltalk like object extensions to C. Objective C++ is the result of applying those same extensions to C++. This leaves you with a language with two different object models. Apple's xcode development environment provides both an Objective-C and Objective-C++ compiler.
There is really something like Objective C++?
[ "", "c++", "objective-c", "cocoa", "macos", "objective-c++", "" ]
Some time ago I wrote a little piece of code to ask about on interviews and see how people understand concepts of cache and memory: ``` #include "stdafx.h" #include <stdlib.h> #include <windows.h> #include <iostream> #define TOTAL 0x20000000 using namespace std; __int64 count(int INNER, int OUTER) { int a = 0; ...
Probably because 64 is the cache line size on your machine, and you basically run each iteration fully out of a single cache line.
I'm not sure what you're asking. Are you just checking what we know? Why bother? Or are you asking us because you can't explain the boost at 64bytes yourself? Or is it to find out if this is a good interview question, or...? Anyway, If the intention is simply to provide a background for your interview question, you sh...
Cache, loops and performance
[ "", "c++", "performance", "memory", "caching", "" ]
I'm looking to use: ``` #define ``` and ``` #if ``` to allow me to simulate potentially absent hardware during unit tests. What are the rules for using the `#define` statements? i.e. what is its default scope? can I change the scope of the directive?
As Chris said, the scope of #define is just the file. (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't! You can also define a symbol project-wide, but that's done with [project properties](http...
From [MSDN](http://msdn.microsoft.com/en-us/library/yt3yck0x(VS.71).aspx), its scope is the file
c# Pre-processor directive scope
[ "", "c#", "scope", "c-preprocessor", "preprocessor-directive", "" ]
How would I get the last item (or any specific item for that matter) in a simplexml object? Assume you don't know how many nodes there will be. ex. ``` <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/xsl.xml"?> <obj href="http://xml.foo.com/" display="com.foo.bar" xmlns:xsi="ht...
Use XPath's `last()` function, which solves this very problem: ``` <?php $xml = simplexml_load_file('HistoryRecord.xml'); $xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0'); $xpath = "/o:obj/o:list/o:obj[last()]/o:int[@name = 'energy_in_kwh']"; $last_kwh = $xml->xpath($xpath); ?> ``` Here it looks...
There is a XPath expression that'll do exactly what you want: ``` $xml='<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/xsl.xml"?> <obj href="http://xml.foo.com/" display="com.foo.bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://obix.org/ns/schema/1.0" > <list na...
PHP SimpleXML. How to get the last item?
[ "", "php", "xml", "simplexml", "" ]
I need to set the properties of a class using reflection. I have a `Dictionary<string,string>` with property names and string values. Inside a reflection loop, I need to convert the string value to the appropriate property type while setting the value for each property. Some of these property types are nullable types...
1. One way to do this is: ``` type.GetGenericTypeDefinition() == typeof(Nullable<>) ``` 2. Just set is as per any other reflection code: ``` propertyInfo.SetValue(yourObject, yourValue); ```
Why do you need to know if it is nullable? And do you mean "reference-type", or "`Nullable<T>`"? Either way, with string values, the easiest option would be via the `TypeConverter`, which is more-easily (and more accurately) available on `PropertyDescriptor`: ``` PropertyDescriptorCollection props = TypeDescriptor.Ge...
how to set nullable type via reflection code ( c#)?
[ "", "c#", "reflection", "" ]
I have a method in a C++ interface that I want to deprecate, with portable code. When I Googled for this all I got was a Microsoft specific solution; [`#pragma deprecated`](https://learn.microsoft.com/en-us/cpp/preprocessor/deprecated-c-cpp?view=vs-2017) and [`__declspec(deprecated)`](https://learn.microsoft.com/en-us...
In C++14, you can mark a function as deprecated using the `[[deprecated]]` attribute (see section 7.6.5 [dcl.attr.deprecated]). > The *attribute-token* `deprecated` can be used to mark names and entities whose use is still allowed, but is discouraged for some reason. For example, the following function `foo` is depre...
This should do the trick: ``` #ifdef __GNUC__ #define DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(func) __declspec(deprecated) func #else #pragma message("WARNING: You need to implement DEPRECATED for this compiler") #define DEPRECATED(func) func #endif ... //don't u...
How can I mark a C++ class method as deprecated?
[ "", "c++", "deprecated", "portability", "" ]
We're using RSpec and Cucumber in our Rails apps with good results. Webrat is great for non-AJAX interactions, but we're getting ready to get back into writing tests for our Javascript. Webrat has Selenium support built in, and we've used Selenium before, but I'm curious if anyone has had good results using Watir with...
As the founder of OpenQA and Selenium RC, I'm obviously biased towards Selenium as a good option. We recently just put out a 1.0 beta 2 release and are very close to a 1.0 final. However, you couldn't go wrong with Watir/FireWatir either. Adam's comment that WebDriver will merge to form Selenium 2.0 is correct, but he...
I am having good results using Cucumber with Celerity through JRuby. Celerity is a headless browser which wraps around HtmlUnit with a Watir-compatible API and supports JavaScript and AJAX testing. Being headless makes Celerity faster and easy to integrate within a Continuous Integration build cycle. Since Celerity ...
Selenium or Watir for Javascript Testing in Rails
[ "", "javascript", "ruby-on-rails", "ajax", "testing", "selenium", "" ]
I have this method Verify\_X which is called during databind for a listbox selected value. The problem is the strongly typed datasource. I want to use the abstract class BaseDataSource or an interface to call the methods supported: Parameters[] and Select(), Instead of using the most specific implementation as seen bel...
If you are unable to alter the class definition or to use some sort of extension methods, you can use Reflection. Here is a sample that I worked up using assumptions about your code: ``` public static string Verify(string valueToBind, object dataSource) { ////what is the correct way to convert from obj...
Thanks John you really put me on the right path there. I ended up with the following code: ``` public string Verify(string valueToBind, object dataSource) { IListDataSource listDataSource = dataSource as IListDataSource; if (listDataSource != null) { if (ListContainsValue(li...
Casting to abstract class or interface when generics are used
[ "", "c#", "reflection", "casting", "abstract-class", "generics", "" ]
My comfort level with java is good , I wanted to teach my friend C# (where I would not consider myself expert in anyway). From the perspective of interviews what should I be studying/implementing myself in C# before i can teach her from an interview perspective. I am not a big fan of a language specific interviews but ...
I tend to take the view that the things you should know for an interview are the things you need to know for core development - at least if the interviewer is any good. So, for C# I would make sure you're comfortable with: * Properties * Reference types vs value types * Parameter passing (what ref means etc) * Generi...
Well, firstly I'd try to avoid mistakes due confusion with java concepts (since you're from a java background). For example: * int/Int32 (etc): in C# they are the same * generics: how they differ from java * delegates/events: don't exist in java * closures: java captures the *value*; C# captures the *variable* (allowi...
How should I teach my friend C#?
[ "", "c#", "" ]
I need to get the version information of a DLL file I created in Visual Studio 2008 C++. How do I get it?
Thanks for the answers. This worked for me: ``` WCHAR fileName[_MAX_PATH]; DWORD size = GetModuleFileName(g_dllHandle, fileName, _MAX_PATH); fileName[size] = NULL; DWORD handle = 0; size = GetFileVersionInfoSize(fileName, &handle); BYTE* versionInfo = new BYTE[size]; if (!GetFileVersionInfo(fileName, handle, size, ve...
If you want programmatic access, see [Version Information](http://msdn.microsoft.com/en-us/library/ms646981(VS.85).aspx) in MSDN for the APIs and data structures you need.
How to get the version information of a DLL file in C++
[ "", "c++", "windows", "dll", "version", "" ]
String's in C# are immutable and threadsafe. But what when you have a public getter property? Like this: ``` public String SampleProperty{ get; private set; } ``` If we have two threads and the first is calling 'get' and the second is calling 'set' at the "same" time, what will happen? IMHO the set must made...
Most of the answers are using the word "atomic" as if atomic changes are all that are needed. They're not, usually. This has been mentioned in the comments, but not usually in the answers - that's the only reason for me providing this answer. (The point about locking at a coarser granularity, to allow things like appe...
A reference-type field's get/set (ldfld/stfld) is (IIRC) guaranteed to be atomic, so there shouldn't be any risk of corruption here. So it should be thread-safe from **that** angle, but personally I'd lock the data at a higher level - i.e. ``` lock(someExternalLock) { record.Foo = "Bar"; } ``` or maybe: ``` lock...
Is a string property itself threadsafe?
[ "", "c#", "multithreading", "" ]
The if keyword in the following statement is underlined in green by ReSharper: ``` if (readOnlyFields.Contains(propertyName)) return false; return base.CanWriteProperty(propertyName); ``` ReSharper suggests the following change: ``` return !readOnlyFields.Contains(propertyName) && base.CanWriteProperty(propert...
Neither one is better in the sense that either one will perform better than the other. (Any difference is going to be entirely negligible.) Certain coding conventions suggest that you use one return statement per function so that it's easy to understand it's flow. It's not a hard and fast rule though and in this case ...
On the quick fix menu (Alt+Enter), there's a "Correction options" (or something like that). You can turn this specific suggestion into a hint, or turn it off entirely. On a personal note, I prefer your original over ReSharper's suggestion.
ReSharper syntax suggestion
[ "", "c#", "visual-studio-2008", "syntax", "resharper", "" ]
Why does the following code NOT give an error, nor any type of a warning about an implicit conversion? ``` std::wstring str = L"hi"; if(str[0] == 'h') cout<<"strange"<<endl; ``` The proper normal code is: ``` std::wstring str = L"hi"; if(str[0] == L'h') cout<<"strange"<<endl; ``` Compiler: visual studio...
It doesn't give a warning because the comparison is valid. In general, you can always compare integral types, they just get promoted to wider types as needed. And I'm pretty sure some compilers would issue a warning about this. Which one are you using? (In any case, warnings are compiler-specific, and they're not requ...
> Why does the following code NOT give an error ... Isn't it because C++ allows implicit conversions? For example, isn't the following also legal: ``` if (str[0] == 104) //C++ allows various implicit type conversions ``` > ... nor any type of a warning about an implicit conversion? That question is compiler-specifi...
unicode char comparing to non unicode char, but no warning nor error
[ "", "c++", "string", "unicode", "" ]
**Closed as exact duplicate of [this question](https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton). But reopened, as the other Singleton questions are for general use and not use for DB access** I was thinking of making an internal data access class a Singleton but couldn't convinc...
I've found that the singleton pattern is appropriate for a class that: * Has no state * Is full of basic "Service Members" * Has to tightly control its resources. An example of this would be a data access class. You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate th...
As one example, **object factories** are very often good candidates to be singletons.
In what circumstances should I use a Singleton class?
[ "", "c#", ".net", "design-patterns", "oop", "" ]
Just curious: * 4 instanceof Number => false * new Number(4) instanceof Number => true? Why is this? Same with strings: * `'some string' instanceof String` returns false * `new String('some string') instanceof String` => true * `String('some string') instanceof String` also returns false * `('some string').toString ...
`value instanceof Constructor` is the same as `Constructor.prototype.isPrototypeOf(value)` and both check the [[Prototype]]-chain of `value` for occurences of a specific object. Strings and numbers are **primitive values**, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in re...
You may try to evaluate: ``` >>> typeof("a") "string" >>> typeof(new String("a")) "object" >>> typeof(4) "number" >>> typeof(new Number(4)) "object" ```
Why is 4 not an instance of Number?
[ "", "javascript", "" ]
the two bits of SQL below get the same result ``` SELECT c.name, o.product FROM customer c, order o WHERE c.id = o.cust_id AND o.value = 150 SELECT c.name, o.product FROM customer c INNER JOIN order o on c.id = o.cust_id WHERE o.value = 150 ``` I've seen both styles used as standard at different compan...
Both queries are an inner joins and equivalent. The first is the older method of doing things, whereas the use of the JOIN syntax only became common after the introduction of the SQL-92 standard (I believe it's in the older definitions, just wasn't particularly widely used before then). The use of the JOIN syntax is s...
To answer part of your question, I think early bugs in the JOIN ... ON syntax in Oracle discouraged Oracle users away from that syntax. I don't think there are any particular problems now. They are equivalent and should be parsed into the same internal representation for optimization.
SQL INNER JOIN syntax
[ "", "sql", "syntax", "inner-join", "cross-join", "" ]
Our java applet needs to open a new htm page to web browser but popup blocker seem to block this code: ``` try { AppletContext a = getAppletContext(); URL url = new URL(link); a.showDocument(url,"_blank"); } ``` can you use somehow live javascript to open a window instead?
`AppletContext` show document is implemented by doing the JavaScript call. However, the context the popup blocker is using will probably be absent. If the click happens outside of an applet you can use only JavaScript to open the popup, but using a URL supplied by the applet (so the applet never has to call out to Java...
I'm probably not being helpful, but a popup blocker's task is to block popups. If there was a way to fool it, it would not be a good blocker after all. You will have to advise your users to disable the popup blocker to use your application.
Can Applet open a new HTML window *and* bypass popup blocker?
[ "", "java", "applet", "" ]
We have a static method in a utility class that will download a file from a URL. An authenticator has been set up so that if a username and password is required, the credentials can be retrieved. The problem is that the credentials from the first successful connection are used for every connection afterwords, as long a...
I've figured something out at least. It appears that this behavior is a [bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=6626700). A workaround is to use a Sun specific class to explicitly reset the cache, like so: ``` import sun.net.www.protocol.http.AuthCacheValue; import sun.net.www.protocol.http.AuthCacheIm...
Facing the same problem, none of these answers worked for me. It took me some time and looking through the java runtime source to figure this out. Sun.net.www.protocol.http.ntlm.NTLMAuthentication attempts to use transparent authentication, what is basically use of current user credentials to login to remote server. In...
Reset the Authenticator credentials
[ "", "java", "" ]
I am trying to pass a number to my JavaScript function, but actually a wrong value is getting passed. I am giving the entire code here: ``` <html> <head> <script type="text/javascript"> function test(num) { /*It should alert as 01004 or 1004 but to my surprise it's alerting as 516!*/ alert(num); } </script> </head> <b...
A numeric literal that starts with a zero is interpreted as octal, so writing 01004 is *exactly* the same as writing 516. Some other answers suggesting using parseInt inside the function to convert the octal value to decimal. This wont help, as the numeric value 516 is passed to the function. If you ask parseInt to g...
The leading zero is probably making it think the number is octal. UPDATE: Thanks to @Paul Dixon for jogging my mind awake somewhat this morning. `01004` is a literal, so no amount of after-the-fact parsing, i.e., `parseInt`, is going to update the base of the number. You need to either strip the leading `0` in your co...
JavaScript function parameter
[ "", "javascript", "function", "types", "parameters", "" ]
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C# ``` [DllImport("coredll.dll", EntryPoint = "RegSetValueExW")] public static extern int RegSetValueExW(uint hKey, string lpValueName, uint lpReserved, uint lpType, byte[] lpData, uint lpcbD...
I've got to start by asking why you are using PInvoke here when there is already a method for setting registry values in the Microsoft.Win32.RegistryKey class? Or are you stuck using an old version of the Compact Framework? Assuming you have a good reason for the PInvoke, the easiest answer is just to overload the PIn...
Use REG\_DWORD instead of REG\_SZ and then use BitConverter.GetBytes(Int32) to convert the int to a byte[].
How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke
[ "", "c#", "interop", "registry", "" ]
I have an image with two points, aligned something like this: ``` |----------------| | | | . | | | | . | | | |----------------| ``` I have both X, Y coordinates for both points and I need to rotate the image X degrees so it looks like this instead...
It depends on which point you want to use as a "center" for your rotation. Let's call the point to the up and left pointA and the one to the right and below pointB. If you want to rotate around the point A so that point B aligns with it, calculating the rotation angle in radians would go like this: ``` double angle = ...
No code, sorry, but a stratagy. You need to be able to create the result image by sampling the the source image. You know the angle of rotation, so you now need to create a mapper function which maps from the result back to the original. The code would simply scan each row of the result image, and map the pixel back ...
Rotate image math (C#)
[ "", "c#", "math", "image", "rotation", "" ]
I'm working on a multi-threaded Silverlight application. The application has two threads: Main/UI and a background working thread. The UI thread should be able to kill the background thread, like so: ``` private Thread executionThread; .... executionThread = new Thread(ExecuteStart); executionThread.Start(); .......
Rather than creating a Thread manually for this purpose you might want to consider using the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.95).aspx) class. This class has built in functionality for cancelling the asynchronous operation when WorkerSupportsCancellat...
It's documented, see [Thread.Abort()](http://msdn.microsoft.com/en-us/library/ty8d3wta(VS.95).aspx) > This member has a > SecurityCriticalAttribute attribute, > which restricts it to internal use by > the .NET Framework for Silverlight > class library. Application code that > uses this member throws a > MethodAccessEx...
Unable to kill a worker thread in Silverlight
[ "", "c#", ".net", "silverlight", "multithreading", "" ]
The median of five is sometimes used as an exercise in algorithm design and is known to be computable **using only 6 comparisons**. What is the best way to implement this **"median of five using 6 comparisons"** in C# ? All of my attempts seem to result in awkward code :( I need nice and readable code while still usin...
This is basically just factoring out the swapping and sorting code from your C++ example: ``` private static void Swap(ref double a, ref double b) { double t = a; a = b; b = t; } private static void Sort(ref double a, ref double b) { if (a > b) { double t = a; a = b; b = t; ...
I found this post interesting and as an exercise I created this which ONLY does 6 comparisons and NOTHING else: ``` static double MedianOfFive(double a, double b, double c, double d, double e) { return b < a ? d < c ? b < d ? a < e ? a < d ? e < d ? e : d : c < a ? ...
How do I calculate the "median of five" in C#?
[ "", "c#", "algorithm", "readability", "median", "" ]
I have a SqlCommand object, and I execute its ExecuteNonQuery method. The query fails, but I can't see how to obtain the query to debug it. Could you help me? **Update** I am currently using Wireshark (tcpdump) to read the command, but I think that its not the best solution **Update** The CommandText property only pr...
You can use SQL Profiler to see what is the query/call to stored procedure being sent along with parameterrs.
You can get the value of the CommandText property of your SqlCommand ? If an exception is thrown, you can catch it, and access the CommandText property which will give you the SQL command like you've set it. Offcourse, if it contains parameters, the parameters won't be replaced by the appropriate values.
How to obtain the IDbCommand output to the DB? (.NET)
[ "", "c#", ".net", "sqlcommand", "idbcommand", "" ]
This is a followup question to this question: [select all contents of textbox when it receives focus (Javascript or jQuery)](https://stackoverflow.com/questions/480735/select-all-contents-of-textbox-when-it-receives-focus-javascript-or-jquery) Basically I am using a textbox in conjunction with the [jQuery masked inpu...
I'm the author of the [Masked Input Plugin](http://digitalbush.com/projects/masked-input-plugin/) for jQuery. I decided that this should be the default behavior for completed masks and I got it into the latest release. You can read the details [here](http://digitalbush.com/2009/03/10/masked-input-plugin-122/)
Hey Jon, not too sure about the performance of this, but this should work: ``` $(function() { // Contents of textboxes will be selected when receiving focus. $("input[type=text]") .focus(function() { var mask = "99/99/9999"; $(this).unmask(mask).select(...
jQuery masked input plugin. select all content when textbox receives focus
[ "", "javascript", "jquery", "jquery-plugins", "" ]
I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-p...
As it hasn't been mentioned yet: [jQuery.UI](http://ui.jquery.com/)
You could look at [ext.js](http://extjs.com) - it provides lots of widgets to GetThingsDone quickly.
What is a good Very-High level UI framework for JavaScript?
[ "", "javascript", "user-interface", "" ]
I've been playing around with ASP.NET MVC with a site containing a Master Page. I created an MVC user control called `ProductThumbnailControl`. The user control displays a product and a small thumbnail image. The View is a `ViewProduct` view which displays full product information - the usercontrol just being a UI ele...
Our master page takes data from the view. We use [strongly typed view names](http://oddiandeveloper.blogspot.com/2008/11/strongly-typed-view-names.html) for our views and in the methods for that implementation we also add standard view data that every page needs from our persistent objects (like the application menu st...
Looks like my solution is very similar to Microsoft's recommendation with one key exception. I was creatng a ViewData baseclass, and they create a Controller baseclass - which makes a lot more sense. However it seems that both ideas could (and should) work in tandem. The MS tutorial below uses a dictionary to store vi...
Should an ASP.NET masterpage get its data from the view?
[ "", "c#", ".net", "asp.net-mvc", "" ]
I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file. I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.
I am doing this in a perl/cgi program. I use these in the top of my code: ``` use CGI qw(:standard); use JSON; ``` Then I print the json header: ``` print header('application/json'); ``` which is a content type of: ``` Content-Type: application/json ``` And then I print out the JSON like this: ``` my $json->{"e...
Even if you specify the type "application/json" you still need to parse the text. jQuery do this for you, using the $.getJSON function,ie: ``` $.getJSON("http://someurl.com/blabla.json",{some: "info"},function(json){ alert(json["aKey"]["anotherOne"]); }); ``` (here the [specs](http://docs.jquery.com/Ajax/jQuery.get...
How can I send a JSON response from a Perl CGI program?
[ "", "javascript", "perl", "json", "" ]
I was browsing through "Text Processing in Python" and tried its [example](http://gnosis.cx/TPiP/038.code) about Schwartzian sort. I used following structure for sample data which also contains empty lines. I sorted this data by fifth column: 383230 -49 -78 1 **100034** '06 text' 9562 'text' 720 'text' 867 335067 ...
I don't know what is the question, so I'll try to clarify things in a general way. This algorithm sorts lines by getting the 4th field and placing it in front of the lines. Then built-in `sort()` will use this field to sort. Later the original line is restored. The lines empty or shorter than 5 fields fall into the `...
Not directly related to the question, but note that in recent versions of python (since 2.3 or 2.4 I think), the transform and untransform can be performed automatically using the `key` argument to `sort()` or `sorted()`. eg: ``` def key_func(line): lst = string.split(line) if len(lst) >= 4: ...
Schwartzian sort example in "Text Processing in Python"
[ "", "python", "" ]
1) How important is it for the site to be accessible without javascript? I'm using a lot of ajax. I converted most of the site to be accessible without js, but the effort involved left me wondering if it was worth it. 2) What are the sort of scenarios (that occur fairly often) in which javascript might be turned off? ...
The most common non-accessible non-paranoid reason why JS would be disabled is when search engine bots come to index the content. You need to be able to handle that if you want to be listed properly on search engines. EDIT for your edit: Fair enough. It really depends on your site's features. If it's a primarily infor...
**The Importance of Being Accessible** It may be very important for your website to be highly accessible, especially if the site is being built for an organization which is subsidized by federal dollars. The Rehabilitation Act was ammended in 1998, and now *requires* Federal agencies to make their electronic and info...
ajax and accessibility
[ "", "javascript", "accessibility", "" ]
I thought it should be a config file, but cannot find it. thanks
If you're talking about .Net settings, then they will normally be in a .config (xml) file in the same directory as the application. When you save them, however, a local copy gets saved in to a user writable folder (typically C:\Users\username\AppData\Local under Vista). Under XP, look in the Documents and Settings fold...
The whole config file location can be a bit slippery. Depending on whether or not its a "user" setting or an "application" setting, it will go into a different file. Some settings can even come from your "machine" config (Like in the case of ASP.NET). Instead of guessing where everything is, I find it much more useful ...
where property.setting value stored in c# windows application
[ "", "c#", "windows", "" ]
I need some help ... I'm a bit (read total) n00b when it comes to regular expressions, and need some help writing one to find a specific piece of text contained within a specific HTML tag from PHP. The source string looks like this: ``` <span lang="en">English Content</span><span lang="fr">French content</span> ... e...
There are plenty of HTML parsers available for PHP. I suggest you check out one of those, (for example: [PHP Simple HTML DOM Parser](http://sourceforge.net/projects/simplehtmldom/)). Shooting yourself in the foot with trying to read HTML with regex is a lot easier than you think, and a lot harder to avoid than you wis...
There's this most awesome class that lets you do SQL-like queries on HTML pages. It might be worth a look: [HTML SQL](http://www.phpclasses.org/browse/package/3086.html) I've used it a bunch and I love it. Hope that helps...
PHP regex to get contents of a specific span element
[ "", "php", "regex", "" ]
All I need is to be able to detect when text is dropped into a Textarea. I then take that text and do stuff with it and clear the textarea. There may be many of these textareas and very high UI expectations, so polling is a last resort. For IE, "onfocus" does the trick, since this event is fired after the user drops s...
Polling seems to be the only way to go. When a Drag+Drop operation is started within the browser, it seems to cancel out everything else that's going on. You can witness this by putting "onmouseover" events on something on the page, then starting a DnD operation and dragging over it. The events will not fire. It seem...
For Firefox, this works for me: ``` window.addEventHandler("dragdrop", function(event) {alert("Drop it like it's hot!")}, true) ``` Does not work in Safari, however. Haven't tried IE.
Detecting drop into textarea with Javascript
[ "", "javascript", "drag-and-drop", "textarea", "detect", "" ]
For simplicity, i have the following file named test.jsp: ``` <script language="javascript"> alert("a$b".replace(/\$/g,"k")); </script> ``` I put this file in my local server, then display it using firefox: <http://localhost:8080/myproj/test.jsp>. It works okay, the result alert string is: ``` akb ``` But when...
JSP 2.0 Spec says: "When EL evaluation is disabled, \$ will not be recognized as a quote, whereas when EL evaluation is enabled, \$ will be recognized as a quote for $." (JSP.3.3.2) Whether EL Evaluation is enabled or disabled depends on many things: * if application server supports JSP 2.0 (Tomcat 5.0 and higher doe...
Maybe you can move the javascript code to a separate .js file? This will prevent the code from being interpreted as jsp.
Javascript String.replace(/\$/,str) works weirdly in jsp file
[ "", "javascript", "regex", "jsp", "tomcat", "el", "" ]
Do you know of an "easy" way to store and retrieve objects in Java **without using a relational DB / ORM like Hibernate**? [*Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of it...
I guess I have found a sort of answer to my question. Getting the document-oriented paradigm mindset is no easy task when you have always thought your data in terms of relationships, normalization and joins. [CouchDB](http://couchdb.apache.org) seems to fit the bill. It still could act as a key-value store but its gr...
* [Object Serialization](http://www.mactech.com/articles/mactech/Vol.14/14.04/JavaSerialization/index.html) (aka storing things to a file) * [Hibernate](http://www.hibernate.org/) (uses a relational database but it is fairly transparent to the developer) I would suggest Hibernate because it will deal with most of the ...
Easy way to store and retrieve objects in Java without using a relational DB?
[ "", "java", "persistence", "relational", "" ]
Ok, here's a problem script. ``` var links = [ 'one', 'two', 'three' ]; for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.onclick = function() { alert( i ) } document.body.appendChild( a ); } ``` This script generates three divs: one, two and...
You need to use this little closure trick - create and execute a function that returns your event handler function. ``` var links = [ 'one', 'two', 'three' ]; for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.onclick = (function(i) { return functi...
I'd stay with your own solution, but modify it in the following way: ``` var links = [ 'one', 'two', 'three' ]; function handler() { alert( this.i ); } for( var i = 0; i < links.length; i++ ) { var a = document.createElement( 'div' ); a.innerHTML = links[i]; a.i = i; //set a property of the current e...
How can one de-reference JavaScript variables when enclosing an outer scope
[ "", "javascript", "scope", "" ]
We have some auto-generated resource files in our project in Visual Studio 2008, with some localized versions, and in one of these localized versions, there is a string which in this case is empty. More explicit. We have a core resource file, with lots of string resources. We then have 4 other localized versions of th...
You might try creating a string resource empty\_string, defined as "" for every locale. If you make it the first resource, the form designer will (hopefully) always pick that one as the value to sprinkle through your forms. This way at least you'll be using a string designated for that purpose.
If the problem is being caused by an empty string in the resource file, what would the effect be of making it a space. So instead of "" the resource file contains " ". I don't know if that's the best solution but I would be interested to know if it stops the designer from using that resource as a default empty string. ...
Resources in project file in VS2008 gets "reused" creatively by the form designer, possible to avoid?
[ "", "c#", "visual-studio-2008", "resources", "form-designer", "" ]
I decided to use LINQ to SQL in my personal project after hearing lots of goods. Is there any thing I need to taken care before start using it (during initial design)?
**EDIT** Completely rewritten as earlier post was misleading - apologies. There has been much rumour that Microsoft will not be taking Linq2Sql any further. Fuelled by an [ADO.Net team blog post](http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx). Following that t...
See [What’s wrong with Linq to SQL?](https://stackoverflow.com/questions/165102/whats-wrong-with-linq-to-sql)
LINQ to SQL: What gives pain?
[ "", ".net", "sql", "linq", "linq-to-sql", "" ]
HI, I am trying to convert the following vba code to c# and i am facing some errors.Hope someone can help me vba code ``` Open "C:\testfile.txt" For Input As #1 varii = "" Do While Not EOF(1) Line Input #1, strField varii = varii & "," & strField Loop Close #1 ...
In converting bear in mind that VBA uses the same operator () for indexes and method calls, whereas C# uses [] for indexes and () for calls to methods. ``` split(intix) ``` should be ``` split[intix] ``` Try ``` rs.Fields("Table_Name").Value.ToString().Substring(0,4), but check the length first. ie rs.Fields("T...
If you add `using VB = Microsoft.VisualBasic;` namespace on top you can use `VB.Left()` instead of `Microsoft.Vbe.Left()`
C#. How to excecute a query on recordset?
[ "", "c#", "" ]
I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so ``` biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio'...
Index on the fields you want to use for lookup. O(n+m) ``` matches = [] biglist1_indexed = {} for item in biglist1: biglist1_indexed[(item["transaction"], item["date"])] = item for item in biglist2: if (item["transaction"], item["date"]) in biglist1_indexed: matches.append(item) ``` This is probably...
What you want to do is to use correct data structures: 1. Create a dictionary of mappings of tuples of other values in the first dictionary to their id. 2. Create two sets of tuples of values in both dictionaries. Then use set operations to get the tuple set you want. 3. Use the dictionary from the point 1 to assign i...
Comparing massive lists of dictionaries in python
[ "", "python", "" ]
Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performance and readability? I tried to flatten such a list with a nested list comprehension, like this: ``` [image for image i...
If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider [itertools.chain and company](http://docs.python.org/library/itertools.html#itertools.chain). ``` >>> list_of_menuitems = [['image00', 'image01'], ['image10'], []] >>> import itertools >>> ch...
You almost have it! The [way to do nested list comprehensions](http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions) is to put the `for` statements in the same order as they would go in regular nested `for` statements. Thus, this ``` for inner_list in outer_list: for item in inner_list: ...
Flattening a shallow list in Python
[ "", "python", "list-comprehension", "" ]
I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is t...
It's possible. Detect the keystroke in a separate thread, a hidden window and WM\_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Have th...
If the script is actually interpreted by your application then you can just tell the interpreter to stop executing whenever some user event occurs.
Cross-thread exception throwing
[ "", "c++", "winapi", "" ]
Can anyone recommend a free grid/graphing component for C#/.NET? I'm having a look at NPlot right now, but so far I'm finding it quite troublesome. EDIT: I particularly need something that plugs into Windows Forms - I'm not doing ASP.NET, and don't really fancy reproducing my graph using Google's API every time I get ...
MS just [released](https://weblogs.asp.net/scottgu/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt) one if you are using 3.5 or you could use [ZedGraph](https://sourceforge.net/projects/zedgraph/) EDIT: The Link is Just a ASP.NET demo they have a [Windows Forms Release](https://www.microsoft.com/en...
[MS Chart Controls](http://www.microsoft.com/downloads/details.aspx?familyId=130f7986-bf49-4fe5-9ca8-910ae6ea442c&displayLang=en) ([VS tools](http://www.microsoft.com/downloads/details.aspx?familyid=1d69ce13-e1e5-4315-825c-f14d33a303e9&displaylang=en)) work with winforms too: > Microsoft Chart Controls for Microsoft >...
Free C# Grid/Graph component
[ "", "c#", ".net", "graphing", "" ]
I wish to set up a ActiveMQ instance (primarily as a STOMP server) which will service requests from two types of clients: 1. authenticated users which can read and write to topics 2. non-authenticated users which can only read from topics I have been using the SimpleAuthenticationBroker so far and I cannot see anyway...
This is not currently supported by ActiveMQ security implementation, but you can always define a user that can connect without a password with read-only privileges. You can raise Jira enhancement request (<https://issues.apache.org/activemq/browse/AMQ>) for this non-authenticated users feature and better yet provide a...
This feature is now available as of ActiveMQ 5.4, as I've just found when searching for the same functionality: <http://activemq.apache.org/security.html>
How to configure ActiveMQ to assign an 'anonymous' user and role to non-authenticated users
[ "", "java", "security", "activemq-classic", "stomp", "" ]
I think this must be a stupid question, but why do the results of urlsafe\_b64encode() always end with a '=' for me? '=' isn't url safe? ``` from random import getrandbits from base64 import urlsafe_b64encode from hashlib import sha256 from time import sleep def genKey(): keyLenBits = 64 a = str(getrandbits(key...
[Base64](http://en.wikipedia.org/wiki/Base64) uses '=' for padding. Your string bit length isn't divisible by 24, so it's padded with '='. By the way, '=' should be URL safe as it's often used for parameters in URLs. See [this discussion](http://mail.python.org/pipermail/python-bugs-list/2007-February/037195.html), to...
The '=' is for padding. If you want to pass the output as the value of a URL parameter, you'll want to escape it first, so that the padding doesn't get lost when later reading in the value. ``` import urllib param_value = urllib.quote_plus(b64_data) ``` Python is just following RFC3548 by allowing the '=' for padding...
urlsafe_b64encode always ends in '=' ?:
[ "", "python", "hash", "base64", "" ]
Drupal is very much a "Do Everything" CMS. There are modules that allow you to add almost any functionality, which is great. However, it feels like a lot of the features (v5 and v6) seem scattered around and unintuitive for the user. As a developer, I'm left with the feeling of having patched a site together using bubb...
The lack of true object oriented design means that you frequently have to rely on other developers' foresight to leave "hook" functions to let you alter a certain behavior. Using Drupal 5 I've also run in to situations where the only way to complete a relatively simple design change is to patch Drupal itself (and then...
To me, the biggest shortcoming of Drupal is that large portions of a live Drupal site are stored in the database. Since there's no automated way to migrate content or configuration between systems, rolling out changes to a live site must either be done manually or dealt with by excessively complicated code.
What are some of Drupal's shortcomings?
[ "", "php", "drupal", "content-management-system", "complexity-theory", "" ]
Is there a version of JDE for emacs that supports the JDK 6.10? I haven't been able to find any information on this. While it runs, every time I attempt to compile files the JDE says that it doesn't recognize my JDK version and reverts to assuming it is a Java5 version.
I've made following customizations for JDE: ``` '(jde-bug-debugger-host-address "127.0.0.1") '(jde-bug-jre-home "/usr/lib/jvm/java-6-sun") '(jde-compile-option-debug (quote ("all" (t nil nil)))) '(jde-debugger (quote ("jdb"))) '(jde-global-classpath (quote ("." "/usr/share/java/" "/usr/lib/jvm/java-6-sun/"))) '(jde-jd...
You can set your paths up in the configuration settings by "registering" a JDK version using `M-x customize-variable` and choosing `jde-jdk-registry`. Save that state, then do `M-x customize-variable` again, customize `jde-jdk` and pick the one you want. That *should* do it; if not, give us a little more detailed info...
JDE for Emacs for JDK 6.10
[ "", "java", "emacs", "" ]
In Java I can write a really basic JSP `index.jsp` like so: `<% request.getRequestDispatcher("/home.action").forward(request, response); %>` The effect of this is that a user requesting `index.jsp` (or just the containing directory assuming `index.jsp` is a default document for the directory) will see `home.action` w...
If you are concerned about CURL availability then you could use `file_get_contents()` and streams. Setting up a function like: ``` function forward($location, $vars = array()) { $file ='http://'.$_SERVER['HTTP_HOST'] .substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'], '/')+1) .$location; ...
The trick about Request.Forward is that it gives you a clean, new request to the action you want. Therefore you have no residu from the current request, and for example, no problems with scripts that rely on the java eq of $\_SERVER['REQUEST\_URI'] being something. You could just drop in a CURL class and write a simpl...
Does PHP Have an Equivalent of Java's RequestDispatcher.forward?
[ "", "php", "jsp", "http", "forwarding", "" ]
I am a beginner SQL user (not formally trained; OJT only) and need some assistance with a simple update statement. I would like to write an update statement that allows me to list ID's. The statement shown below is how I am currently writing it. Ideally, the statement would allow me to write it like "where plantunitid ...
Can this work? ``` update plantfunctiontable set decommissioned=1 where plantunitid between 49 and 57 ```
You can use ``` Where plantunitid >= 49 AND plantunitid <= 57 ``` OR ``` Where plantunitid BETWEEN 49 and 57 ```
Update Statements
[ "", "sql", "sql-server-2000", "query-help", "" ]
Do you know any freely available WPF component for using masks (regex) in textbox?
I think you will find what you need in this control library: <http://www.codeplex.com/WPFDeveloperTools> Look for 'FilteredTextBox' amongst all the other useful controls. I don't think it does regex, but it should be able to filter just about everything you need, and since you will have the source, you should find it ...
[Extended WPF Toolkit](https://github.com/xceedsoftware/wpftoolkit) has a [MaskedTextBox](https://github.com/xceedsoftware/wpftoolkit/wiki/MaskedTextBox) similar to the one that was in WinForms. As with the old one, this doesn't actually support RegExes, but has a subset of useful masks. Oh, and it's on [NuGet](https:...
Where can I find a free masked TextBox in WPF?
[ "", "c#", ".net", "wpf", "wpf-controls", "" ]