Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an application. First I display a splash screen, a form, and this splash would call another form. Problem: When the splash form is displayed, if I then open another application on the top of the splash, and then minimize this newly opened application window, the splash screen becomes white. How do I avoid this...
You need to display the splash screen in a different thread - currently your new form loading code is blocking the splash screen's UI thread. Start a new thread, and on that thread create your splash screen and call `Application.Run(splash)`. That will start a new message pump on that thread. You'll then need to make ...
The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this: ``` using System; using System.Windows.Forms; using Microsoft.VisualBasic.ApplicationServic...
problem with splash screen - C# - VS2005
[ "", "c#", "winforms", "splash-screen", "" ]
I have the option of writing two different formats for a database structure: ``` Article ------- ArticleID int FK Article_Tags ------------ ArticleTagID int FK ArticleID int FK TagText varchar(50) ``` or ``` Article ------- ArticleID int PK Article_Tags ------------ ArticleTagID int PK ArticleID int FK TagText var...
I would go with ``` Article ------- ArticleID int PK Article_Tags ------------ ArticleTagID int PK ArticleID int FK TagId int FK Tag --- TagId int identity(1,1) PK TagText varchar(50) ``` There really is no reason to denormalize this from get go. (your first and second versions are not normalized) Having tags in a...
I would go with whichever solution will result in the best/cleanest design for your application. If you need to attach data directly to a tag then a separate table (i.e. a more normalised solution) would be the correct one. I would warn against worrying too much about the performance difference in the 2 proposed solut...
How slow is DISTINCT?
[ "", "sql", "t-sql", "" ]
I understand (I think) that XmlHttpRequest objects adhere to the "same-domain" policy. However, I want to create a simple (POC) local html file that downloads XML from a web server and does something with it (let's start with a simple "alert()"). Is it possible at all? Do I need a special Firefox config option? The s...
XMLHttpRequest actually adheres to a much stricter implementation of the same domain policy: while you can set the document.domain property to allow JavaScript served from two sub-domains to talk with each other, you can't do that with XMLHttpRequestObject. In your case, going to a completely different domain, you coul...
If the XML that you're trying to retrieve is returned by one of Google's JS APIs, then there's no need for XmlHttpRequest(since that can only be used on the same domain as your page anway). So in the case of using a Google API, such as the Maps one, usually begin by adding a reference to their common API somewhere on ...
cross-site XmlHttpRequest in Firefox?
[ "", "javascript", "api", "firefox", "xmlhttprequest", "" ]
I'm new to TDD and xUnit so I want to test my method that looks something like: ``` List<T> DeleteElements<T>(this List<T> a, List<T> b); ``` Is there any Assert method that I can use ? I think something like this would be nice ``` List<int> values = new List<int>() { 1, 2, 3 }; List<int> expected = new List<int>() ...
### 2021-Apr-01 update I recommend using [FluentAssertions](https://fluentassertions.com/). It has a vast IntelliSense-friendly assertion library for many use cases including [collections](https://fluentassertions.com/collections/) ``` collection.Should().Equal(1, 2, 5, 8); collection.Should().NotEqual(8, 2, 3, 5); c...
In the current version of XUnit (1.5) you can just use > Assert.Equal(expected, actual); The above method will do an element by element comparison of the two lists. I'm not sure if this works for any prior version.
xUnit : Assert two List<T> are equal?
[ "", "c#", "xunit", "" ]
I have a list view that is periodically updated (every 60 seconds). It was anoying to me that i would get a flicker every time it up dated. The method being used was to clear all the items and then recreate them. I decided to instead of clearing the items I would just write directly to the cell with the new text. Is th...
The ListView control has a flicker issue. The problem appears to be that the control's Update overload is improperly implemented such that it acts like a Refresh. An Update should cause the control to redraw only its invalid regions whereas a Refresh redraws the control’s entire client area. So if you were to change, s...
In addition to the other replies, many controls have a `[Begin|End]Update()` method that you can use to reduce flickering when editing the contents - for example: ``` listView.BeginUpdate(); try { // listView.Items... (lots of editing) } finally { listView.EndUpdate(); } ```
c# flickering Listview on update
[ "", "c#", "listview", "flicker", "" ]
I am resizing an iframe, and when I do that in Firefox, the content gets refreshed. I have a swf that extends, and in Firefox when the iframe extends to accommodate the swf, the swf appears in its normal position. In IE this doesn't happen. Anyone know how to prevent the refresh from happening in Firefox? Thanks -...
Antonio, I'm afraid that the problem is in Firefox it self. When Gecko detects a change to the width of an iFrame, it repaints the page and causes that "refresh." There's no way that I know of to change this behavior, short of using a different technique. I confirmed that the problem exists in other Gecko-based browse...
It seems to be that either setting `position: absolute;` or `.cssText` will refresh the frame. The solution is to add `style="position: absolute;"` to your `<iframe>` and set your css like this: ``` this.mrec_div_idObj.style.left = ((offsetLeftIframe) - (dimX - disX)) + "px"; this.mrec_div_idObj.style.top = (offsetTo...
How do I prevent a swf from refreshing when an iframe is resized?
[ "", "javascript", "firefox", "iframe", "flash", "refresh", "" ]
I have an ASP.Net CheckBoxList control inside an Ajax UpdatePanel. I will include the code (C#) along with the HTML below. I have found that it is something with the CheckBoxList not persisting through the post back. BTW, it is a little messy. It is a prototype. This is the method used to populate the original Chec...
After further research, I have found that the controls aren't persisting through the post back, and are dropping out of the view state. So each time it posts back, there is a null object returned from: ``` protected Control PostBackControl { get { return Page.FindControl(Request.Params.Get("__EVENTTARGET")); } } `...
``` protected void BindCheckboxes() { if(!IsPostBack) { chkBuildings.Items.Clear(); chkNeighborhoods.Items.Clear(); string city = ddlFindHome_Location.SelectedItem.Value.ToLower(); ResidentDataContext rdc = new ResidentDataContext(Utility.Lookup.GetResidentConnectionString()); ...
Asp.net updatepanel clears checkboxlist selections
[ "", "c#", "asp.net", "updatepanel", "checkboxlist", "" ]
I have a login page that has several textboxes on the page, one of them has the mode set to "password". This page worked previously but we've recently noticed (since an IE7 update) that the textbox that is specified as a password textbox is not as wide as the other textboxes on the page. If I remove the TextMode="Passw...
The best way to ensure that all of your controls will be of the same size is via style (either inline or in css).
I've found that if you use the following CSS: ``` input, select { font-family: sans-serif; } ``` this will make the text and password boxes be the same width. The font-family does not have to be sans-serif, but it must be defined. This may be a better solution as it seems to fix the issue rather than band-aid over i...
ASP.NET Textbox size differs when TextMode=Password
[ "", "c#", "asp.net", "" ]
I am new to C# and .NET programming. I want to design an application that opens up with a small login screen and when user presses the "Login" button, my program should close the login form and pass to a new form. How can I achieve this simple process? Thanks.
This could be a solution; In LoginForm; ``` public bool IsLoggedIn { get; private set;} public void LoginButton_Click(object sender, EventArgs e) { IsLoggedIn = DoLogin(); if(IsLoggedIn) { this.Close() } else { DoSomethingElse(); } } ``` In program.cs ``` static void Main() { Application.Ena...
Depending on the overall architecture of your application, I often like to let the main form control launching the login screen. ``` //Program.cs: [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application...
Two different windows forms in C#
[ "", "c#", "winforms", "authentication", "screen", "" ]
Is there stable linear algebra (more specifically, vectors, matrices, multidimensional arrays and basic operations on them) library for C#? Search yielded a few open source libraries which are either not updated for couple of years or are in an early beta stage - and Centerspace NMath. Which alternatives are worth che...
[Math.NET](http://numerics.mathdotnet.com/). We're using it in production.
See: <http://en.wikipedia.org/wiki/List_of_numerical_libraries> <http://www.alglib.net/> - Open source. Multi-language library. <http://www.mathdotnet.com/> - Open source. As mentioned by others. dnAnalytics is replaced by <http://numerics.mathdotnet.com/> in this. <http://www.lutzroeder.com/dotnet/> - Lutz Roeder h...
C# linear algebra library
[ "", "c#", ".net", "linear-algebra", "nmath", "" ]
I still have a problem with the splash screen. I don't want to use the property `SC.TopMost=true`. Now my application scenario is as follows: **in progeram.cs:** ``` [STAThread] static void Main() { new SplashScreen(_tempAL);// where _tempAL is an arrayList Application.Run(new Form1(_tempAL)); } ``` **in Sp...
Following across 2 threads is a bit confusing, but I'm going to take a stab and say this... I don't fully understand your design here, but if the issue is that when you launch a second application the splash screen form turns white... It's most likely due to the fact that splash screen is busy executing all of that co...
Same question, same answer: The .NET framework has excellent built-in support for splash screens. Start a new WF project, Project + Add Reference, select Microsoft.VisualBasic. Add a new form, call it frmSplash. Open Project.cs and make it look like this: ``` using System; using System.Windows.Forms; using Microsoft....
Splash Screen waiting until thread finishes
[ "", "c#", "winforms", "splash-screen", "" ]
I was reading a question about c# code optimization and one solution was to use c++ with SSE. Is it possible to do SSE directly from a c# program?
The upcoming [Mono](http://www.mono-project.com/Main_Page) 2.2 release will have SIMD support. Miguel de Icaza blogged about the upcoming feature [here](http://tirania.org/blog/archive/2008/Nov-03.html), and the API is [here](http://go-mono.com/docs/index.aspx?tlink=0@N%3aMono.Simd). Although there will be a library t...
**Can C# explicitly make an SSE call?** No. C# cannot produce inline IL much less inline x86/amd64 assembly. The CLR, and more specifically the JIT, will use SSE if it's available removing the need to force it in most circumstances. I say most because I'm not an SSE expert and I'm sure that there are cases where it c...
Using SSE in c# is it possible?
[ "", "c#", "sse", "" ]
I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?
There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)
No. It would be better to make them functions and if they are related, place them into their own module. For instance, if you have a class like this: ``` class Something(object): @staticmethod def foo(x): return x + 5 @staticmethod def bar(x, y): return y + 5 * x ``` Then it would be...
Is there any advantage in using a Python class?
[ "", "python", "class", "static-methods", "" ]
How to do it? Is it possible to call a function from one F# code into C# without using a separated dll file or project?
You can't include two different languages in the same project, but you can merge them using [ilmerge](http://research.microsoft.com/en-us/people/mbarnett/ILMerge.aspx). To do this, put both projects in the same solution and reference the F# module as you would any dll. As part of your deployment script, run ilmerge to ...
Not being able to mix C# and F# in the same project creates a problem; It leads to circular dependencies between the two projects. Conceptually there is only one project containing two languages, but because of the way visual studio manages projects languages cannot be mixed, leading to circular dependencies. For now ...
Is it possible to mix .cs (C#) and .fs (F#) files in a single Visual Studio Windows Console Project? (.NET)
[ "", "c#", ".net", "visual-studio", "f#", "console", "" ]
I have a sparsely populated matrix that's the result of a series of left joins. I'd like to collapse it down to a single row (see below). The only solution I've seen to this is a GROUP BY on the PK and a MAX() on ColA, ColB etc. Performance is a huge issue here, so I'd like to know if anyone has a better solution. The ...
I rewrote this as a PIVOT and saw a performance increase of about 30%. It wasn't easy to do, had to read [**this post**](http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx) very carefully. PIVOTs are weird.
The GROUPY BY + MAX solution isn't a bad one. Since it's going to be scanning over the same number of records whether or not you're doing aggregates. I'd be curious to know what the time difference with and without grouping is.
best way to collapse a sparsely populated matrix
[ "", "sql", "sql-server", "" ]
What is the best way to append to a text field using t-sql in Sql Server 2005? With a varchar I would do this. ``` update tablename set fieldname = fieldname + 'appended string' ``` But this doesn't work with a text field.
Try this: ``` update tablename set fieldname = convert(nvarchar(max),fieldname) + 'appended string' ```
[This should work (link)](http://developer.fusium.com/FUblog/index.cfm/2006/7/13/appending-an-ntext-field "This should work.") Copied from link: ``` DECLARE @ptrval binary(16) SELECT @ptrval = TEXTPTR(ntextThing) FROM item WHERE id =1 UPDATETEXT table.ntextthing @ptrval NULL 0 '!' GO ```
How to append to a text field in t-sql SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "append", "" ]
I have a JAR file named *helloworld.jar*. In order to run it, I'm executing the following command in a command-line window: ``` java -jar helloworld.jar ``` This works fine, but how do I execute it with double-click instead? Do I need to install any software?
Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE). Or this: * Open the Windows Explorer, from the Tools select 'Folder Options...' * Click the File Types tab, scroll down and select JAR File type. * Press the Advanced button. * In the Edit File Type dialog box, select open in Act...
In Windows Vista or Windows 7, the [manual file association editor](https://stackoverflow.com/questions/394616/running-jar-file-in-windows/394628#394628) has been removed. The easiest way is to run [Jarfix](http://johann.loefflmann.net/en/software/jarfix/index.html), a tiny but powerful freeware tool. Just run it and ...
Running JAR file on Windows
[ "", "java", "jar", "executable-jar", "" ]
Right now I am using this to export a repeater (with multiple nested repeaters) to excel: ``` protected void ExportToExcel(object sender, EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=finance.xls"); Response.Charset = ""; Response.Content...
You need to enclose all of that in table tags. Excel can understand HTML table structures. Try: ``` Response.Write("<table>"); Response.Write(stringWrite.ToString()); Response.Write("</table>"); ```
not to answer your question directly, but given you my opinion for that kinda of data, is in my opinion that you should use a GridView control, taking your example you will need to write something like: ``` <asp:Repeater ID="rpt" runat="server" DataSourceID="ods"> <HeaderTemplate> <table> <tr> ...
Export to Excel from a Repeater?
[ "", "c#", "asp.net", "excel", "repeater", "" ]
I have a few procedures, for simplicity sake, look like the following: ``` public string FetchValueAsString(string key) public int FetchValueAsInteger(string key) public bool FetchValueAsBoolean(string key) public DateTime FetchValueAsDateTime(string key) ``` I know I could just have one method that returns and objec...
``` public static T FetchValue<T>(string key) { string value; // logic to set value here // ... return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } ```
I'm assuming you're writing code in C#. If you are then you could do what your talking about like this: ``` public T FetchValueAsType<T>(string key) ``` You would then call the version like this: ``` FetchValueAsType<int>(key); ``` That being said the the `System.Convert` class provided by the framework works just ...
One function with varying return types ... possible with Generics?
[ "", "c#", ".net", "generics", "" ]
I've always wondered how to write the **`"A ? B : C"`** syntax in a C++ compatible language. I think it works something like: *(Pseudo code)* ``` If A > B C = A Else C = B ``` *Will any veteran C++ programmer please help me out?*
It works like this: ``` (condition) ? true-clause : false-clause ``` It's most commonly used in assignment operations, although it has other uses as well. The ternary operator `?` is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (`IIf(condition,true-clause,fals...
It works like this: ``` expression ? trueValue : falseValue ``` Which basically means that if `expression` evaluates to true, trueValue will be returned or executed, and falseValue will be returned or evaluated if not. Remember that trueValue and falseValue will only be evaluated and executed if the expression is tr...
How do I use the conditional (ternary) operator?
[ "", "c++", "conditional-operator", "" ]
I understand the reflection API (in c#) but I am not sure in what situation would I use it. What are some patterns - anti-patterns for using reflection?
The only place I've used the Reflection stuff in C# was in factory patterns, where I'm creating objects (in my case, network listeners) based on configuration file information. The configuration file supplied the location of the assemblies, the name of the types within them, and any additional arguments needed. The fac...
In one product I'm working on we use it a lot, but Reflection is a complex, slow beast. Don't go looking for places to use it just because it sounds fun or interesting. You'll use it when you run into a problem that can't be solved in any other way (dynamically loading assemblies for plug ins or frameworks, assembly in...
When do you use reflection? Patterns/anti-patterns
[ "", "c#", "reflection", "" ]
I started with a query: ``` SELECT strip.name as strip, character.name as character from strips, characters, appearances where strips.id = appearances.strip_id and characters.id = appearances.character.id and appearances.date in (...) ``` Which yielded me some results: ``` strip | character ...
Does mySQL support analytic functions? Like: ``` SELECT foo.bar, baz.yoo, count(baz.yoo) over (partition by foo.bar) as yoo_count from foo, bar where foo.baz_id = baz.id and baz.id in (...) ``` Alternatively: ``` SELECT foo.bar, baz.yoo, v.yoo_count from foo, bar, ( select foo.baz_id, count(*) as yoo_count from...
What about grouping by foo.bar? ``` SELECT count(baz.id) as count, foo.bar, baz.yoo where foo.baz_id = baz.id and baz.id in (...) group by foo.bar ```
How can I mix COUNT() and non-COUNT() columns without losing information in the query?
[ "", "sql", "" ]
From my understanding, Lua is an embeddable scripting language that can execute methods on objects. What are the pitfalls to avoid? Is is it feasible to use Lua as an interpreter and execute methods in an web environment or as a rule engine?
Lua is very fast - scripts can be precompiled to bytecodes and functions execute close to C++ virtual method calls. That is the reason why it is used in gaming industry for scripting AI, plugins, and other hi-level stuff in games. But you put C# and web server in your question tags. If you are not thinking of embedde...
Lua scripting is [on track](http://lua-users.org/lists/lua-l/2008-12/msg00119.html) to becoming a core module for Apache web server. There are a couple tools for binding Lua and C#/.NET code [here](http://lua-users.org/wiki/BindingCodeToLua). [LuaInterface](http://lua-users.org/wiki/LuaInterface) is the most up to dat...
What are the most effective ways to use Lua with C#?
[ "", "c#", "performance", "clr", "lua", "" ]
I have a huge list of datetime strings like the following ``` ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"] ``` How do I convert them into [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) objects?
[`datetime.strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) parses an input string in the user-specified format into a *timezone-naive* [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) object: ``` >>> from datetime import datetime >>> datetime.strptim...
Use the third-party [`dateutil`](https://dateutil.readthedocs.io) library: ``` from dateutil import parser parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0) ``` It can handle most date formats and is more convenient than `strptime` since it usually guesses the correct format. It is also very...
Convert string "Jun 1 2005 1:33PM" into datetime
[ "", "python", "datetime", "" ]
OK, every other browser works fine with the method I have coded so far but for some reason Internet Explorer will not work. I have spent hours of time (more time than actually developing the feature!) on compatibility and am close to giving up! I have a forum and one of its neat features is the WYSIWYG editor. For tha...
In the end I used frames['frameName'].document.write('someText') but only if the other method fails.
Have you activated IE's [debugging](https://msdn.microsoft.com/library/bg182326(v=vs.85)) [facilities](https://msdn.microsoft.com/en-us/library/gg699336%28v=vs.85%29.aspx)?
Accessing frames via the DOM in IE
[ "", "javascript", "html", "internet-explorer", "iframe", "" ]
Is there a nice way to split a collection into `n` parts with LINQ? Not necessarily evenly of course. That is, I want to divide the collection into sub-collections, which each contains a subset of the elements, where the last collection can be ragged.
A pure linq and the simplest solution is as shown below. ``` static class LinqExtensions { public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts) { int i = 0; var splits = from item in list group item by i++ % parts into part ...
EDIT: Okay, it looks like I misread the question. I read it as "pieces of length n" rather than "n pieces". Doh! Considering deleting answer... (Original answer) I don't believe there's a built-in way of partitioning, although I intend to write one in my set of additions to LINQ to Objects. Marc Gravell has an [imple...
Split a collection into `n` parts with LINQ?
[ "", "c#", ".net", "linq", "data-structures", "" ]
A *using* declaration does not seem to work with an enum type: ``` class Sample{ public: enum Colour {RED, BLUE, GREEN}; } using Sample::Colour; ``` does not work! Do we need to add a *using* declaration for every enumerators of enum type? Like below: ``` using sample::Colour::RED; ```
A class does not define a namespace, and therefore "using" isn't applicable here. Also, you need to make the enum public. If you're trying to use the enum within the same class, here's an example: ``` class Sample { public: enum Colour { RED, BLUE, GREEN }; void foo(); } void Sample::foo() { Colour foo = RE...
To add to [Steve Lacey's answer](https://stackoverflow.com/questions/438192/using-declaration-with-enum#438210), the problem with the original code is that you refer to a member, but the *using* declaration is not itself a member declaration: 7.3.3/6 has: > A using-declaration for a class member > shall be a member-d...
A 'using' declaration with an enum
[ "", "c++", "enums", "using-declaration", "" ]
I have three applications that talk to each other using sockets. They can all live on their own machines but they can also share a machine. Right now I'm having two of them on the same and the third on its own machine. I'm trying to make my communication bullet proof so I unplug cables and kill the applications to make...
What address are you using for "Con A"? If you are using an address that is bound to the external network adapter, even though you're talking to the same machine, then what you describe could happen. What you can do is use the address `localhost` (127.0.0.1) for "Con A", which should be completely independent of what ...
On some platforms (windows) pulling the network cable tells the network stack to activly invalidate open socket connections associated with the interface. In this scenario pulling a network cable is actually a bad test because it provides positive feedback to your application that it may not receive in a real life sit...
What happens to sockets when I unplug a network cable?
[ "", "c#", ".net", "sockets", "" ]
Is there anything like [`Collections.max`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collections.html#max(java.util.Collection)) which finds the maximal value in an array for regular arrays (such as an `int[]`) in the standard Java runtime library?
No, there is no Arrays.max or a lookalike, at least in Java 6. If you look at the signature and implementation of Collections.max, it makes quite heavy use of parameterized types. In Java, generic arrays are problematic to say the least, so maybe therefore it is not a good idea to provide a generic max implementation ...
If you have an array of Objects you can use ``` Collections.max(Arrays.asList(array)); ``` If you have an array of primitive you can just use a simple loop. ``` long[] array; long max = array[0]; for(long l : array) if (max < l) max = l; ```
Maximal element in an array in Java (Collections.max() for integer arrays int[])
[ "", "java", "collections", "max", "" ]
How can I limit a result set to *n* distinct values of a given column(s), where the actual number of rows may be higher? Input table: ``` client_id, employer_id, other_value 1, 2, abc 1, 3, defg 2, 3, dkfjh 3, 1, ldkfjkj 4, 4, dlkfjk 4, 5, 342 4, 6, dkj 5, 1, dlkfj 6, 1, 34kjf 7, 7, 34kjf 8, 6, lkjkj 8, 7, 23kj ``` ...
You can use a subselect ``` select * from table where client_id in (select distinct client_id from table order by client_id limit 5) ```
This is for SQL Server. I can't remember, MySQL may use a LIMIT keyword instead of TOP. That may make the query more efficient if you can get rid of the inner most subquery by using the LIMIT and DISTINCT in the same subquery. (It looks like Vinko used this method and that LIMIT is correct. I'll leave this here for the...
How to do equivalent of "limit distinct"?
[ "", "sql", "mysql", "" ]
I am trying to figure out how C and C++ store large objects on the stack. Usually, the stack is the size of an integer, so I don't understand how larger objects are stored there. Do they simply take up multiple stack "slots"?
The stack is a piece of memory. The stack pointer points to the top. Values can be pushed on the stack and popped to retrieve them. For example if we have a function which is called with two parameters (1 byte sized and the other 2 byte sized; just assume we have an 8-bit PC). Both are pushed on the stack this moves ...
--- ## Stack and Heap are not as different as you think! --- True, some operating systems do have stack limitations. (Some of those also have nasty heap limitations too!) But this isn't 1985 any more. These days, I run Linux! My default *stacksize* is limited to 10 MB. My default *heapsize* is unlimited. It's pre...
How do C and C++ store large objects on the stack?
[ "", "c++", "c", "memory", "stack", "" ]
Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like: ``` def iterlen(x): n = 0 try: while True: next(x) ...
There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example: ``` def fib(): a, b = 0, 1 while True: a, b = b, a + b yield a ``` This never terminates but will generate the Fibonacci numbers. You can get as many Fibonacci numbers as you ...
The easiest way is probably just `sum(1 for _ in gen)` where gen is your generator.
Length of generator output
[ "", "python", "generator", "iterable", "" ]
How can I detect which CPU is being used at runtime ? The c++ code needs to differentiate between AMD / Intel architectures ? Using gcc 4.2.
If you're on Linux (or on Windows running under Cygwin), you can figure that out by reading the special file `/proc/cpuinfo` and looking for the line beginning with `vendor_id`. If the string is `GenuineIntel`, you're running on an Intel chip. If you get `AuthenticAMD`, you're running on an AMD chip. ``` void get_vend...
The `cpuid` instruction, used with `EAX=0` will return a 12-character vendor string in `EBX`, `EDX`, `ECX`, in that order. For Intel, this string is "GenuineIntel". For AMD, it's "AuthenticAMD". Other companies that have created x86 chips have their own strings.The [Wikipedia page](http://en.wikipedia.org/wiki/CPUID) ...
How to detect what CPU is being used during runtime?
[ "", "c++", "gcc", "cpu", "" ]
I'm working on making a simple server application with python, and I'm trying to get the IP to bind the listening socket to. An example I looked at uses this: ``` HOST = gethostbyaddr(gethostname()) ``` With a little more processing after this, it should give me just the host IP as a string. This should return the IP...
Getting your IP address is harder than you might think. Check [this answer](https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#274644) I gave for the one reliable way I've found. Here's what the answer says in case you don't like clicking on things: Use the...
IPv6 is taking precedence over IPv4 as it's the newer family, it's generally what you want if your hostname is associated with multiple families. You should be using [getaddrinfo](http://docs.python.org/library/socket.html#socket.getaddrinfo) for family independent resolution, here is an example, ``` import sys, socke...
Why does gethostbyaddr(gethostname()) return my IPv6 IP?
[ "", "python", "sockets", "ip-address", "ipv6", "ipv4", "" ]
What do people here use C++ Abstract Base Class constructors for in the field? I am talking about pure interface classes having no data members and no non-pure virtual members. Can anyone demonstrate any idioms which use ABC constructors in a useful way? Or is it just intrinsic to the nature of using ABCs to implement...
> Can anyone demonstrate any idioms which use ABC constructors in a useful way? Here's an example, although it's a contrived, uncommon example. You might use it to keep a list of all instances: ``` class IFoo { private: //static members to keep a list of all constructed instances typedef std::set<IFoo*> Set; s...
Suppose that there is some behavior that is common for all the derived classes. Such as registering itself in some external registry, or checking validity of something. All this common code can be placed in base class's constructor, and it will be called implicitly from the constructors of each of the derived classes.
What do *you* use C++ ABC constructors for?
[ "", "c++", "constructor", "abstract-base-class", "interface-design", "" ]
I'm not good with JavaScript, and this is Google's code. I'm getting a object expected on this, which seems to work fine in other places. It's the 3rd to the last line (the one with `utmSetVar`). ``` <HTML> <HEAD> </HEAD> <BODY > <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protoc...
The utmSetVar function is a one that was available in the old Google Analytics codebase using the "urchin" tracker. <http://www.google-analytics.com/urchin.js> You can use the following to determine which one you are using <http://www.google.com/support/googleanalytics/bin/answer.py?answer=75129> In order to solve ...
The correct code was: ``` <script type="text/javascript">pageTracker._setVar('aff/undefined');</script> ```
javascript object expected
[ "", "javascript", "internet-explorer", "" ]
I'm trying to figure out how to exclude items from a select statement from table A using an exclusion list from table B. The catch is that I'm excluding based on the prefix of a field. So a field value maybe "FORD Muffler" and to exclude it from a basic query I would do: ``` SELECT FieldName FROM TableName WHERE UP...
I think this will do it: ``` SELECT FieldName FROM TableName LEFT JOIN TableName2 ON UPPER(ColumnName) LIKE TableName2.FieldName2 + '%' WHERE TableName2.FieldName2 IS NULL ```
Dunno how efficient this would be, but it should work: ``` SELECT FieldName FROM TableName t1 WHERE NOT EXISTS ( SELECT * FROM TableName2 t2 WHERE t1.FieldName LIKE t2.FieldName2 + '%' ) ```
SQL Exclude LIKE items from table
[ "", "sql", "subquery", "" ]
I have a file containing several lines similar to: ``` Name: Peter Address: St. Serrano número 12, España Country: Spain ``` And I need to extract the address using a regular expression, taking into account that it can contain dots, special characters (ñ, ç), áéíóú... The current code works, but it looks quite ugly:...
I don't know Java's regex objects that well, but something like this pattern will do it: ``` ^Address:\s*((?:(?!^\w+:).)+)$ ``` assuming multiline and dotall modes are on. This will match any line starting with Address, followed by anything until a newline character and a single word followed by a colon. If you kno...
Assuming "content" is a string containing the file's contents, your main problem is that you're using `matches()` where you should be using `find()`. ``` Pattern p = Pattern.compile("^Address:\\s*(.*)$", Pattern.MULTILINE); Matcher m = p.matcher(content); if ( m.find() ) { ... } ``` There seems to be some confusion...
Regular Expression to extract label-value pairs in Java
[ "", "java", "regex", "" ]
I would like to be able to perform SQL queries on my e-mail inbox. With the output, I can make graphs about how much e-mails I send or receive for example. I want to analyze my performance and what keeps me busy. My mailbox seems like a good place to start. I'm using Gmail on-line, and Thunderbird, Outlook 2007 and Ma...
You can simply connect Outlook to Access via Access Wizards or code (<http://support.microsoft.com/kb/209946/en-us>)
You can parse mbox files (which Thunderbird uses to store it's messages) using any number of scripts like [this](http://blog.devayd.com/2008/07/copy-messages-from-a-thunderbird-mbox-file-to-a-mysql-table-using-php/) then do any sql on the messages you like.
SQL in an e-mail app
[ "", "sql", "ms-access", "email", "outlook", "thunderbird", "" ]
Currently, I only know a way of doing RPC for POJOs in Java, and is with the very complex EJB/JBoss solution. Is there any better way of providing a similar functionality with a thiner layer (within or without a Java EE container), using RMI or something that can serialize and send full blown objects over the wire? I...
As is nearly always the case, [Spring](http://www.springsource.org/) comes to the rescue. From the [reference documentation](http://static.springframework.org/spring/docs/2.5.x/reference/index.html), you will want to read [Chapter 17. Remoting and web services using Spring](http://static.springframework.org/spring/docs...
Simple RPC is exactly what RMI was built for. If you make a serializable interface, you can call methods on one app from another app.
Simpler-than-JBoss way to have POJO RPC in Java with container session management
[ "", "java", "serialization", "jboss", "distributed", "rmi", "" ]
Hey all - I have an app where I'm authenticating the user. They pass username and password. I pass the username and password to a class that has a static method. For example it'm calling a method with the signature below: ``` public class Security { public static bool Security.Member_Authenticate (string username, str...
This will not happen. When a method is Static (or Shared in VB.NET), then you're safe as long as the method doesn't rely on anything other than the inputs to figure something out. As long as you're not modifying any public variables or objects from anywhere else, you're fine.
A static method is just fine as long as it is not using any of persistent data between successive calls. I am guessing that your method simply runs a query on the database and returns true/false based on that. In this scenario, I think the static method should work without a problem, regardless of how many calls you m...
Static methods in a class - okay in this situation?
[ "", "c#", "asp.net", "asp.net-2.0", "" ]
I am looking to develop an audio player in C#, but was wondering what libraries are available for playback. I am looking for a free library that allows for an extensive list of audio formats to be played (for example mp3, wma, wav, ogg, etc.) Thats pretty much the basic functionality I would need. But if I could get pi...
[Bass Audio Library](http://www.un4seen.com/) is one option.
[NAudio](https://github.com/naudio/NAudio) is an open source .NET audio library that can play back WAV, MP3, WMA, AAC and AIFF files, making use of ACM or Media Foundation codecs installed on your computer for decompression purposes. For ogg support, there is an [add-on nuget package](https://nuget.org/packages/NVorbis...
C# Audio Library
[ "", "c#", "audio", "" ]
I don't think this is possible with just regular expressions, but I'm not an expert so i thought it was worth asking. I'm trying to do a massive search and replace of C# code, using .NET regex. What I want to do is find a line of code where a specific function is called on a variable that is of type DateTime. e.g: ``...
Try this: ``` @"(?s)set_Field\(""[^""]*"",\s*(?<vname>\w+)(?<=\bDateTime\s+\k<vname>\b.+)" ``` By doing the lookbehind first, you're forcing the regex to search for the method calls in a particular order: the order in which the variables are declared. What you want to do is match a likely-looking method call first, t...
Have a look at my answer to this question [Get a methods contents from a C# file](https://stackoverflow.com/questions/261741/get-a-methods-contents-from-a-cs-file#261861) It gives links to pages that show how to use the built in .net language parser to do this simply and reliably (i.e. not by asking "what looks like t...
regular expression lookaround
[ "", "c#", ".net", "regex", "" ]
I am attempting to create a small application to collect data received from an external sensor attached to COM10. I have successfully created a small C# console object and application that opens the port and streams data to a file for a fixed period of time using a for-loop. I would like to convert this application to...
~~I think your issue is the line:~~\*\* ~~sp.DataReceived += port\_OnReceiveDatazz;~~ ~~Shouldn't it be:~~ ~~sp.DataReceived += new SerialDataReceivedEventHandler (port\_OnReceiveDatazz);~~ \*\*Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question). I've also se...
First off I recommend you use the following constructor instead of the one you currently use: ``` new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One); ``` Next, you really should remove this code: ``` // Wait 10 Seconds for data... for (int i = 0; i < 1000; i++) { Thread.Sleep(10); Console.WriteLin...
How do I use dataReceived event of the SerialPort Port Object in C#?
[ "", "c#", "serial-port", "" ]
In an ASP.NET (2.0) application I use FormsAuthentication. In the Global.asax / Application\_AuthenticateRequest method I check if HttpContext.Current.User is null. Is this enough to know if the forms authentication cookie exists, the ticket is not expired, and overall, that the forms authentication mechanism has don...
No, the `User` could just be a reference to the anonymous user. Check [`HttpContext.Current.Request.IsAuthenticated`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.isauthenticated.aspx).
I usually use Request.IsAuthenticated. I couldn't tell you whether your approach should work or not. It sounds like it should, although it might have side effects if you support anonymous logins?
Is (HttpContext.Current.User != null) enough to assume that FormsAuthentication has authenticated the user
[ "", "c#", ".net", "asp.net", ".net-2.0", "forms-authentication", "" ]
(code examples are python) Lets assume we have a list of percentages that add up to 100: ``` mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] ``` Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. ...
How's this? ``` def adjustAppend( v, n ): weight= -n/sum(v) return [ i+i*weight for i in v ] + [n] ``` Given a list of numbers *v*, append a new number, *n*. Weight the existing number to keep the sum the same. ``` sum(v) == sum( v + [n] ) ``` Each element of *v*, *i*, must be reduced by some function of *...
you're being silly. let's say you want to add 4.0 to the list. You don't need to subtract a certain amount from each one. What you need to do is multiply each item. 100 - 4 = 96. therefore, multiply each item by 0.96 you want to add 20.0 as an item. so then you multiply each item by 0.8, which is (100-20)\*0.01 upd...
Algorithm to keep a list of percentages to add up to 100%
[ "", "python", "algorithm", "" ]
I'm basically looking for a way to automate typing stuff like the following: ``` cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; ``` Something like: ``` PRINTDBG(a[x][y]); ``` Ideally this would also work for ``` PRINTDBG(func(arg1, arg2)); ``` and even ``` PRINTDBG(if(condition) func(foo);); ``` ...
This is, in the way you want it, not possible. If you have *if(condition) func(foo);* given to a macro, it can stringize that stuff, and it will print *if(condition) func(foo);*, but not with the actual values of the variables substituted. Remember the preprocessor doesn't know about the structure about that code. For...
This is an area where the `printf` style output can be more concise: ``` cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; printf("a[%d][%d] =\t%d\n", x, y, a[x][y]); ``` Of course, this has the limitation of only working for types that `printf` understands, and it still doesn't address your question. I ...
Printing detailed debugging output easily?
[ "", "c++", "debugging", "" ]
i want to do this simple piece of code work. ``` #include <iostream> #include <windows.h> void printSome (int i) { std::cout << i << std::endl; } void spawnThread (void (*threadName)(int i)) { CreateThread ( 0, // default security attributes ...
Personally, I wouldn't consider passing in a function pointer like you are trying to do as very C++ like. That's coding C in C++ Instead, I'd wrap that thing in a class. The big advantage there is you can just override the class to have however many members you want, rather than having to perform greazy casting tricks...
CreateThread wants 2 arguments: pointer to the function to execute as a thread, and a DWORD argument that will be given to the thread. your spawnThread() function only has 1 argument (threadName); you *think* it has 2 args because of the "i", but that is really part of the definition of the "threadName" type. (you coul...
Passing function Pointers in C++
[ "", "c++", "windows", "multithreading", "function", "pointers", "" ]
I read somewhere (can't find it now) that large exception hierarchies are a waste of time. The justification for this statement seemed sound at the time and the idea stuck with me. In my own code when I have a code base that can have a range of error conditions I use a single exception with an enumeration member to di...
Simple rule of thumb: * If you end up rethrowing exceptions after examining them, then you need a more finegrained exception hierarchy (Except for the rare case where the examination entails considerable logic). * If you have Exception classes that are never caught (only their supertypes are), then you need a less fin...
I think having just one exception type with an embedded enum is suboptimal: 1. You are forced to catch the exception more often than necessary (and rethrow it, once you have established that you can't handle it) 2. The enum itself becomes a change hotspot (all programmers need to modify it on a regular basis) 3. An en...
exception hierarchy vs error enumeration
[ "", "c++", "exception", "" ]
I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge pa...
Using the same get/set functions for both classes forces you into an ugly hack with the argument list. Very sketchy, this is how I would do it: In class SingleParameter, define get and set as usual: ``` def get(self): return self._s def set(self, value): self._s = value ``` In class Collection, you cannot know t...
Look at built-in functions `getattr` and `setattr`. You'll probably be a lot happier.
How to implement property() with dynamic name (in python)
[ "", "python", "oop", "parameters", "properties", "" ]
We've licensed a commercial product (product not important in this context), which is limited by the number of concurrent users. Users access this product by going through a Spring Controller. We have N licenses for this product, and if N+1 users access it, they get a nasty error message about needing to buy more lice...
What you need is a ObjectPool. Check out Apache Commons Pool <http://commons.apache.org/pool> At the application startup you should create a Object Pool with licences or objects of commercial library (Not sure what kind of public interface they have). ``` public class CommercialObjectFactory extends BasePoolableObjec...
Spring has a org.springframework.aop.interceptor.ConcurrencyThrottleInterceptor that can be used via AOP (or the underlying code can be used standalone). That might be a lighter weight approach than using a object pool.
Limit Access To a Spring MVC Controller -- N sessions at a time
[ "", "java", "multithreading", "spring", "session", "controller", "" ]
In [this](https://stackoverflow.com/questions/381267/looped-pushback-against-resize-iterator) thread some one commented that the following code should only be used in 'toy' projects. Unfortunately he hasn't come back to say why it's not of production quality so I was hoping some one in the community may be able to eith...
It seems like a lot of templated code to achieve very little, given you have direct hex conversion in the standard C **scanf** and **printf** functions. why bother?
My main comment about it is that it's very difficult to read. Especially: ``` *outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) << 4) & 0x00f0) + (((*(it+1) > '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f) ``` It would take my brain a little while to grok that, and annoy me if I inherited the code...
Converting binary data to printable hex
[ "", "c++", "templates", "stl", "" ]
I'm using `ShellExecuteEx` to execute a command in C. Is there a way to use `ShellExecuteEx` and capture standard in/out/err? Note: I don't want to use `CreateProcess`.
As mentioned by pilif and Bob, you need to use `CreateProcess`. If you want code that wraps it all up for you, I do have a class for this exact issue at: <http://code.google.com/p/kgui/source/browse/trunk/kguithread.cpp>. The class (`kGUICallThread`) handles Linux, macOS and Windows versions. The code is licensed LG...
I use to found the problem like you. Suppose, You want to capture the output from STDOUT that it's generated by **dir** command and save the captured into **out.txt**. 1. Use text editor and type **dir > out.txt** and save it with **mybat.bat** (\*.bat, don't \*.txt) 2. In your c/c++ program, type **WinExec("mybat.ba...
Using ShellExecuteEx and capturing standard in/out/err
[ "", "c++", "c", "windows", "winapi", "" ]
i have a weird problem. i would like to delete an assembly(plugin.dll on harddisk) which is already loaded, but the assembly is locked by the operating system (vista), even if i have unloaded it. f.e. ``` AppDomainSetup setup = new AppDomainSetup(); setup.ShadowCopyFiles = "true"; AppDomain appDomain = AppDomain.Crea...
I think i've the answer! the answer from Øyvind Skaar will not work, if you would like to delete the loaded assembly. instead of ``` using (FileStream dll = File.OpenRead(path)) { fileContent = new byte[dll.Length]; dll.Read(fileContent, 0, (int)dll.Length); } Assembly assembly = appDomain.Load(fileContent); ``...
I know this thread is quite dead, but I am currently working on this and I just got the answer (at 1h30 AM...) ``` AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain app = AppDomain.CreateDomain("YaCsi", null, setup); app.DoCallBack(LoaderCallback); Ap...
how to delete the pluginassembly after AppDomain.Unload(domain)
[ "", "c#", "plugins", "assemblies", "" ]
I've read a few posts where people have stated (not suggested, not discussed, not offered) that PHP should not be used for large projects. Being a primarily PHP developer, I ask two questions: 1. What defines a "large project"? 2. Why not? What are the pitfalls of using PHP I run a small development team and I know ...
I really hate it when people say flat out that PHP is a terrible language because you can write code which mixes presentation with logic, or that it lets you allow SQL injection. **That's nothing at all to do with the language, that's the developer.** PHP has proved itself to be highly scalable: Wikipedia is one of th...
A lot of people who say not use it are really saying don't use PHP 4. It comes down to this **you can write good code in any language** and **you can write bad code in any language** PHP can very often lend itself to becoming tangled spaghetti code libraries and make your 'application' really just a series of scrip...
No PHP for large projects? Why not?
[ "", "php", "scalability", "projects", "" ]
I have the following HTML / JS: ``` <html> <body> <script> function foo(){ var html = "<iframe src=\"foo.html\" />"; document.getElementById('content').innerHTML=html; } function bar(){ var html = "<iframe src=\"bar.html\" />"; document.getElementById('content')...
Have you tried changing the url in your generated iframe? E.g. ``` var randomNum = Math.random(); var html = "<iframe src=\"bar.html?rand="+randomNum+"\" />"; ``` Even better, combine that with geowa4's appendChild() suggestion.
Use this DOM ``` <div id="content" style='display:none;'> <iframe id='contentFrame' src='' /> </div> ``` And this as your script ``` function foo() { var contentDiv = document.getElementById('content'); var contentFrame = document.getElementById('contentFrame'); contentFrame.src = 'foo.html'; contentDiv...
IE caches dynamically added iframe. Why, and how do I prevent it?
[ "", "javascript", "html", "internet-explorer", "dom", "cross-browser", "" ]
I got the image like this (it's a graph): [![Gold Trade Graph](https://i.stack.imgur.com/vyayH.gif)](https://i.stack.imgur.com/vyayH.gif) (source: [kitconet.com](http://www.kitconet.com/charts/metals/platinum/tny_pt_en_caoz_2.gif)) I want to change the colours, so the white is black, the graph line is light blue, e...
This will replace the white color with Gray ``` $imgname = "test.gif"; $im = imagecreatefromgif ($imgname); $index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor imagecolorset($im,$index,92,92,92); // SET NEW COLOR $imgname = "result.gif"; imagegif($im, $imgname ); // save image as gif imagedestroy($i...
I had trouble making this solution work. The image cannot be a true color image. Convert it first with imagetruecolortopalette(); ``` $imgname = "test.gif"; $im = imagecreatefromgif ($imgname); imagetruecolortopalette($im,false, 255); $index = imagecolorclosest ( $im, 255,255,255 ); // get White COlor imagecolorset...
Can I swap colors in image using GD library in PHP?
[ "", "php", "colors", "gd", "swap", "imagefilter", "" ]
I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm ...
Use the LABEL tag: <http://www.w3schools.com/tags/tag_label.asp>
clicking on any `<input>` tag triggers the click event of `<p>` tag (because `<input>` tag is inside the `<p>` tag) which then triggers the click event of `<input>` tag leading to an endless loop.
Jquery Event Bubbling CheckBox
[ "", "javascript", "jquery", "events", "" ]
I have one interesting problem. I must parse mail body (regular expression), get some data from mail body, put this data to mail subject and forward this mail to another address. This must be done immediately when mail is received. Is any free WEBMAIL client that allow writing custom filter, or I must make applicatio...
I use this one to parse bounce emails <http://pear.php.net/package/Mail_Mime> good results so far. EDIT: also <http://www.xpertmailer.com/> has a very nice MIME library that can help you.
To get immediate processing of mails without polling, this should be integrated into your mail delivery process (MDA, Mail Delivery Agent). On most Unix boxes, this can be easily done via [procmail](http://www.procmail.org/) and [formail](http://www.stimpy.net/procmail/tutorial/formail.html) (part of procmail). If you...
Mail body parsing - open source mail client (PHP or ASP.NET)
[ "", "php", "asp.net", "email", "" ]
I'm trying to create a randomized maze in C++, but I can't start because I don't know how to create grids or cells. How could I create it? And I also want to create it using ASCII characters. how can i store it in array? (can any one give a sample code and some explanation so i can understand it better) Another questi...
You probably want to store your maze in a 2-dimension char array. You can declare an array with or without initializing it in C++. ``` char a[30][10]; // declares a char array of 30 rows and 10 columns. // declare an array with 3 rows and 3 columns, and provide initial values char ticTacToeBoard[3][3] = {{'x', 'x', ...
Are you looking for [Maze generation algorithms](http://en.wikipedia.org/wiki/Maze_generation_algorithm) ([more](http://www.astrolog.org/labyrnth/algrithm.htm))? Is your problem with the algorithms, or graphics? The typical algorithms work by considering each "cell" in the maze as a vertex of a graph, start with all "...
How can I create cells or grids in C++ for a randomized maze?
[ "", "c++", "algorithm", "data-structures", "maze", "" ]
Is this a good way to implement a Finally-like behavior in standard C++? (Without special pointers) ``` class Exception : public Exception { public: virtual bool isException() { return true; } }; class NoException : public Exception { public: bool isException() { return false; } }; Object *myObject = 0; tr...
The standard answer is to use some variant of [resource-allocation-is-initialization](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) abbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the ...
No. The Standard way to build a finally like way is to separate the concerns (<http://en.wikipedia.org/wiki/Separation_of_concerns>) and make objects that are used within the try block automatically release resources in their destructor (called "Scope Bound Resource Management"). Since destructors run deterministically...
Implementation of finally in C++
[ "", "c++", "exception", "try-catch", "throw", "finally", "" ]
I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP. I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.
Django has some OLAP features that are nearing release. Read <http://www.eflorenzano.com/blog/post/secrets-django-orm/> <http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html>, also If you have a proper star schema design in the first place, then one-dimensional results can have the following form. ``` fr...
Same thing as *kpw*, I write my own stuff, except that it is exclusively for Django : <https://code.google.com/p/django-cube/>
Any Python OLAP/MDX ORM engines?
[ "", "python", "django", "orm", "olap", "mdx", "" ]
I am implementing a tree think of it as a folder structure so I have a class that looks like: ``` public class Folder { //Various Props like Name etc. public IList<Folder> Children{get;} public Folder Parent {get;} } ``` Now what I want is to be able to walk up and down the tree so given a root I can find...
After looking [on MSDN](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) you could try this: ``` List<Folder> children; public ReadOnlyCollection<Folder> Children { get { return this.children.AsReadOnly(); } } ``` If your private member must be declared as an IList then we can copy that into a list and the...
Personally, I'd go with method 1. Allowing client code to manipulate the Children collection directly violates encapsulation in any case, so 'locking' the Children collection is the Right Thing™. The 'proper' strategy for keeping your node relationships correct depends on the needs of your clients. I'm presuming that ...
Implementing a tree in c# managing parent-child
[ "", "c#", "nhibernate", "design-patterns", "tree", "" ]
Is there any way to force PHP to blow up (error, whatever) if I misspell a variable name? What about if I'm using an instance of a class and I spell the name of a variable wrong? [I know that I should just get used to it, but maybe there's a way to enforce name checking?] Thanks! **Edit:** Sorry, that wasn't very sp...
Here is something I whipped up really quickly to show how you can trigger errors when something like that happens: ``` <?php error_reporting( E_ALL | E_STRICT ); class Joe { public $lastName; public function __set( $name, $value ) { if ( !property_exists( $this, $name ) ) { trigger_error...
You could try: ``` error_reporting(E_ALL|E_STRICT); ``` EDIT: OK, I've now read the updated question. I think you're out of luck. That's valid in PHP. Some say it's a feature. :)
Force PHP to error on non-declared variables? In objects?
[ "", "php", "typechecking", "" ]
I need to remove multiple items from a Dictionary. A simple way to do that is as follows : ``` List<string> keystoremove= new List<string>(); foreach (KeyValuePair<string,object> k in MyCollection) if (k.Value.Member==foo) keystoremove.Add(k.Key); foreach (string s in keystoremove) MyCollect...
Here's an alternate way ``` foreach ( var s in MyCollection.Where(kv => kv.Value.Member == foo).ToList() ) { MyCollection.Remove(s.Key); } ``` Pushing the code into a list directly allows you to avoid the "removing while enumerating" problem. The `.ToList()` will force the enumeration before the foreach really star...
you can create an [extension method](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods): ``` public static class DictionaryExtensions { public static void RemoveAll<TKey, TValue>(this IDictionary<TKey, TValue> dict, Func<TValue, bool> predicate) { ...
Best way to remove multiple items matching a predicate from a .NET Dictionary?
[ "", "c#", ".net", "linq", "collections", "dictionary", "" ]
I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?
My automatic response would be [WebFaction](http://www.webfaction.com/). I haven't personally hosted with them, but they are primarily Python-oriented (founded by the guy who wrote CherryPy, for example, and as far as I know they were the first to roll out [Python 3.0 support](http://blog.webfaction.com/python-3-0-is-...
I am a big fan of [Slicehost](http://www.slicehost.com/) -- you get root access to a virtual server that takes about 2 minutes to install from stock OS images. The 256m slice, which has been enough for me, is US$20/mo -- it is cheaper than keeping an old box plugged in, and easy to back up. Very easy to recommend.
For Python support, what company would be best to get hosting from?
[ "", "python", "web-hosting", "wsgi", "" ]
Is there a tool that can parse C++ files within a project and generate UML from it?
Here are a few options: Step-by-Step Guide to Reverse Engineering Code into UML Diagrams with Microsoft Visio 2000 - <http://msdn.microsoft.com/en-us/library/aa140255(office.10).aspx> BoUML - <https://www.bouml.fr/features.html> StarUML - <https://staruml.io/> Reverse engineering of the UML class diagram from C++ c...
If its just diagrams that you want, [doxygen](http://www.doxygen.org) does a pretty good job.
Generating UML from C++ code?
[ "", "c++", "uml", "" ]
I've got a list of People that are returned from an external app and I'm creating an exclusion list in my local app to give me the option of manually removing people from the list. I have a composite key which I have created that is common to both and I want to find an efficient way of removing people from my List usi...
Have a look at the [Except](http://msdn.microsoft.com/en-us/library/bb336390.aspx) method, which you use like this: ``` var resultingList = listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer) ``` You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. Th...
I would just use the FindAll method on the List class. i.e.: ``` List<Person> filteredResults = people.FindAll(p => return !exclusions.Contains(p)); ``` Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.
Filtering lists using LINQ
[ "", "c#", "linq", "list", "linq-to-objects", "" ]
I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and i...
If you have `numpy` and `scipy` available (and if you are manipulating large arrays in Python, I would recommend them), then the [`scipy.misc.pilutil.toimage`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.toimage.html) function is very handy. A simple example: ``` import numpy as np import scipy.mis...
``` import Image im= Image.new('RGB', (1024, 1024)) im.putdata([(255,0,0), (0,255,0), (0,0,255)]) im.save('test.png') ``` Puts a red, green and blue pixel in the top-left of the image. `im.fromstring()` is faster still if you prefer to deal with byte values.
What is the fastest way to draw an image from discrete pixel values in Python?
[ "", "python", "image", "python-imaging-library", "" ]
I have a CMS with a WYSIWYG editor which produces pretty good xhtml. Based on this fact, I think a HTML parser might be slightly overkill for this small job. I am intending to use regular expressions but so far have been unable to get mine to match what I'm after. I'm using PHP5. I need to match the content of the 3...
This should work as long as you don't have nested p/ul/ol tags: ``` preg_match_all("<(?:p|ul|ol)>(.*?)</(?:p|ul|ol)>", $string, $matches) ``` `?:` prevents anything in the parens from being included in `$matches` and `.*?` prevents the regex from matching past the end of another tag.
I think I just figured it out ``` preg_match_all('/<(p|ul|ol)>(.*)<\/(p|ul|ol)>/iU', $content, $blockElements); ```
Getting the content of XHTML tags: p, ul and/or ol from string
[ "", "php", "regex", "" ]
I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much. If I have this: ``` A = '1,2,3,4' B = [int(x) for x in A.split(',')] B results in [1, 2, 3, 4] ``` which is what...
How about this: ``` A = '1, 2,,3,4 ' B = [int(x) for x in A.split(',') if x.strip()] ``` x.strip() trims whitespace from the string, which will make it empty if the string is all whitespace. An empty string is "false" in a boolean context, so it's filtered by the if part of the list comprehension.
For the sake of completeness, I will answer this seven year old question: The C program that uses strtok: ``` int main() { char myLine[]="This is;a-line,with pieces"; char *p; for(p=strtok(myLine, " ;-,"); p != NULL; p=strtok(NULL, " ;-,")) { printf("piece=%s\n", p); } } ``` can be accompl...
How do I do what strtok() does in C, in Python?
[ "", "python", "" ]
What I mean is, I'm looking for really short code that returns the lower value. for example: ``` a=[1,2,3,4,5,6,7,8,9,10] b=[1,2,3,4,5,6,7,8] len(a) = 10 len(b) = 8 if (fill-this-in): print(lesser-value) ``` And I forgot to add that if b is lower than a, I want b returned - not len(b) - the variable b.
``` print(min(a, b)) ```
You're not hugely clear about what you want, so some alternatives. Given the following two lists: ``` a = [1,2,3,4,5,6,7,8,9,10] b = [1,2,3,4,5,6,7,8] ``` To print the shortest list, you can just do.. ``` >>> print(min(a, b)) [1, 2, 3, 4, 5, 6, 7, 8] ``` To get the shortest length as an number, you can either `min`...
Short Python Code to say "Pick the lower value"?
[ "", "python", "code-snippets", "" ]
I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good examp...
**Update**: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and **udev**, I keep the Hal version for historical reasons. This is basically the [example in the pyudev documentation](http://pyudev.readthedocs.org/en/latest/a...
Here is a solution in 5 lines. ``` import pyudev context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') for device in iter(monitor.poll, None): if device.action == 'add': print('{} connected'.format(device)) # do something very interesting her...
How can I listen for 'usb device inserted' events in Linux, in Python?
[ "", "python", "linux", "usb", "" ]
I run Selenium tests with Selenium RC from .NET (c#). In some cases, I would like to keep the test case source as HTML (to be able to modify it from Selenium IDE), but I would like to run/include these tests from my c# unit tests. Maybe it is obvious, but I can't find the API method in the Selenium Core to achieve th...
I have asked this question some time ago, and since then I have moved forward in automated functional testing, more to the BDD/ATDD/Specification by Example direction with [SpecFlow](http://www.specflow.org). I only realize it now however that I have implemented a solution for this concrete question during my experime...
I don't think there was a way to do this the last time I used Selenium RC .NET
How to run a recorded (HTML) selenium test from .NET
[ "", "c#", "testing", "selenium", "" ]
I want to get the ASCII value of characters in a string in C#. If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters. How can I get ASCII values in C#?
From [MSDN](http://msdn.microsoft.com/en-us/library/system.text.encoding.convert(VS.71).aspx) ``` string value = "9quali52ty3"; // Convert the string into a byte[]. byte[] asciiBytes = Encoding.ASCII.GetBytes(value); ``` You now have an array of the ASCII value of the bytes. I got the following: 57 113 117 97 108 1...
``` string s = "9quali52ty3"; foreach(char c in s) { Console.WriteLine((int)c); } ```
How to get ASCII value of string in C#
[ "", "c#", "encoding", "ascii", "" ]
Does \* have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: ``` def get(self, *a, **kw) ``` Would you please explain it to me or point out where I can find an answer (Google interprets the \* as wild card character and thus I cannot find a satisfactory answer).
See [Function Definitions](https://docs.python.org/2.7/reference/compound_stmts.html#function-definitions) in the Language Reference. > If the form `*identifier` is > present, it is initialized to a tuple > receiving any excess positional > parameters, defaulting to the empty > tuple. If the form `**identifier` is > p...
I only have one thing to add that wasn't clear from the other answers (for completeness's sake). You may also use the stars when calling the function. For example, say you have code like this: ``` >>> def foo(*args): ... print(args) ... >>> l = [1,2,3,4,5] ``` You can pass the list l into foo like so... ``` >>>...
What does asterisk * mean in Python?
[ "", "python", "" ]
In a C++ project that uses smart pointers, such as `boost::shared_ptr`, what is a good design philosophy regarding use of "**`this`**"? Consider that: * It's dangerous to store the raw pointer contained in any smart pointer for later use. You've given up control of object deletion and trust the smart pointer to do it...
While i don't have a general answer or some idiom, there is [`boost::enable_shared_from_this`](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/enable_shared_from_this.html) . It allows you to get a shared\_ptr managing an object that is already managed by shared\_ptr. Since in a member function you have no referenc...
# Wrong question > In a C++ project that uses smart pointers The issue has nothing to do with smart pointers actually. It is only about ownership. ## Smart pointers are just tools They change nothing WRT the concept of ownership, esp. **the need to have well-defined ownership in your program**, the fact that owners...
smart pointers + "this" considered harmful?
[ "", "c++", "pointers", "this", "smart-pointers", "shared-ptr", "" ]
Is it possible to update more than one local variable in a single select? Something like: ``` set @variableOne = avg(someColumn), @variableTwo = avg(otherColumn) from tblTable ``` It seems a bit wasteful to make two separate select operations for something as trivial as this task: ``` set @variableOne =...
Something like this: ``` select @var1 = avg(someColumn), @var2 = avg(otherColumn) from theTable ```
You can use SELECT assignment to assign multiple variables. This code generates a single row of constants and assigns each to a variable. ``` SELECT @var1 = 1, @var2 = 'Zeus' ``` You can even query tables and do assignment that way: ``` SELECT @var1 = c.Column1, @var2 = c.Column2, FROM Customers c WHERE c....
T-SQL, updating more than one variable in a single select
[ "", "sql", "sql-server", "t-sql", "" ]
I have a file input element that needs to be cloned after the user has browsed and selected a file to upload. I started by using obj.cloneNode() and everything worked fine, that is until I tried using it in IE. I've since tried using jQuery's clone method as follows: ``` var tmp = jQuery('#categoryImageFileInput_'+id...
Editing the file form field is a security risk and thus is disabled on most browsers and *should* be disabled on firefox. It is not a good idea to rely on this feature. Imagine if somebody was able, using javascript, to change a hidden file upload field to, lets say, c:\Users\Person\Documents\Finances Or C:\Users\Pe...
Guessing that you need this functionality so you can clone the input element and put it into a hidden form which then gets POSTed to a hidden iframe... IE's element.clone() implementation doesn't carry over the value for input type="file", so you have to go the other way around: ``` // Clone the "real" input element ...
Clone a file input element in Javascript
[ "", "javascript", "jquery", "internet-explorer", "clone", "" ]
I asked about getting iTextSharp to render a PDF from HTML and a CSS sheet before [here](https://stackoverflow.com/questions/430280/render-pdf-in-itextsharp-from-html-with-css) but it seems like that may not be possible... So I guess I will have to try something else. Is there an open source .NET/C# library out there ...
I've always used it on the command line and not as a library, but [HTMLDOC](https://www.msweet.org/htmldoc/) gives me excellent results, and it handles at least *some* CSS (I couldn't easily see how much). Here's a sample command line ``` htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf `...
This command line tool is the business! <https://wkhtmltopdf.org/> It uses webkit rendering engine(used in safari and KDE), I tested it on some complex sites and it was by far better than any other tool.
Open Source HTML to PDF Renderer with Full CSS Support
[ "", "c#", "html", "css", "pdf", "pdf-generation", "" ]
Any nice **Paneled user interface** component COM/**ActiveX**/Source-code for **C#**/VB? Like what VS has internally: * Dock to screen edges * Slide open/close (unpinned) * Pin open * Group in tabs And if possible, **open-source**/free. Well, because otherwise I'd have to develop an interface system myself.
**[DockPanel Suite!](http://sourceforge.net/projects/dockpanelsuite/)** Its an open-source **docking library** for .NET Windows Forms development which **mimics Visual Studio .NET**.
We use the DevExpress (devexpress.com) Component Suite, which has a Docking Manager that does that sort of thing.
Good panel interface component for C#?
[ "", "c#", "vb.net", "user-interface", "activex", "" ]
Is there a quick way to set an HTML text input (`<input type=text />`) to only allow numeric keystrokes (plus '.')?
## JavaScript You can filter the input values of a text `<input>` with the following `setInputFilter` function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and [all browsers since IE 9](https://c...
Use this DOM ``` <input type='text' onkeypress='validate(event)' /> ``` And this script ``` function validate(evt) { var theEvent = evt || window.event; // Handle paste if (theEvent.type === 'paste') { key = event.clipboardData.getData('text/plain'); } else { // Handle key press var key = theE...
HTML text input allow only numeric input
[ "", "javascript", "jquery", "html", "" ]
How can I use RMI with a applet client behind a firewall? How can I use RMI with a firewalled server and firewalled applet client? (If possible) I know that the RMI server uses port 1099 (by default, but this is configurable); however after this the communication requires a new socket on a different random port. I al...
See <http://java.sun.com/javase/6/docs/technotes/guides/rmi/faq.html#firewall>
If the servers code is in your hand you could also restrict RMI to use a predifined port by providing a custom RMISocketFactory as described here: <http://insidecoffe.blogspot.com/2012/02/firewall-friently-rmi-port-fixing.html> (Note specially the hint that it may cause problems if you use JMX in parallel)
How to use RMI with applet client behind a firewall?
[ "", "java", "applet", "rmi", "firewall", "" ]
How do I get the current time in Python?
Use [`datetime`](https://docs.python.org/3/library/datetime.html): ``` >>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> print(now) 2009-01-06 15:08:24.789150 ``` For just the clock time without the date: ``` >>> now.time() datetime.time(15, 8, 24, 7891...
Use [`time.strftime()`](http://docs.python.org/3.3/library/time.html?highlight=time.strftime#time.strftime): ``` >>> from time import gmtime, strftime >>> strftime("%Y-%m-%d %H:%M:%S", gmtime()) '2009-01-05 22:14:39' ```
How do I get the current time in Python?
[ "", "python", "datetime", "time", "" ]
I'm developing a LoB application in Java after a long absence from the platform (having spent the last 8 years or so entrenched in Fortran, C, a smidgin of C++ and latterly .Net). Java, the language, is not much changed from how I remember it. I like it's strengths and I can work around its weaknesses - the platform h...
There are two reasons I can think of not to use Groovy (or Jython, or JRuby): * If you really, truly need performance * If you will miss static type checking Those are both big ifs. Performance is probably less of a factor in most apps than people think, and static type checking is a religious issue. That said, one s...
If you use Groovy, you're basically throwing away useful information about types. This leaves your code "groovy": nice and concise. ``` Bird b ``` becomes ``` def b ``` Plus you get to play with all the meta-class stuff and dynamic method calls which are a torture in Java. However -- and **yes** I have tried Intel...
Are there compelling reasons not to use Groovy?
[ "", "java", "groovy", "jvm", "" ]
**Overall Plan** Get my class information to automatically optimize and select my uni class timetable Overall Algorithm 1. Logon to the website using its Enterprise Sign On Engine login 2. Find my current semester and its related subjects (pre setup) 3. Navigate to the right page and get the data from each rel...
Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me... Still, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance. So, you have two constraints: 1....
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) was mentioned here a few times, e.g [get-list-of-xml-attribute-values-in-python](https://stackoverflow.com/questions/87317/get-list-of-xml-attribute-values-in-python). > Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like...
Automated Class timetable optimize crawler?
[ "", "python", "screen-scraping", "scheduling", "" ]
I see in MSDN links such as "CompareOrdinal Overloads". How can I write such a link in C#? I tried: ``` <seealso cref="MyMethod">MyMethod Overloads</seealso> ``` But the compiler gives me a warning about being an ambiguous reference for the method which has other overloads. (Beginner question: do I actually need to...
Xml documentation doesn't have a means to reference all overloads of a method. The most popular documentation generator for C# projects is Sandcastle. It will automatically create a link to an overloads list page if necessary. Hence in a members list page the name of an overloaded method will appear only once, clickin...
To target *specific* members, I believe you just match the signature: ``` /// <seealso cref="Foo(int)"/> static void Foo() { } /// <seealso cref="Foo()"/> /// <seealso cref="Foo(float)"/> <------ complains static void Foo(int a) { } ``` To be honest, I'm not sure how to generate an "all overloads" link; I'd assume th...
How to make a cref to method overloads in a <seealso> tag in C#?
[ "", "c#", "xml-documentation", "" ]
I need to filter result sets from sql server based on selections from a multi-select list box. I've been through the idea of doing an instring to determine if the row value exists in the selected filter values, but that's prone to partial matches (e.g. Car matches Carpet). I also went through splitting the string into...
I solved this one by writing a table-valued function (we're using 2005) which takes a delimited string and returns a table. You can then join to that or use WHERE EXISTS or WHERE x IN. We haven't done full stress testing yet, but with limited use and reasonably small sets of items I think that performance should be ok....
> I've been through the idea of doing an > instring to determine if the row value > exists in the selected filter values, > but that's prone to partial matches > (e.g. Car matches Carpet) It sounds to me like you aren't including a unique ID, or possibly the primary key as part of values in your list box. Ideally each...
Filtering With Multi-Select Boxes With SQL Server
[ "", "sql", "sql-server", "listbox", "" ]
I've stumbled across [this great post](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/) about validating parameters in C#, and now I wonder how to implement something similar in C++. The main thing I like about this stuff is that is does not cost anything until the first validation fail...
Other than the fact that C++ does not have extension methods (which prevents being able to add in new validations as easily) it should be too hard. ``` class Validation { vector<string> *errors; void AddError(const string &error) { if (errors == NULL) errors = new vector<string>(); errors->pu...
Can't say much to the rest of the question, but I did want to point out this: > Though I'd guess that allocating > something like a std::vector on the > stack should be for free (is this > actually true? I'd suspect an empty > vector does no allocations on the > heap, right?) No. You still have to allocate any other ...
Lazy object creation in C++, or how to do zero-cost validation
[ "", "c++", "validation", "" ]
I have a form on an HTML page with multiple submit buttons that perform different actions. However, when the user is typing a value into a text input and hit enters, the browsers generally act as though the next submit button sequentially was activated. I want a particular action to occur, so one solution I found was t...
One way would be to remove all of the submit buttons and use input buttons to submit the form programatically. This would remove the ability to submit the form by hitting the enter key in a textbox. You could also leave one submit button as the default submit functionality, and use regular button inputs for the others ...
The invisible default submit action is a reasonable approach and doesn't drag JavaScript into the equation. However form elements with 'display: none' aren't generally reliable. I tend to use an absolutely-positioned submit button before the others on the page, positioned off the left-hand-side of the page. It's still ...
Use Javascript to change which submit is activated on enter key press
[ "", "javascript", "html", "webforms", "submit", "user-input", "" ]
Pretty self-explanatory, I tried google and got a lot of the dreaded expertsexchange, I searched here as well to no avail. An online tutorial or example would be best. Thanks guys.
If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model: ``` struct Customer { int id; std::string first_nam...
More information would be useful. But the simplest form: ``` #include <iostream> #include <sstream> #include <fstream> #include <string> int main() { std::ifstream data("plop.csv"); std::string line; while(std::getline(data,line)) { std::stringstream lineStream(line); std::string ...
How can I read and manipulate CSV file data in C++?
[ "", "c++", "csv", "" ]
I was wondering what is the best way to parse a DateTime object to your SQL server. Where you are generating the SQL in code. I have always used something like `DateTime.Now.TolongDateString()` and had good results, apart from today where i got a error, and it made me think. ``` System.Data.SqlClient.SqlException: C...
there are only 2 safe formats ISO and ISO8601 ISO = yymmdd ISO8601 = yyyy-mm-dd Thh:mm:ss:mmm(no spaces) (notice the T) See also here: [Setting a standard DateFormat for SQL Server](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/setting-a-standard-dateformat-for-sql-se)
Why not parameterise the query and pass the DateTime value as a SQL DateTime input param? e.g `INSERT INTO SomeTable (Blah, MyDateTime) VALUES (1, @MyDateTime)` Then you can be really sure. Even if you're generating the SQL you should be able to handle this specifically?
Best way to parse DateTime to SQL server
[ "", ".net", "sql", "sql-server", "t-sql", "datetime", "" ]
Given `$displayHeight = "800";`, replace whatever number is at `800` with int value `y_res`. ``` resultString = Regex.Replace( im_cfg_contents, @"\$displayHeight[\s]*=[\s]*""(.*)"";", Convert.ToString(y_res)); ``` In Python I'd use re.sub and it would work. In .NET it replaces the whole line, not the ma...
Building on a couple of the answers already posted. The Zero-width assertion allows you to do a regular expression match without placing those characters in the match. By placing the first part of the string in a group we've separated it from the digits that you want to be replaced. Then by using a zero-width lookbehin...
Try this: ``` resultString = Regex.Replace( im_cfg_contents, @"\$displayHeight[\s]*=[\s]*""(.*)"";", @"\$displayHeight = """ + Convert.ToString(y_res) + @""";"); ```
C# regex replace unexpected behavior
[ "", "c#", ".net", "regex", "" ]
I am working on a project that needs to use a database driven MVC scheme where the route to the controllers and views are controlled through a single database table. However, I haven't been able to find any tutorials that demonstrate this with a current version of the framework (they all appear to have been written sev...
I realized that a more elegant approach is indeed to use a router, but for that you would need to create a custom one by extending the Zend\_Controller\_Router\_Abstract class and implementing the "route" method. You get a Zend\_Controller\_Request\_Abstract object as the parameter of the "route" method. There you can...
You can also use the routeStartup() method in your plugin. eg: ``` class My_Plugin_PageRoute extends Zend_Controller_Plugin_Abstract { public function routeStartup () { $front = Zend_Controller_Front::getInstance(); $pages = new Model_Pages(); $page_data = $page...
Tutorials For Database-Driven Routing in Zend Framework?
[ "", "php", "zend-framework", "url-routing", "model-view-controller", "database-driven", "" ]
What is the meaning of the .NET 3.5 extension method `Enumerable.First()` when you call it on an instance of the `Dictionary` collection? Does the set of keys determine which item is first, or is it just not defined?
Well, I believe the set of keys *will* determine which item is first, but not in a well-defined (or easy to predict) way. In other words, don't assume that it will always work the same way - it's as unsafe as relying on a hash code implementation staying the same between runs. EDIT: I believe that in fact, the orderin...
If you need the first item in a dictionary, you're best using a SortedDictionary. I would think the First() method will just return the first item which happens to be at the top, but not necessarily the first one that was added.
Who's on Dictionary<>.First()?
[ "", "c#", ".net", "" ]
I want to run a console application that will output a file. I user the following code: ``` Process barProcess = Process.Start("bar.exe", @"C:\foo.txt"); ``` When this runs the console window appears. I want to hide the console window so it is not seen by the user. Is this possible? Is using Process.Start the best ...
``` Process p = new Process(); StreamReader sr; StreamReader se; StreamWriter sw; ProcessStartInfo psi = new ProcessStartInfo(@"bar.exe"); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.Redire...
Check into ProcessStartInfo and set the WindowStyle = ProcessWindowStyle.Hidden and the CreateNoWindow = true.
How do I hide a console application user interface when using Process.Start?
[ "", "c#", ".net", "" ]
A little background: I'm creating a set of adapters to allow communication with mobile devices over different cellular networks. This will be achieved using a class factory pattern. At least one of the networks requires a service reference to communicate with their devices through a web service. So far I've got 3 ass...
In the end, I just removed the service reference and added a web reference [i.e. did it the 2.0 way]. For some reason the web reference will access its own app.config instead of the main application's app.config. Far easier than the alternative...
You can set all the options programatically.
How do I move service references to their own assembly?
[ "", "c#", ".net", "asp.net", "vb.net", "web-services", "" ]
we have an application that needs to send out various different types of template email. The current code is very cumbersome and not very flexible. Does any one konw of a library to help with this type of work... We are looking for some kind of templating library for email.
[StringTemplate](http://www.stringtemplate.org) is also a very nice template engine.
Perhaps [Apache Velocity](https://velocity.apache.org/) could work for you?
Suggestions for Java email templating?
[ "", "java", "email", "frameworks", "templates", "" ]
I want to create variables as `a1`,`a2`,`a3`...`a10`. For that I used a for loop. As the variable in loop increments I need to create a variable as above. Can anyone give me an idea? At the time of creation I also need to be able to assign values to them. That's where I'm getting syntax error.
Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important: ``` data = {} for i in range(0, 10): data['a%d' % i] = i >>>data {'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8} ``` I would add that thi...
Usually, we use a list, not a bunch of individual variables. ``` a = 10*[0] a[0], a[1], a[2], a[9] ```
need help-variable creation in Python
[ "", "python", "variables", "" ]
I have a table in PostgreSQL where the schema looks like this: ``` CREATE TABLE "foo_table" ( "id" serial NOT NULL PRIMARY KEY, "permalink" varchar(200) NOT NULL, "text" varchar(512) NOT NULL, "timestamp" timestamp with time zone NOT NULL ) ``` Now I want to make the permalink unique across the table ...
I figured it out from the PostgreSQL docs, the exact syntax is: ``` ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn); ``` Thanks [Fred](https://stackoverflow.com/users/55774/frederik-gheysels).
Or, have the DB automatically assign a constraint name using: ``` ALTER TABLE foo ADD UNIQUE (thecolumn); ```
How do I ALTER a PostgreSQL table and make a column unique?
[ "", "sql", "postgresql", "unique-constraint", "" ]