Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Does javascript use immutable or mutable strings? Do I need a "string builder"?
They are immutable. You cannot change a character within a string with something like `var myString = "abbdef"; myString[2] = 'c'`. The string manipulation methods such as [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim), [`slice`](https://developer.mozilla.org/en-U...
from the [rhino book](http://oreilly.com/catalog/9780596000486/): > In JavaScript, strings are immutable objects, which means that the > characters within them may not be changed and that any operations on > strings actually create new strings. Strings are assigned by > reference, not by value. In general, when an obj...
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
[ "", "javascript", "string", "" ]
I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example: **.h file** ``` class foo { public: template <typename T> void do(const T& t); }; ``` **.cpp file** ``` temp...
The problem you describe can be solved by defining the template in the header, or via the approach you describe above. I recommend reading the following points from the [C++ FAQ Lite](https://isocpp.org/wiki/faq/templates): * [Why can’t I separate the definition of my templates class from its declaration and put it i...
For others on this page wondering what the correct syntax is (as did I) for explicit template instantiation (or at least in VS2008), its the following... In your .h file... ``` template<typename T> class foo { public: void bar(const T &t); }; ``` And in your .cpp file ``` template <class T> void foo<T>::bar(con...
Storing C++ template function definitions in a .CPP file
[ "", "c++", "templates", "" ]
Is there a tutotial or help file, suitable for a beginner c# programmer to use.
The primary documentation for the Farseer Physics engine is on the homepage. <http://www.codeplex.com/FarseerPhysics/Wiki/View.aspx?title=Documentation&referringTitle=Home> You can also check out the source code, they have a demos folder in there, though it's only got one example, but it can show you how to implement...
I realize this is an old question, but for future searchers I will post a few links: **Farseer Physics Helper** Physics helper for Blend makes it very easy to create realistic looking games or demos using practically no code :) <http://physicshelper.codeplex.com/> **Farseer Physics Engine Simple Samples** Very sim...
Farseer Physics Tutorials, Help files
[ "", "c#", "silverlight", ".net-3.5", "farseer", "" ]
What kind of performance implications are there to consider when using try-catch statements in php 5? I've read some old and seemingly conflicting information on this subject on the web before. A lot of the framework I currently have to work with was created on php 4 and lacks many of the niceties of php 5. So, I don'...
One thing to consider is that the cost of a try block where no exception is thrown is a different question from the cost of actually throwing and catching an exception. If exceptions are only thrown in failure cases, you almost certainly don't care about performance, since you won't fail very many times per execution ...
I was bored and profiled the following (I left the timing code out): ``` function no_except($a, $b) { $a += $b; return $a; } function except($a, $b) { try { $a += $b; } catch (Exception $e) {} return $a; } ``` using two different loops: ``` echo 'no except with no surrounding try'; for ...
Performance of try-catch in php
[ "", "php", "performance", "exception", "try-catch", "" ]
I have a table with a "Date" column, and I would like to do a query that does the following: If the date is a **Monday**, **Tuesday**, **Wednesday**, or **Thursday**, the displayed date should be shifted up by 1 day, as in ``` DATEADD(day, 1, [Date]) ``` On the other hand, if it is a **Friday**, the displayed date s...
Here is how I would do it. I do recommend a function like above if you will be using this in other places. ``` CASE WHEN DATEPART(dw, [Date]) IN (2,3,4,5) THEN DATEADD(d, 1, [Date]) WHEN DATEPART(dw, [Date]) = 6 THEN DATEADD(d, 3, [Date]) ELSE [Date] END AS [ConvertedDate] ```
``` CREATE FUNCTION dbo.GetNextWDay(@Day datetime) RETURNS DATETIME AS BEGIN DECLARE @ReturnDate DateTime set @ReturnDate = dateadd(dd, 1, @Day) if (select datename(@ReturnDate))) = 'Saturday' set @ReturnDate = dateadd(dd, 2, @ReturnDate) if (select datename(@ReturnDate) = 'Sunday' s...
SQL Query Help: Transforming Dates In A Non-Trivial Way
[ "", "sql", "sql-server", "date", "sql-server-2000", "dateadd", "" ]
I know next to nothing when it comes to the how and why of https connections. Obviously, when I'm transmitting secure data like passwords or especially credit card information, https is a critical tool. What do I need to know about it, though? What are the most common mistakes you see developers making when they implem...
An HTTPS, or Secure Sockets Layer (SSL) certificate is served for a site, and is typically signed by a Certificate Authority (CA), which is effectively a trusted 3rd party that verifies some basic details about your site, and certifies it for use in browsers. If your browser trusts the CA, then it trusts any certificat...
I'm not going to go in depth on SSL in general, gregmac did a great job on that, see below ;-). However, some of the most common (and critical) mistakes made (not specifically PHP) with regards to use of SSL/TLS: 1. Allowing HTTP when you should be enforcing HTTPS 2. Retrieving some resources over HTTP from an HTTPS ...
What does a PHP developer need to know about https / secure socket layer connections?
[ "", "php", "security", "ssl", "https", "" ]
I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe: ``` windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... ``` I tried loading the icon using: ``` hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_...
@efotinis: You're right. Here is a workaround until py2exe gets fixed and you don't want to include the same icon twice: ``` hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True) ``` Be aware that **1** is not the ID you gave the icon in setup.py (which is the icon group ID)...
Well, well... I installed py2exe and I think it's a bug. In py2exe\_util.c they should init `rt_icon_id` to 1 instead of 0. The way it is now, it's impossible to load the first format of the first icon using LoadIcon/LoadImage. I'll notify the developers about this if it's not already a known issue. A workaround, in ...
How do you load an embedded icon from an exe file with PyWin32?
[ "", "python", "icons", "exe", "pywin32", "" ]
We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an...
Call DirectXSetupGetVersion: <http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion> You'll need to include dsetup.h Here's the sample code from the site: ``` DWORD dwVersion; DWORD dwRevision; if (DirectXSetupGetVersion(&dwVersion, &dwRevision)) { printf("DirectX versi...
According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \Samples\Multimedia\DXMisc\GetDXVer.
How to determine which version of Direct3D is installed?
[ "", "c++", "windows", "direct3d", "" ]
No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. ``` IDLE 1.2.2 ==== No Subprocess ==== >>> import unittest >>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEq...
Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing ``` unittest.main() ``` to ``` unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test)) ``` More information is available [here](http://docs.python.org/library/unittest.html#basic-ex...
In new Python 2.7 release, [unittest.main()](http://docs.python.org/library/unittest.html#unittest.main) has a new argument. If 'exit' is set to `False`, `sys.exit()` is not called during the execution of `unittest.main()`.
Unittest causing sys.exit()
[ "", "python", "unit-testing", "" ]
I have a table called OffDays, where weekends and holiday dates are kept. I have a table called LeadTime where amount of time (in days) for a product to be manufactured is stored. Finally I have a table called Order where a product and the order date is kept. Is it possible to query when a product will be finished man...
You can generate a table of working days in advance. ``` WDId | WDDate -----+----------- 4200 | 2008-01-08 4201 | 2008-01-09 4202 | 2008-01-12 4203 | 2008-01-13 4204 | 2008-01-16 4205 | 2008-01-17 ``` Then do a query such as ``` SELECT DeliveryDay.WDDate FROM WorkingDay OrderDay, WorkingDay DeliveryDay, LeadTime, Or...
The best approach is to use a Calendar table. See <http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html>. Then your query could look something like: ``` SELECT c.dt, l.*, o.*, c.* FROM [statistics].dbo.[calendar] c, ...
Non-iterative / Non-looping Way To Calculate Effective Date?
[ "", "sql", "date", "" ]
I want to link to bookmark on a page (mysite.com/mypage.htm#bookmark) AND visually highlight the item that was bookmarked (maybe having a red border). Naturally, there would be multiple items bookmarked. So that if someone clicked on #bookmark2 then *that* other area would be highlighted). I can see how to do that wit...
In your css you need to define ``` a.highlight {border:1px solid red;} ``` or something similar Then using jQuery, ``` $(document).ready ( function () { //Work as soon as the DOM is ready for parsing var id = location.hash.substr(1); //Get the word after the hash from the url if (id) $('#'+id).addClass('hi...
You can also use the `target` pseudo-class in CSS: ``` <html> <head> <style type="text/css"> div#test:target { background-color: yellow; } </style> </head> <body> <p><b><a href="#test">Link</a></b></p> <div id="test"> Target </div> </body> </html> ``` Unfortunately the target pseudo class isn't supported by IE ...
Is there a way to highlight the target of a bookmark? (www.site.com/page.htm#bookmark)?
[ "", "javascript", "jquery", "css", "" ]
I have heard there is a way to cheat single inheritance and implement multiple inheritance in Java. Does anyone know how to implement this(with out using interface)? Just out of curiosity ;-)
Sure you can, but it's tricky and you should really consider if that's the way you want to go. The idea is to use scope-based inheritance coupled with type-based one. Which is type-talk for saying that for internal purposes, inner classes "inherit" methods and fields of the outer class. It's a bit like mixins, where ...
SingleMultiple inheritance is not supported by Java, instead it has got interfaces to serve the same purpose. In case you are adamant on using multiple inheritance it should be done in C++.
Cheat single inheritance in Java?
[ "", "java", "oop", "inheritance", "" ]
We have 18 databases that should have identical schemas, but don't. In certain scenarios, a table was added to one, but not the rest. Or, certain stored procedures were required in a handful of databases, but not the others. Or, our DBA forgot to run a script to add views on all of the databases. What is the best way ...
For legacy fixes/cleanup, there are tools, like [SQLCompare](http://www.red-gate.com/products/SQL_Compare/index.htm?gclid=CMvQrZjZ5ZUCFQZqswodnQ8Tfg), that can generate scripts to sync databases. For .NET shops running SQL Server, there is also the [Visual Studio Database Edition](http://msdn.microsoft.com/en-us/vsts2...
[SQL Compare](http://www.red-gate.com/products/SQL_Compare/index.htm) by Red Gate is a great tool for this.
How can I maintain consistent DB schema accross 18 databases (sql server)?
[ "", "sql", "sql-server", "database", "schema", "" ]
I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable. I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object). Let's say some thread is currently iterating...
The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable. You should perhaps add the [volatile](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keyword...
Since the getter `{ return sektioner; }` is called before the new value is put in the field, the old value is returned. Then, the loop `foreach (Sektion s in cache.Sektioner)` uses the value that was received when the getter was called, i.e. the old value. That value will be used throughout the foreach loop.
Updating reference to a member variable in use
[ "", "c#", ".net", "singleton", "" ]
Suppose we have: ``` interface Foo { bool Func(int x); } class Bar: Foo { bool Func(int x) { return (x>0); } } class Baz: Foo { bool Func(int x) { return (x<0); } } ``` Now we can toss around Bar and Baz as a Foos and call their Func methods. Delegates simplify this a little bit: ``` deleg...
There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed...
From a Software Engineering perspective you are right, delegates are much like function interfaces in that they prototype a function interface. They can also be used much in the same kind of way: instead of passing a whole class in that contains the method you need you can pass in just a delegate. This saves a whole l...
Are delegates not just shorthand interfaces?
[ "", "c#", "delegates", "interface", "" ]
using C++Builder 2007, the FindFirstFile and FindNextFile functions doesn't seem to be able to find some files on 64-bit versions of Vista and XP. My test application is 32-bit. If I use them to iterate through the folder C:\Windows\System32\Drivers they only find a handful of files although there are 185 when I issue...
Is there redirection going on? See the remarks on Wow64DisableWow64FsRedirection <http://msdn.microsoft.com/en-gb/library/aa365743.aspx>
I found this on MSDN: *If you are writing a 32-bit application to list all the files in a directory and the application may be run on a 64-bit computer, you should call the Wow64DisableWow64FsRedirectionfunction before calling FindFirstFile and call Wow64RevertWow64FsRedirection after the last call to FindNextFile. Fo...
FindNextFile fails on 64-bit Windows?
[ "", "c++", "64-bit", "c++builder", "" ]
I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser. How do I use jQuery to get the set of images, filter it to broken images then replace the src? --- --I thought it would be easier to do this with jQuery, but it turned out m...
Handle the `onError` event for the image to reassign its source using JavaScript: ``` function imgError(image) { image.onerror = ""; image.src = "/images/noimage.gif"; return true; } ``` ``` <img src="image.png" onerror="imgError(this);"/> ``` Or without a JavaScript function: ``` <img src="image.png" o...
I use the built in `error` handler: ``` $("img").error(function () { $(this).unbind("error").attr("src", "broken.gif"); }); ``` **Edit:** The `error()` method is deprecated in [jquery 1.8](https://api.jquery.com/error/) and higher. Instead, you should use `.on("error")` instead: ``` $("img").on("error", function...
jQuery/JavaScript to replace broken images
[ "", "javascript", "jquery", "html", "broken-image", "" ]
I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day. For example, if Alice worked a job from 15:30 to 19:30 and B...
Create a table with just time in it from midnight to midnight containing each minute of the day. In the data warehouse world we would call this a time dimension. Here's an example: ``` TIME_DIM -id -time_of_day -interval_15 -interval_30 ``` an example of the data in the table would be ``` id time_of_day in...
How about this: Use that "times" table, but with two columns, containing the 15-minute intervals. The from\_times are the 15-minutely times, the to\_times are a second before the next from\_times. For example 12:30:00 to 12:44:59. Now get your person work table, which I've called "activity" here, with start\_time and...
Elegant method for drawing hourly bar chart from time-interval data?
[ "", "sql", "excel", "charts", "group-by", "" ]
Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.
``` SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Tab.Constraint_Type = 'PRIMARY KEY' AND Col.Table_Name = '<your table name>' ```
It's generally recommended practice now to use the `sys.*` views over `INFORMATION_SCHEMA` in SQL Server, so unless you're planning on migrating databases I would use those. Here's how you would do it with the `sys.*` views: ``` SELECT c.name AS column_name, i.name AS index_name, c.is_identity FROM sys.in...
How do you list the primary key of a SQL Server table?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor? ``` Create Table A (id int identity, Fname nvarchar(50), Lname nvarchar(50)) Create Table B (Fname nvarchar(50), Lname nvarchar(50), NewId i...
MBelly is right on the money - But then the trigger will always try and update table B even if that's not required (Because you're also inserting from table C?). Darren is also correct here, you can't get multiple identities back as a result set. Your options are using a cursor and taking the identity for each row you...
Use the ouput clause from 2005: ``` DECLARE @output TABLE (id int) Insert into A (fname, lname) OUTPUT inserted.ID INTO @output SELECT fname, lname FROM B select * from @output ``` now your table variable has the identity values of all the rows you insert.
How to insert multiple records and get the identity value?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with...
Thanks @rofly, the full conversion from string to string is as follows: ``` import time time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")))) ``` My summary of the `time`/`calendar` fu...
First, parse the string into a naive datetime object. This is an instance of `datetime.datetime` with no attached timezone information. See its [documentation](https://docs.python.org/3/library/datetime.html#available-types). Use the [`pytz`](http://pytz.sourceforge.net/) module, which comes with a full list of time z...
How to convert local time string to UTC?
[ "", "python", "datetime", "utc", "localtime", "" ]
For example, given a type param method i'm looking for something like the part in bold > void MyMethod< T >() { > if ( **typeof(T).Implements( *IMyInterface* )** ) > { > > ``` > //Do something > ``` > > else > > ``` > //Do something else > ``` > > } Anwers using C# 3.0 are also welcome, but first drop the .NET ...
[Type.IsAssignableFrom](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx) ``` if(typeof(IMyInterface).IsAssignableFrom(typeof(T))) { // something } else { // something else } ```
I think ``` if (typeof (IMyInterFace).IsAssignableFrom(typeof(T)) ``` should also work: but i don't see an advantage...
What is the easier way to know if a type param implements an interface in c# 2.0?
[ "", "c#", "reflection", "types", "" ]
In C#.NET I am trying to programmatically change the color of the border in a group box. Update: This question was asked when I was working on a winforms system before we switched to .NET.
Building on the previous answer, a better solution that includes the label for the group box: ``` groupBox1.Paint += PaintBorderlessGroupBox; private void PaintBorderlessGroupBox(object sender, PaintEventArgs p) { GroupBox box = (GroupBox)sender; p.Graphics.Clear(SystemColors.Control); p.Graphics.DrawString(box...
Just add paint event. ``` private void groupBox1_Paint(object sender, PaintEventArgs e) { GroupBox box = sender as GroupBox; DrawGroupBox(box, e.Graphics, Color.Red, Color.Blue); } private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor) { if...
How do you change the color of the border on a group box?
[ "", "c#", "winforms", "user-interface", "controls", "groupbox", "" ]
Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# **should** be as easy as ``` DateTime.ParseExact(theDate, "yyyy/MM/dd"); ``` but no, C# forces you to create an IFormatProvider. Is there an app.config friendly way of setting this so I don't need to do this each...
The IFormatProvider argument can be null.
ParseExact needs a culture : consider "yyyy MMM dd". MMM will be a localized month name that uses the current culture.
Parsing exact dates in C# shouldn't force you to create an IFormatProvider
[ "", "c#", ".net", "datetime", "parsing", "globalization", "" ]
How can I get a full call stack for a c++ application developed with Visual Studio 2005? I would like to have a full call stack including the code in the system libraries. Do I have to change some settings in Visual Studio, or do I have to install additional software?
1. Get debug information for all project dependencies. This is specified under the "Configuration Properties -> C/C++ -> General" section of the project properties. 2. On the menu, go to "Tools -> Options" then select "Debugging -> Symbols". 3. Add a new symbol location (the folder icon) that points to Microsoft's free...
Agree with Clay, but for Symbols Server you should get the latest symsrv.DLL from "Debugging Tools For Windows", a free Microsoft download. (Since you explicitly asked what you need to download, I presume you don't have it yet)
How to get a full call stack in Visual Studio 2005?
[ "", "c++", "visual-studio", "debugging", "callstack", "visual-c++-2005", "" ]
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 b...
That depends on how you are running the cherrypy init. If using cherrypy 3.1 syntax, that wold do it: ``` cherrypy.server.socket_host = 'www.machinename.com' cherrypy.engine.start() cherrypy.engine.block() ``` Of course you can have something more fancy, like subclassing the server class, or using config files. Thos...
``` server.socket_host: '0.0.0.0' ``` ...would also work. That's IPv4 INADDR\_ANY, which means, "listen on all interfaces". In a config file, the syntax is: ``` [global] server.socket_host: '0.0.0.0' ``` In code: ``` cherrypy.server.socket_host = '0.0.0.0' ```
How do I configure the ip address with CherryPy?
[ "", "python", "cherrypy", "" ]
I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was acceler...
``` function holdit(btn, action, start, speedup) { var t; var repeat = function () { action(); t = setTimeout(repeat, start); start = start / speedup; } btn.mousedown = function() { repeat(); } btn.mouseup = function () { clearTimeout(t); } }; /* t...
When the button is pressed, call `window.setTimeout` with your intended time and the function `x`, and set the timer again at the end of `x` but this time with a smaller interval. Clear the timeout using `window.clearTimeout` upon release of the mouse button.
Need javascript code for button press and hold
[ "", "javascript", "mouse", "" ]
I have huge 3D arrays of numbers in my .NET application. I need to convert them to a 1D array to pass it to a COM library. Is there a way to convert the array without making a copy of all the data? I can do the conversion like this, but then I use twice the ammount of memory which is an issue in my application: ``` ...
I don't believe the way C# stores that data in memory would make it feasible the same way a simple cast in C would. Why not use a 1d array to begin with and perhaps make a class for the type so you can access it in your program as if it were a 3d array?
Unfortunately, C# arrays aren't guaranteed to be in contiguous memory like they are in closer-to-the-metal languages like C. So, no. There's no way to convert double[,,] to double[] without an element-by-element copy.
Is is possible to convert C# double[,,] array to double[] without making a copy
[ "", "c#", ".net", "arrays", "" ]
I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like. ``` [ConfigurationElementType(typeof(MyCustomHandlerData))] public class MyCustomHandle...
You can also check IsSpecialName is true. this will be true in a property (amongst other things) At the il level the methods are exposed as follows (using Environment.ExitCode as example): ``` .method public hidebysig specialname static int32 get_ExitCode() cil managed .method public hidebysig specialname static void...
A couple of you mentioned using the "IsSpecialName" property of the MethodBase type. While it is true that the will return true for property "gets" or "sets", it will also return true for operator overloads such as add\_EventName or remove\_EventName. So you will need to examine other attributes of the MethodBase insta...
What's the best way to tell if a method is a property from within Policy Injection?
[ "", "c#", "enterprise-library", "policy-injection", "" ]
I'm trying to incorporate some JavaScript unit testing into my automated build process. Currently JSUnit works well with JUnit, but it seems to be abandonware and lacks good support for Ajax, debugging, and timeouts. Has anyone had any luck automating (with [Ant](https://en.wikipedia.org/wiki/Apache_Ant)) a unit testi...
There are many JavaScript unit test framework out there (JSUnit, scriptaculous, ...), but JSUnit is the only one I know that may be used with an automated build. If you are doing 'true' unit test you should not need AJAX support. For example, if you are using an [RPC](https://en.wikipedia.org/wiki/Remote_procedure_cal...
I'm just about to start doing JavaScript [TDD](https://en.wikipedia.org/wiki/Test-driven_development) on a new project I am working on. My current plan is to use [QUnit](http://docs.jquery.com/QUnit) to do the unit testing. While developing the tests can be run by simply refreshing the test page in a browser. For cont...
Automated unit testing with JavaScript
[ "", "javascript", "jquery", "unit-testing", "ant", "automation", "" ]
It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold\_on) which is normally a date, but is occasionally (10% of the time) null. Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mea...
I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help your query. 10% is too many to bother using an index for -- it'll just do a table scan. If you were talking about 2-3%, I think it would actually use your index. Think about how many records are on a page/...
From where did you get the impression that DB2 doesn't index NULLs? I can't find anything in documentation or articles supporting the claim. And I just performed a query in a large table using a IS NULL restriction involving an indexed column containing a small fraction of NULLs; in this case, DB2 certainly used the in...
Indexing nulls for fast searching on DB2
[ "", "sql", "performance", "indexing", "null", "db2", "" ]
I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript. What's the best way to go about this? Is it best to separate the visual from the functional? Do you develop the visual elements first, and then write tests and then code for functionality?
I've done some TDD with Javascript in the past, and what I had to do was make the distinction between Unit and Integration tests. Selenium will test your overall site, with the output from the server, its post backs, ajax calls, all of that. But for unit testing, none of that is important. What you want is just the UI...
I've never successfully TDDed UI code. The closest we came was indeed to separate UI code as much as possible from the application logic. This is one reason why the model-view-controller pattern is useful - the model and controller can be TDDed without much trouble and without getting too complicated. In my experience...
Developing UI in JavaScript using TDD Principles
[ "", "javascript", "user-interface", "tdd", "" ]
What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser.
The following code surely works: ``` Process.Start("http://www.yoururl.com/Blah.aspx"); ``` It opens the default browser (technically, the default program that handles HTTP URIs).
I'd use the [Process.Start method](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start#System_Diagnostics_Process_Start_System_String_).
How does one load a URL from a .NET client application
[ "", "c#", ".net", "windows", "client", "" ]
Basically I would like to find a way to ddo something like: ``` <asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label> ``` I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solut...
Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags. The general syntax is: ``` <%$ resources: ResourceKey %> ``` There is a built-in expression for appSettings: ``` <%$ appSettings: AppSettingsKey %> ``` More info on this here: <http://weblogs.asp.ne...
You can do ``` <asp:Label runat="server" Text='<%# MyProperty %>' /> ``` And then a Page.DataBind() in the codebehind.
How to 'bind' Text property of a label in markup
[ "", "c#", "asp.net", "" ]
The **C** preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a `#define`. The following macro: ``` #define SUCCEEDED(hr) ((HRESULT)(hr) >= 0) ``` is in no way superior to the type safe: ``` inline bool succeed...
As wrappers for debug functions, to automatically pass things like `__FILE__`, `__LINE__`, etc: ``` #ifdef ( DEBUG ) #define M_DebugLog( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg #else #define M_DebugLog( msg ) #endif ``` Since C++20 the magic type [`std::source_location`](https://en.cppreference...
Methods must always be complete, compilable code; macros may be code fragments. Thus you can define a foreach macro: ``` #define foreach(list, index) for(index = 0; index < list.size(); index++) ``` And use it as thus: ``` foreach(cookies, i) printf("Cookie: %s", cookies[i]); ``` Since C++11, this is superseded...
When are C++ macros beneficial?
[ "", "c++", "c-preprocessor", "" ]
The situation is this: * You have a Hibernate context with an object graph that has some lazy loading defined. * You want to use the Hibernate objects in your UI as is without having to copy the data somewhere. * There are different UI contexts that require different amounts of data. * The data is too ...
Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders. Then I would define a Repository with a fluent interface that will allow me to say something like : ``` new ClientRepo().LoadClientBy(id) .WithOrders() .WithBon...
An approach we use in our projects is to create a service for each view you have. Then the view fetches the sub-graph you need for this specific view, always trying to reduce the number of sqls send to the database. Therefore we are using a lot of joins to get the n:1 associated objects. If you are using a 2-tier desk...
What is the best way to load a Hibernate object graph before using it in a UI?
[ "", "java", "hibernate", "" ]
From [PyPubSub](http://pypi.python.org/pypi/PyPubSub/): > Pypubsub provides a simple way for > your Python application to decouple > its components: parts of your > application can publish messages (with > or without data) and other parts can > subscribe/receive them. This allows > message "senders" and message > "lis...
[PyDispatcher](http://pydispatcher.sourceforge.net/) is used heavily in [Django](http://pydispatcher.sourceforge.net/) and it's working perfectly for me (and for whole Django community, I guess). As I remember, there are some performance issues: * Arguments checking made by PyDispatcher is slow. * Unused connections ...
The best dispatch package for python seems to be the [dispatch module](http://github.com/django/django/tree/master/django/dispatch/) inside django (called [signals](http://docs.djangoproject.com/en/dev/topics/signals/) in the documentation). It is independent of the rest of django, and is short, documented, tested and ...
Recommended Python publish/subscribe/dispatch module?
[ "", "python", "publish-subscribe", "pypubsub", "" ]
Referenced [here](https://stackoverflow.com/questions/21265/comparing-ieee-floats-and-doubles-for-equality) and [here](https://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison)...Why would I use two's complement over an epsilon method? It seems like the epsilon method would be good e...
the second link you reference mentions an article that has quite a long description of the issue: <http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm> but unless you are tweaking performance I would stick with epsilon so people can debug your code
In short, when comparing two floats with unknown origins, picking an epsilon that is valid is almost impossible. For example: What is a good epsilon when comparing distance in miles between Atlanta GA, Dallas TX and some place in Ohio? What is a good epsilon when comparing distance in miles between my left foot, my ...
Why would I use 2's complement to compare two doubles instead of comparing their differences against an epsilon value?
[ "", "c++", "floating-point", "double", "" ]
I create a web application (WAR) and deploy it on Tomcat. In the *webapp* there is a page with a form where an administrator can enter some configuration data. I don't want to store this data in an DBMS, but just in an XML file on the file system. Where to put it? I would like to put the file somewhere in the director...
What we do is to put it in a separate directory on the server (you could use something like /config, /opt/config, /root/config, /home/username/config, or anything you want). When our servlets start up, they read the XML file, get a few things out of it (most importantly DB connection information), and that's it. I ask...
WEB-INF is a good place to put your config file. Here's some code to get the absolute path of the directory from a servlet. ``` public void init(ServletConfig servletConfig) throws ServletException{ super.init(servletConfig); String path = servletConfig.getServletContext().getRealPath("/WEB-INF") ```
What is the best place to store a configuration file in a Java web application (WAR)?
[ "", "java", "web-applications", "tomcat", "jakarta-ee", "" ]
Since the Google App Engine Datastore is based on [Bigtable](http://research.google.com/archive/bigtable.html) and we know that's not a relational database, how do you design a ***database schema*/*data model*** for applications that use this type of database system?
Designing a bigtable schema is an open process, and basically requires you to think about: * The access patterns you will be using and how often each will be used * The relationships between your types * What indices you are going to need * The write patterns you will be using (in order to effectively spread load) GA...
You can use www.web2py.com. You build the model and the application once and it works on GAE but also witl SQLite, MySQL, Posgres, Oracle, MSSQL, FireBird
How do you design data models for Bigtable/Datastore (GAE)?
[ "", "python", "database", "google-app-engine", "bigtable", "" ]
A `.container` can contain many `.components`, and `.components` themselves can contain `.containers` (which in turn can contain .components etc. etc.) Given code like this: ``` $(".container .component").each(function(){ $(".container", this).css('border', '1px solid #f00'); }); ``` What do I need to add to the l...
``` $(".container .component").each(function() { $(".container", this).each(function() { if($(this).css('width') == 'auto') { $(this).css('border', '1px solid #f00'); } }); }); ``` Similar to the other answer but since components can also have multiple containers, also needs...
You may want to look into `.filter()`. Something like: ``` $('.container .component .container') .filter(function() {return $(this).css('width') == 'auto';}) .css({border: '1px solid #f00'}); ```
Can jQuery select by CSS rule, not class?
[ "", "javascript", "jquery", "css-selectors", "" ]
I am having a bit of a problem. I get a RAW char\* buffer from a camera and I need to add this tags before I can save it to disk. Writing the file to disk and reading it back again is not an option, as this will happen thousands of times. The buffer data I receive from the camera does not contain any EXIF information...
Look at this [PDF](http://www.exif.org/Exif2-1.PDF), on page 20 you have a diagram showing you were to place or modify your exif information. What is the difference with a file on disk ? Does the JPEG buffer of your camera contain an EXIF section already ?
What's the difference? Why would doing it to a file on the disk be any different from doing it in memory? Just do whatever it is you do after you read the file from the disk..
How do you place EXIF tags into a JPG, having the raw jpeg buffer in C++?
[ "", "c++", "jpeg", "exif", "" ]
I am looking for a PHP blog engine which needs to be easy to redesign (CSS, HTML). It also needs to be free and have simple user interface so that the client doesn't struggle to add posts. Any suggestions?
[Wordpress](http://www.wordpress.org) - I keep trying other blogs and I keep going back to wordpress. It's definitely the easiest I've used for customizing templates, and the admin UI is very nice.
I kinda like [b2evo](http://b2evolution.net/) we used it on [our site](http://blogs.lessthandot.com/) and modded it to great effect.
Simple, free PHP blog engine easy to redesign?
[ "", "php", "blog-engine", "" ]
I want to grab the value of a hidden input field in HTML. ``` <input type="hidden" name="fooId" value="12-3456789-1111111111" /> ``` I want to write a regular expression in Python that will return the value of `fooId`, given that I know the line in the HTML follows the format ``` <input type="hidden" name="fooId" va...
For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-) ``` from BeautifulSoup import BeautifulSoup #Or retrieve it from the web, etc. html_data = open('/yourwebsit...
I agree with Vinko [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is the way to go. However I suggest using `fooId['value']` to [get the attribute](http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags) rather than relying on value being the third attribute. ``` f...
Python regular expression for HTML parsing
[ "", "python", "regex", "web-scraping", "beautifulsoup", "" ]
If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file? This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!
Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file. The inner loop would look something like: ``` byte[] buffer = new byte[ ( string.length ...
If you're lucky, java.math.BigInteger may do everything for you. ``` String s = "11001010001010101110101001001110"; byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray(); ``` This does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want b...
Bit manipulation and output in Java
[ "", "java", "bit-manipulation", "" ]
What would be better practice when giving a function the original variable to work with: ``` unsigned long x = 4; void func1(unsigned long& val) { val = 5; } func1(x); ``` or: ``` void func2(unsigned long* val) { *val = 5; } func2(&x); ``` IOW: Is there any reason to pick one over another?
My rule of thumb is: Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer. Use references otherwise.
I really think you will benefit from establishing the following function calling coding guidelines: 1. As in all other places, always be `const`-correct. * Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the `const` specifier. 2. Only pass a ...
Should I use a pointer or a reference to remotely assign a variable?
[ "", "c++", "variables", "pointers", "reference", "" ]
I'm looking to have text display vertically, first letter at the bottom, last letter at the top, within a JLabel. Is this possible?
I found this page: <http://www.java2s.com/Tutorial/Java/0240__Swing/VerticalLabelUI.htm> when I needed to do that. I don't know if you want the letters 'standing' on each other or all rotated on their side. ``` /* * The contents of this file are subject to the Sapient Public License * Version 1.0 (the "License"); y...
You can do it by messing with the paint command, sort of like this: ``` public class JVertLabel extends JComponent{ private String text; public JVertLabel(String s){ text = s; } public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.rotate(Math.t...
How do I present text vertically in a JLabel ? (Java 1.6)
[ "", "java", "jlabel", "" ]
I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.
See example on how you can do this with full source code here: <http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/> ``` [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(IntPtr hWnd, StringBuilde...
If you were talking about WPF then use: ``` Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive); ```
How do I get the title of the current active window using c#?
[ "", "c#", ".net", "windows", "winforms", "" ]
Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I...
This is probably a combination of impersonation and a mismatch of different authentication methods occurring. There are many pieces; I'll try to go over them one by one. **Impersonation** is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the...
I encountered this error while diagnosing a console app that was writing in temp files. In one of my test iterations I purged all the files/directories in temp for a 'clean-slate' run. I resolved this self inflicted issue by logging out and back in again.
Path.GetTempFileName -- Directory name is invalid
[ "", "c#", "asp.net", "iis", "" ]
If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all? If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect? sorry if this is a dumb questi...
You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code. For example: ``` #!/usr/bin/env python import threading shared_balance = 0 class Deposit(threading.Thread): def run(self): for _ in xr...
No - the GIL just protects python internals from multiple threads altering their state. This is a very low-level of locking, sufficient only to keep python's own structures in a consistent state. It doesn't cover the *application* level locking you'll need to do to cover thread safety in your own code. The essence of ...
Are locks unnecessary in multi-threaded Python code because of the GIL?
[ "", "python", "multithreading", "locking", "" ]
This question is the other side of the question asking, "[How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time)". Given some human input for a relative time, how can you parse it? By default you would offset from `DateTime.Now()`, but could optionally offset from a...
That's building a DSL (Domain specific language) for date handling. I don't know if somebody has done one for .NET but the construction of a DSL is fairly straightforward: 1. Define the language precisely, which input forms you will accept and what will you do with ambiguities 2. Construct the grammar for the language...
A Google search turns up the [parsedatetime](http://code.google.com/p/parsedatetime/) library (associated with the [Chandler project](http://chandlerproject.org/)), which is designed to do exactly this. It's open source (Apache License) and written in Python. It seems to be quite sophisticated -- from the homepage: > ...
How to parse relative time?
[ "", "c#", "parsing", "time", "language-agnostic", "" ]
I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the fram...
An easy way to determine if a string is a valid identifier for a class or variable is to call the static method ``` System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value) ```
Use the `CreateValidIdentifier` method on the `CSharpCodeProvider` class. ``` CSharpCodeProvider codeProvider = new CSharpCodeProvider(); string sFixedName = codeProvider.CreateValidIdentifier("somePossiblyInvalidName"); CodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); ``` It returns a valid name...
Is there a .NET function to validate a class name?
[ "", "c#", ".net", "validation", "class", "naming", "" ]
I am developing a Win32 application and I would like to use an RSA encryption library. **Which library would you recommend?**
I use the following library: <http://www.efgh.com/software/rsa.htm> It's public domain, compact, self contained, and does the work well.
If you're using Win32, why don't you simply use the built-in win32 crypto-API? Here's a little example how it works in practice: <http://www.codeproject.com/KB/security/EncryptionCryptoAPI.aspx>
RSA encryption library for C++
[ "", "c++", "winapi", "encryption", "rsa", "" ]
I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations? Class code here: ``` class Enum(object): '''Simple Enum Class Example Usage: >>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, nam...
There's a lot of good discussion [here](https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python).
Enums have been proposed for inclusion into the language before, but were rejected (see [http://www.python.org/dev/peps/pep-0354/](http://www.python.org/dev/peps/pep-0354/ "PEP 354")), though there are existing packages you could use instead of writing your own implementation: * enum: [http://pypi.python.org/pypi/enum...
How should I best emulate and/or avoid enum's in Python?
[ "", "python", "enums", "" ]
How do I generate all the permutations of a list? For example: ``` permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] ```
Use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) from the **standard library**: ``` import itertools list(itertools.permutations([1, 2, 3])) ``` --- Adapted from [here](http://code.activestate.com/recipes/252178/) is a demonstration of how `itertools.permutation...
For [Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html) onwards: ``` import itertools itertools.permutations([1, 2, 3]) ``` This returns as a generator. Use `list(permutations(xs))` to return as a list.
How do I generate all permutations of a list?
[ "", "python", "algorithm", "permutation", "combinatorics", "" ]
I'm building a PHP page with data sent from MySQL. Is it better to have * 1 `SELECT` query with 4 table joins, or * 4 small `SELECT` queries with no table join; I do select from an ID Which is faster and what is the pro/con of each method? I only need one row from each tables.
You should run a profiling tool if you're truly worried cause it depends on many things and it can vary but as a rule its better to have fewer queries being compiled and fewer round trips to the database. Make sure you filter things as well as you can using your where and join on clauses. But honestly, it usually doe...
Generally, it's better to have one SELECT statement. One of the main reasons to have databases is that they are fast at processing information, particularly if it is in the format of query. If there is any drawback to this approach, it's that there are some kinds of analysis that you can't do with one big SELECT state...
Should I use one big SQL Select statement or several small ones?
[ "", "php", "mysql", "performance", "optimization", "" ]
1. You have multiple network adapters. 2. Bind a UDP socket to an local port, without specifying an address. 3. Receive packets on one of the adapters. How do you get the local ip address of the adapter which received the packet? The question is, "What is the ip address from the receiver adapter?" not the address fro...
You could enumerate all the network adapters, get their IP addresses and compare the part covered by the subnet mask with the sender's address. Like: ``` IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr ) { foreach( adapter in EnumAllNetworkAdapters() ) { adapterSubnet = adapter.subnetmask & a...
The solution provided by [timbo](https://stackoverflow.com/users/1810/timbo) assumes that the address ranges are unique and not overlapping. While this is usually the case, it isn't a generic solution. There is an excellent implementation of a function that does exactly what you're after provided in the Steven's book ...
How to get your own (local) IP-Address from an udp-socket (C/C++)
[ "", "c++", "sockets", "udp", "" ]
Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?
The [PyXPCOM extension](https://developer.mozilla.org/en/PyXPCOM) is one possibility. But looking at what firewatir provides, I have to 2nd the suggestion for twill. It's based on [mechanize](http://wwwsearch.sourceforge.net/mechanize/), which might also be useful in this context.
You could try [selenium](http://selenium.openqa.org/).
Automate firefox with python?
[ "", "python", "linux", "firefox", "ubuntu", "automation", "" ]
An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e. ``` int[] vs. Integer[] ``` I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other ob...
No VM I know of will store an Integer[] array like an int[] array for the following reasons: 1. There can be **null** Integer objects in the array and you have no bits left for indicating this in an int array. The VM could store this 1-bit information per array slot in a hiden bit-array though. 2. You can synchronize ...
John Rose working on [fixnums](http://blogs.oracle.com/jrose/entry/fixnums_in_the_vm) in the JVM to fix this problem.
How are Integer arrays stored internally, in the JVM?
[ "", "java", "jvm", "" ]
In our application, we receive text files (`.txt`, `.csv`, etc.) from diverse sources. When reading, these files sometimes contain garbage, because the files where created in a different/unknown codepage. Is there a way to (automatically) detect the codepage of a text file? The `detectEncodingFromByteOrderMarks`, on ...
You can't detect the codepage, you need to be told it. You can analyse the bytes and guess it, but that can give some bizarre (sometimes amusing) results. I can't find it now, but I'm sure Notepad can be tricked into displaying English text in Chinese. Anyway, this is what you need to read: [The Absolute Minimum Every...
If you're looking to detect non-UTF encodings (i.e. no BOM), you're basically down to heuristics and statistical analysis of the text. You might want to take a look at the [Mozilla paper on universal charset detection](http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html) ([same link, with better...
How can I detect the encoding/codepage of a text file?
[ "", "c#", ".net", "text", "encoding", "globalization", "" ]
While we try to set up as many unit tests as time allows for our applications, I always find the amount of UI-level tests lacking. There are many options out there, but I'm not sure what would be a good place to start. What is your preferred unit testing tool for testing Swing applications? Why do you like it?
On our side, we use to test SWING GUI with [FEST](http://code.google.com/p/fest/). This is an adapter on the classical swing robot, but it ease dramatically its use. Combined with TestNG, We found it an easy way to simulate "human" actions trough the GUI.
If your target application has **custom components**, I would definitely recommend [Marathon](http://www.marathontesting.com/) to automate your tests. I was given the task of automating an application with several *extremely* complicated custom components, written in-house from the ground up. I went through a review p...
What is the best testing tool for Swing-based applications?
[ "", "java", "swing", "testing", "" ]
In C# there are `String` objects and `string` objects. What is the difference between the two? What are the best practices regarding which to use?
There is no difference. string (lower case) is just an alias for System.String.
No difference. `System.String` is strictly identical to `string`. Common C# coding guidelines indicates that you should use the keyword `string`.
String vs string
[ "", "c#", ".net", "string", "declaration", "" ]
My team is developing a new service oriented product with a web front-end. In discussions about what technologies we will use we have settled on running a JBoss application server, and Flex frontend (with possible desktop deployment using Adobe AIR), and web services to interface the client and server. We've reached a...
There won't be much difference between EJB3 and Spring based on Performance. We chose Spring for the following reasons (not mentioned in the question): * Spring drives the architecture in a direction that more readily supports unit testing. For example, inject a mock DAO object to unit test your business layer, or uti...
The gap between EJB3 and Spring is much smaller than it was, clearly. That said, one of the downsides to EJB3 now is that you can only inject into a bean, so you can end up turning components into beans that don't need to be. The argument about unit testing is fairly irrelevant now - EJB3 is clearly designed to be mor...
Should I use EJB3 or Spring for my business layer?
[ "", "java", "performance", "spring", "ejb-3.0", "scalability", "" ]
A rather comprehensive site explaining the difficulties and solutions involved in using a dll written in c/c++ and the conversion of the .h header file to delphi/pascal was posted to a mailing list I was on recently, so I thought I'd share it, and invite others to post other useful resources for this, whether they be l...
Over at [Rudy's Delphi Corner](http://rvelthuis.de/index.html), he has an [excellent article about the pitfalls of converting C/C++ to Delphi](http://rvelthuis.de/articles/articles-convert.html). In my opinion, this is essential information when attempting this task. Here is the description: > This article is meant fo...
[Article](http://rvelthuis.de/articles/articles-convert.html#main) at Rudy's Delphi Corner
Best resources for converting C/C++ dll headers to Delphi?
[ "", "c++", "c", "delphi", "dll", "header", "" ]
I'm able to successfully uninstall a third-party application via the command line and via a custom Inno Setup installer. Command line Execution: ``` MSIEXEC.exe /x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn ``` Inno Setup Command: ``` [Run] Filename: msiexec.exe; Flags: runhidden waituntilterminated; Parameters: "...
Thanks to those offering help. This appears to be a permissions issue. I have updated my service to run under an Administrator account and it was able to successfully uninstall the third-party application. To Orion's point, though the Local System account is a powerful account that has full access to the system -- <htt...
I've come across similar problems in the past with installation, a customer was using the SYSTEM account to install and this was causing all sorts of permission problems for non-administrative users. MSI log files aren't really going to help if the application doesn't appear "installed", I'd suggest starting with capt...
Uninstall Command Fails Only in Release Mode
[ "", "c#", "installation", "service", "" ]
I just want my apache to register some of my predefined environment so that i can retrieve it using getenv function in php. How can i do this? I tried adding /etc/profile.d/foo.sh with export FOO=/bar/baz using root and restarted apache.
Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment. Possible Fixes: * log out/log in, then start apache * source t...
You can use [SetEnv](http://httpd.apache.org/docs/2.2/mod/mod_env.html#setenv) in your config files (/etc/httpd/conf.d/\*.conf, .htaccess ...). Additionally you should be able to define them in /etc/sysconfig/httpd (on RPM-based distribs) and *export* them (note: not tested). Note: it wouldn't surprise me if some dist...
reinitialize system wide environment variable in linux
[ "", "php", "linux", "variables", "environment", "" ]
I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order? ``` String propFile = "/path/to/file"; Properties props = new Properties(); /*set some properties here*/ try { FileOutputStream xmlStream = new FileOutputStream(...
Here's a quick and dirty way to do it: ``` String propFile = "/path/to/file"; Properties props = new Properties(); /* Set some properties here */ Properties tmp = new Properties() { @Override public Set<Object> keySet() { return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet())); } }; tmp.pu...
Here's a way to produce sorted output for both store `Properties.store(OutputStream out, String comments)` and `Properties.storeToXML(OutputStream os, String comment)`: ``` Properties props = new Properties() { @Override public Set<Object> keySet(){ return Collections.unmodifiableSet(new TreeSet<Object...
How to write java.util.Properties to XML with sorted keys?
[ "", "java", "xml", "" ]
I have an object in a multi-threaded environment that maintains a collection of information, e.g.: ``` public IList<string> Data { get { return data; } } ``` I currently have `return data;` wrapped by a `ReaderWriterLockSlim` to protect the collection from sharing violations. However, to be doub...
If your underlying data is stored as list you can use [List(T).AsReadOnly](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) method. If your data can be enumerated, you can use [Enumerable.ToList](http://msdn.microsoft.com/en-us/library/bb342261.aspx) method to cast your collection to List and call AsReadOnly on...
I voted for your accepted answer and agree with it--however might I give you something to consider? Don't return a collection directly. Make an accurately named business logic class that reflects the purpose of the collection. The main advantage of this comes in the fact that you can't add code to collections so when...
Return collection as read-only
[ "", "c#", ".net", "multithreading", "collections", "concurrency", "" ]
I wrote a small `PHP` application several months ago that uses the `WordPress XMLRPC library` to synchronize two separate WordPress blogs. I have a general "RPCRequest" function that packages the request, sends it, and returns the server response, and I have several more specific functions that customize the type of re...
@Novak: Thanks for your suggestion. The problem turned out to be a memory issue; by retrieving all the posts from the remote location, the response exceeded the amount of memory PHP was allowed to utilize, hence the unclosed token error. The problem with the cryptic and incomplete error message was due to an outdated ...
Expat is the XML parser in PHP. Error code 5 is one of many expat error constants, in this case: `XML_ERROR_UNCLOSED_TOKEN`. Sounds to me like there's an error in the result returned from the RPC call. You might want to do some error checking in RPCRequest after `file_get_contents` and before `xmlrpc_decode`.
WordPress XMLRPC: Expat reports error code 5
[ "", "php", "blogs", "xml-rpc", "" ]
I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST. (Non essential xml generating code replaced with "Hello there") ``` StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection c...
This kind of thing is much easier using a library like [HttpClient](http://hc.apache.org/httpclient-3.x/). There's even a [post XML code example](http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup): ``` PostMethod post = new PostMethod(url); RequestEntity entity = new File...
I recommend using Apache [HTTPClient](http://hc.apache.org/) instead, because it's a nicer API. But to solve this current problem: try calling `connection.setDoOutput(true);` after you open the connection. ``` StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); Ht...
Writing post data from one java servlet to another
[ "", "java", "servlets", "" ]
I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time. ``` int globalgarbage; unsigned int anumber = 42; ``` But what about static ones defined within a function? ``` void doSomething() { static bool globalish = true; // ... } ``` When is the s...
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2. ``` include <iostream> #include <string> using namespace std; class test { public: test(const char *name) : _name(name) { cout << _name << " created" << endl; ...
Some relevant verbiage from C++ Standard: > ## 3.6.2 Initialization of non-local objects [basic.start.init] > > ### 1 > > The storage for objects with static storage > duration (*basic.stc.static*) shall be zero-initialized (*dcl.init*) > before any other initialization takes place. Objects of > POD types (*basic.type...
When do function-level static variables get allocated/initialized?
[ "", "c++", "variables", "" ]
Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separa...
For the threading safety of boost::shared\_ptr you should check [this link](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety). It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.
> In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? In your example, if thread1 gets the pointer before thread2, then thread2 will have to wait at the beginning of the function (because of the lo...
Boost shared_ptr container question
[ "", "c++", "boost", "smart-pointers", "" ]
We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: ``` SELECT * FROM customer WHERE fname LIKE '%someName%' ``` Does full-text indexing help in the scenario? We're using SQL Server 2005.
It will depend upon your DBMS. I believe that most systems will not take advantage of the full-text index unless you use the full-text functions. (e.g. [MATCH/AGAINST](http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html) in mySQL or FREETEXT/CONTAINS in MS SQL) Here is two good articles on when, why,...
FTS *can* help in this scenario, the question is whether it is worth it or not. To begin with, let's look at why `LIKE` may not be the most effective search. When you use `LIKE`, especially when you are searching with a `%` at the beginning of your comparison, SQL Server needs to perform both a table scan of every sin...
When should you use full-text indexing?
[ "", "sql", "sql-server", "t-sql", "indexing", "full-text-search", "" ]
I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does **managed** code mean? Wikipedia [describes it](http://en.wikipedia.org/wiki/Managed_code) simply as > Code ...
When you compile C# code to a .exe, it is compiled to Common Intermediate Language(CIL) bytecode. Whenever you run a CIL executable it is executed on Microsofts Common Language Runtime(CLR) virtual machine. So no, it is not possible to include the VM withing your .NET executable file. You must have the .NET runtime ins...
I don't think you are alone in being confused about what .Net is. There are already other answers that should have you covered but I'll throw out this tidbit of info for others. To see what .Net "really" is simply go to c:\Windows\Microsoft.Net\Framework In there you'll see folders that are specfic to the version(s) ...
What exactly is "managed" code?
[ "", "c#", ".net", "vb.net", "managed-code", "" ]
This question was [already asked in the context of C#/.Net](https://stackoverflow.com/questions/13049). Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design. I'll start with an obvious differen...
You forget the tricky 2nd difference between classes and structs. Quoth the standard (§11.2.2 in C++98 through C++11): > In absence of an *access-specifier* > for a base class, public is assumed > when the derived class is declared > *struct* and private is assumed when the class is declared *class*. And just for co...
Quoting [The C++ FAQ](https://isocpp.org/wiki/faq/classes-and-objects#struct-vs-class), > [7.8] What's the difference between > the keywords struct and class? > > The members and base classes of a > struct are public by default, while in > class, they default to private. Note: > you should make your base classes > exp...
What are the differences between struct and class in C++?
[ "", "c++", "oop", "class", "struct", "c++-faq", "" ]
What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this: ``` MyPage.aspx: <asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceholder" runat="server"> <uc1:MyUserControl ID="MyUserControl1" runat="server" OnSomeEvent="MyUserCo...
You would want to create an event on the control that is subscribed to in the parent. See [OdeToCode](http://www.odetocode.com/code/94.aspx) for an example. Here is the article for longevity sake: Some user controls are entirely self contained, for example, a user control displaying current stock quotes does not need...
1) Declare a Public event in the user control 2) Issue a RaiseEvent where appropriate inside the user control 3) In the Init event of the parent page, use AddHandler to assign the control.event to the the handling procedure you want to use Simple as that!
Eventhandling in ascx usercontrols
[ "", "c#", "asp.net", "" ]
What is the difference between the following class methods? Is it that one is static and the other is not? ``` class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two() ```
In Python, there is a distinction between *bound* and *unbound* methods. Basically, a call to a member function (like `method_one`), a bound function ``` a_test.method_one() ``` is translated to ``` Test.method_one(a_test) ``` i.e. a call to an unbound method. Because of that, a call to your version of `method_two...
Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class: ``` class C(object): def foo(self): pass ``` Now let's have a look at that class in the shell: ``` >>> C.foo <unbound method C.foo> >>> C.__dict__['foo'] <function foo at ...
Class method differences in Python: bound, unbound and static
[ "", "python", "static-methods", "" ]
We are getting very slow compile times, which can take upwards of 20+ minutes on dual core 2GHz, 2G Ram machines. A lot of this is due to the size of our solution which has grown to 70+ projects, as well as VSS which is a bottle neck in itself when you have a lot of files. (swapping out VSS is not an option unfortunat...
The Chromium.org team listed several options for [accelerating the build](http://dev.chromium.org/developers/how-tos/build-instructions-windows) (at this point about half-way down the page): > In decreasing order of speedup: > > * Install Microsoft hotfix [935225](http://support.microsoft.com/kb/935225). > * Install M...
# We have nearly 100 projects in one solution and a dev build time of only seconds :) For local development builds we created a Visual Studio Addin that changes `Project references` to `DLL references` and unloads the unwanted projects (and an option to switch them back of course). * Build our entire solution *once* ...
Very slow compile times on Visual Studio 2005
[ "", "c#", "visual-studio", "compilation", "" ]
I like the XMLReader class for it's simplicity and speed. But I like the xml\_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning.
I'd avoid SimpleXML if you can. Though it looks very tempting by getting to avoid a lot of "ugly" code, it's just what the name suggests: simple. For example, it can't handle this: ``` <p> Here is <strong>a very simple</strong> XML document. </p> ``` Bite the bullet and go to the DOM Functions. The power of it fa...
[SimpleXML](https://www.php.net/simplexml) seems to do a good job for me.
What XML parser do you use for PHP?
[ "", "php", "xml", "" ]
How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this *almost* works for me: ``` proc1 = subprocess.Popen(['python','mytest.py']) proc2 = subprocess.Popen(['python','mytest.py']) proc1.wait() print "1 finished" proc2.wait() print "2 finished" ``` The pro...
It might seem overkill, but, here it goes: ``` import Queue, thread, subprocess results= Queue.Queue() def process_waiter(popen, description, que): try: popen.wait() finally: que.put( (description, popen.returncode) ) process_count= 0 proc1= subprocess.Popen( ['python', 'mytest.py'] ) thread.start_new_thread...
Building on zseil's answer, you can do this with a mix of subprocess and win32 API calls. I used straight ctypes, because my Python doesn't happen to have win32api installed. I'm just spawning sleep.exe from MSYS here as an example, but clearly you could spawn any process you like. I use OpenProcess() to get a HANDLE f...
Python on Windows - how to wait for multiple child processes?
[ "", "python", "windows", "asynchronous", "" ]
> **Possible Duplicate:** > [How do you send email from a Java app using Gmail?](https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail) How do I send an SMTP Message from Java?
Here's an example for Gmail smtp: ``` import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.smtp.*; public class Distribution { public static void main(String args[]) throws Exception { ...
Another way is to use aspirin (<https://github.com/masukomi/aspirin>) like this: ``` MailQue.queMail(MimeMessage message) ``` ..after having constructed your mimemessage as above. Aspirin **is** an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simpl...
How do I send an SMTP Message from Java?
[ "", "java", "smtp", "" ]
I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain. So, for example, some of the applications I work with use settings which we access with: ``` string...
Nij, our difference in thinking comes from our different perspectives. I'm thinking about developing enterprise apps that predominantly use WinForms clients. In this instance the business logic is contained on an application server. Each client would need to know the phone number to dial, but placing it in the App.conf...
If you use the settings tab in VS 2005+, you can add strongly typed settings and get intellisense, such as in your first example. ``` string phoneNum = Properties.Settings.Default.EmergencyPhoneNumber; ``` This is physically stored in App.Config. You could still use the config file's appSettings element, or even rol...
Understanding .Net Configuration Options
[ "", "c#", ".net", "configuration", "" ]
How do I find out what directory my console app is running in with C#?
To get the directory where the .exe file is: ``` AppDomain.CurrentDomain.BaseDirectory ``` To get the current directory: ``` Environment.CurrentDirectory ```
Depending on the rights granted to your application, whether [shadow copying](http://msdn.microsoft.com/en-us/library/ms404279.aspx) is in effect or not and other invocation and deployment options, different methods may work or yield different results so you will have to choose your weapon wisely. Having said that, all...
How do I find out what directory my console app is running in?
[ "", "c#", ".net", "console-application", "" ]
I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: ``` List<int> iList = new List<int>(); for (int i = 1; i <= x; i++) { iList.Add(i); } ``` This seems dumb, surely there's a more elegant way to do this, something like the...
If you're using .Net 3.5, [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx) is what you need. > Generates a sequence of integral > numbers within a specified range.
LINQ to the rescue: ``` // Adding value to existing list var list = new List<int>(); list.AddRange(Enumerable.Range(1, x)); // Creating new list var list = Enumerable.Range(1, x).ToList(); ``` See [Generation Operators](http://msdn.microsoft.com/en-us/vcsharp/aa336752.aspx#range) on [LINQ 101](http://msdn.microsoft....
Populating a list of integers in .NET
[ "", "c#", ".net", "list", "integer", "" ]
I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, ...
If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException) But you may not want to rely on t...
Throwing an exception is not useful from a WCF service Why not? Because it comes back as a bare fault and you need to a) Set the fault to include exceptions b) Parse the fault to get the text of the exception and see what happened. So yes you need a fault rather than an exception. I would, in your case, create a cus...
WCF faults and exceptions
[ "", "c#", "wcf", "validation", "exception", "" ]
You might have a set of properties that is used on the developer machine, which varies from developer to developer, another set for a staging environment, and yet another for the production environment. In a Spring application you may also have beans that you want to load in a local environment but not in a production...
I just put the various properties in JNDI. This way each of the servers can be configured and I can have ONE war file. If the list of properties is large, then I'll host the properties (or XML) files on another server. I'll use JNDI to specify the URL of the file to use. If you are creating different app files (war/ea...
I just use different Spring XML configuration files for each machine, and make sure that all the bits of configuration data that vary between machines is referenced by beans that load from those Spring configuration files. For example, I have a webapp that connects to a Java RMI interface of another app. My app gets t...
How do you maintain java webapps in different staging environments?
[ "", "java", "spring", "configuration", "web-applications", "" ]
I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes. How can I achieve something similar to `array_map` or `array_walk` with objects?
use [get\_object\_vars()](https://www.php.net/manual/en/function.get-object-vars.php) to get an associative array of the members, and use the functions you mentioned. btw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well.
You can use `get_object_vars()`, but if you need more control, try using [reflection](http://web.archive.org/web/20090228224836/http://www.php.net:80/manual/en/language.oop5.reflection.php). It's slower than `get_object_vars()` (or `get_class_methods()` for that matter), but it's much more powerful.
PHP: array_map on object?
[ "", "php", "oop", "" ]
I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query? ``` var family = from p in db.Par...
Your joins are going to screw up your cardinality! You don't have a list of Parents! Here's some untested free-hand code. Adding the relationships in the Linq designer gives you relationship properties. String.Join will put the list together. I've added two optional method calls. *Where ... Any* will filter the pare...
you could try as follow: ``` var family = from p in db.Parents where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"]) join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId select new { Family = "Name: " ...
Linq to SQL Grouping Child Relationships
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter `"$5"`, I'd like to match that exactly rather than a `"5"` after the end of input.
Since [Java 1.5, yes](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)): ``` Pattern.quote("$5"); ```
Difference between [`Pattern.quote`](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#quote-java.lang.String-) and [`Matcher.quoteReplacement`](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#quoteReplacement-java.lang.String-) was not clear to me before I saw following exampl...
How to escape text for regular expression in Java?
[ "", "java", "regex", "escaping", "" ]
I am writing a little application to download files over http (as, for example, described [here](https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776)). I also want to include a little download progress indicator showing the percentage of the download progress. Here is what ...
There's a text progress bar library for python at <http://pypi.python.org/pypi/progressbar/2.2> that you might find useful: > This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. > > The ProgressB...
You might also try: ``` sys.stdout.write("\r%2d%%" % percent) sys.stdout.flush() ``` Using a single carriage return at the beginning of your string rather than several backspaces. Your cursor will still blink, but it'll blink after the percent sign rather than under the first digit, and with one control character ins...
How to write a download progress indicator in Python?
[ "", "python", "http", "" ]
Suppose I have a collection (be it an array, generic List, or whatever is the **fastest** solution to this problem) of a certain class, let's call it `ClassFoo`: ``` class ClassFoo { public string word; public float score; //... etc ... } ``` Assume there's going to be like 50.000 items in the collection,...
With the constraint that the condition clause can be "anything", then you're limited to scanning the entire list and applying the condition. If there are limitations on the condition clause, then you can look at organizing the data to more efficiently handle the queries. For example, the code sample with the "byFirst...
var Answers = myList.Where(item => item.bar.StartsWith(query) || item.bar.EndsWith(query)); that's the easiest in my opinion, should execute rather quickly.
Fastest way to find objects from a collection matched by condition on string member
[ "", "c#", "arrays", "string", "collections", "performance", "" ]
I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me? ``` gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP) ```
The answer is in the [GCC manual](http://gcc.gnu.org/onlinedocs/gcc-4.3.2/cpp/Invocation.html): use the `-MT` flag. > `-MT target` > > Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as `.c`,...
I'm assuming you're using GNU Make and GCC. First add a variable to hold your list of dependency files. Assuming you already have one that lists all our sources: ``` SRCS = \ main.c \ foo.c \ stuff/bar.c DEPS = $(SRCS:.c=.d) ``` Then include the generated dependencies in the makefile: ``` in...
GCC dependency generation for a different output directory
[ "", "c++", "gcc", "makefile", "dependencies", "" ]
What does the `explicit` keyword mean in C++?
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. This means that the compiler can use constructors callable with a **single parameter** to convert from one type to another in order to get the right type for a parameter. Here's an example with *converting constructors* th...
Suppose, you have a class `String`: ``` class String { public: String(int n); // allocate n bytes to the String object String(const char *p); // initializes object with char *p }; ``` Now, if you try: ``` String mystring = 'x'; ``` The character `'x'` will be implicitly converted to `int` and then the `Stri...
What does the explicit keyword mean?
[ "", "c++", "constructor", "explicit", "c++-faq", "explicit-constructor", "" ]
I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file. Since then, I've become fairly proficient at 'coding' my hbm.xml file. But all the cool kids are using annotations these days. So, the question is: **Is it worth the effort** to refactor my code to use hibernate annota...
"If it ain't broke - don't fix it!" I'm an old fashioned POJO/POCO kind of guy anyway, but why change to annotations just to be cool? To the best of my knowledge you can do most of the stuff as annotations, but the more complex mappings are sometimes expressed more clearly as XML.
One thing you'll gain from using annotations instead of an external mapping file is that your mapping information will be on classes and fields which improves maintainability. You add a field, you immediately add the annotation. You remove one, you also remove the annotation. you rename a class or a field, the annotati...
Is it worth the effort to move from a hand crafted hibernate mapping file to annotaions?
[ "", "java", "hibernate", "annotations", "" ]
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves? I have seen [the Scheme example](http://en.wikipedia.org/wiki/Scheme_%28programming_language%29) given on Wikipedia, but un...
A closure is a pairing of: 1. A function and 2. A reference to that function's outer scope (lexical environment) A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values. Every function in JavaScript maintains a reference to its ou...
Every function in JavaScript maintains a link to its outer lexical environment. A lexical environment is a map of all the names (eg. variables, parameters) within a scope, with their values. So, whenever you see the `function` keyword, code inside that function has access to variables declared outside the function. `...
How do JavaScript closures work?
[ "", "javascript", "function", "variables", "scope", "closures", "" ]
I have to deploy my php/html/css/etc code to multiple servers and i am looking at my options for software that allows easy and secure deployment to multiple servers. Also helps if it could be tied into my SVN. Any suggestions?
[Capistrano](http://capify.org/) is pretty handy for that. There's a few people using it ([1](http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/), [2](http://www.contentwithstyle.co.uk/Blog/178), [3](http://laurentbois.com/2008/08/05/use-capistrano-in-enterprise-for-php-and-ruby-on-...
Setting up password-less publickey authentication with ssh would allow you to scp your files to any of your servers very quickly (or be automated by a shell script). Here's a simple tutorial: <http://rcsg-gsir.imsb-dsgi.nrc-cnrc.gc.ca/documents/internet/node31.html>
Deploying to multiple servers
[ "", "php", "deployment", "" ]
How can I retrieve the page title of a webpage (title html tag) using Python?
I'll always use [lxml](http://lxml.de/) for such tasks. You could use [beautifulsoup](http://www.crummy.com/software/BeautifulSoup/) as well. ``` import lxml.html t = lxml.html.parse(url) print(t.find(".//title").text) ``` EDIT based on comment: ``` from urllib2 import urlopen from lxml.html import parse url = "htt...
Here's a simplified version of [@Vinko Vrsalovic's answer](https://stackoverflow.com/a/51242/4279): ``` import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen("https://www.google.com")) print soup.title.string ``` NOTE: * *soup.title* finds the first *title* element **anywhere**...
How can I retrieve the page title of a webpage using Python?
[ "", "python", "html", "" ]
I'm getting an error message when I try to build my project in eclipse: `The type weblogic.utils.expressions.ExpressionMap cannot be resolved. It is indirectly referenced from required .class files` I've looked online for a solution and cannot find one (except for those sites that make you pay for help). Anyone have ...
How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project? If you right click on your project and choose build `path->configure` build path and then choose the libraries tab. You should see the weblogic libr...
Add spring-tx jar file and it should settle it.
Indirectly referenced from required .class file
[ "", "java", "eclipse", "weblogic", "" ]
Working on a new back end system for my company, and one of their requests is for a window to become locked down and for the user to be sent to the login screen if they leave it idle for to long. I figure I'd do this with JavaScript by attaching listeners to clicks, mouse moves and key-ups but I worry about messing wi...
Firstly, for this to be effective, you have to make sure users are logged out on the server at the end of this idle time. Otherwise, nothing you do on the client side is effective. If you send them to a login page, they can just click the back button. Second, the conventional way to do this is to use a "meta refresh" ...
You could just make it do a log out if the user doesn't change pages after so long. That's what the Angel Learning Courseware system seems to do. The other problem you'll face, though, is that some users disable JavaScript.
How can I check to make sure a window is being actively used, and if not alert the end user that they are about to be logged out?
[ "", "javascript", "session", "" ]
How do you deal with source control management and automated deployment (configuration management) of database tables. I work in a SQL Server environment and it's pretty easy to script out drop and create files for stored procedures/triggers/functions even jobs. It's also easy to handle scripting out the creation of a ...
You can automatically create the initial creation script, but ALTER scripts really need to be hand-coded on a case-by-case basis, because in practice you need to do custom stuff in them. In any case, you'll need some way of creating apply and rollback scripts for each change, and have an installer script which runs th...
Tools like Red-gate's SQL Compare are invaluable in making sure you have a complete script. You still may need to manually adjust it to make sure the objects are scripted in the correct order. Make sure to script triggers and constraints, etc as well as tables.In general you will want to use alter commands instead of d...
How do you deal with configuration management of Database Tables?
[ "", "sql", "sql-server", "database", "t-sql", "" ]