Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an application in C#/Winforms that lets users place objects on a grid to create levels for a game. It has several tools for placing tiles/lights/doors/entities etc. Currently I just use an enum for storing the currently selected tool and have a switch statement to run each tools code. As I've been adding more tools to the application it's starting to get spaghetti like, with lots of duplicated code.
Here is a cutdown version of the mouse down function in my editor class:
```
public void OnEditorViewMouseDown(Point mousePos)
{
// Check if the click is out of bounds.
if (IsLocationOOB(mousePos)) return;
if (CurrentTool == ToolType.GroundTile)
{
// Allow drags along whole tiles only.
m_DragManager.DragType = DragManager.DragTypeEnum.Tile;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.WallTile)
{
// Allow drags along grid edges only.
m_DragManager.DragType = DragManager.DragTypeEnum.Edge;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.PostTile)
{
// Allow drags along grid points only.
m_DragManager.DragType = DragManager.DragTypeEnum.Point;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.AreaLight)
{
// Allow drags anywhere. ie. not snapped to the grid in some way.
m_DragManager.DragType = DragManager.DragTypeEnum.FreeForm;
m_DragManager.StartDrag(mousePos);
}
else if (CurrentTool == ToolType.PointLight)
{
m_CurrentWorld.AddLight(TranslateToWorldCoords(mousePos));
}
else if (CurrentTool == ToolType.PlaceEntity)
{
m_CurrentWorld.PlaceEntity(TranslateToWorldCoords(mousePos));
}
}
```
The switch is used in several other functions (OnMouseMove, OnMouseUp) and it seems like bad design (big switch copied in several functions). Any advice for refactoring something like this in a cleaner and more extensible way? I'm currently thinking of having a base `Tool` class and having each tool it's own class that overrides the functions it uses (OnMouseDown() etc.). Does this sound sensible?
Thanks for reading. | You have the good intuition.
Usually, in OOP, when you have rows of if's or humongous switches, it's a strong code smell. The best way to make this smell go away is to go with polymorphism.
You should go ahead with your idea, having a base abstract class BaseTool, with the different OnXXX methods implemented as nops (just returns, so you only have to specify the behavior if your tool knows how to act on the method), and have each tool inherit from BaseTool and implement its own behavior by overriding the relevant methods.
So your method ends up being
```
public void OnEditorViewMouseDown(Point mousePos)
{
currentTool.OnEditorViewMouseDown(mousePos);
}
```
Depending on your design, you should also consider passing the DragManager to the method, so as not to be tied to instance variables laying around. An EditorContext (containing the DragManager) fitted with everything the method needs without having to fetch "global" variables would make your method more self-contained and less brittle when refactoring. The design itself will depend on the responsability: who is in charge of what. | Sounds like a good place to use the Strategy Pattern: <http://www.google.com/search?q=c%23+strategy+pattern> | Refactoring advice for big switches in C# | [
"",
"c#",
"switch-statement",
""
] |
I have two DateTime vars, beginTime and endTime. I have gotten the difference of them by doing the following:
```
TimeSpan dateDifference = endTime.Subtract(beginTime);
```
How can I now return a string of this in hh hrs, mm mins, ss secs format using C#.
If the difference was 00:06:32.4458750
It should return this 00 hrs, 06 mins, 32 secs | Would [TimeSpan.ToString()](http://msdn.microsoft.com/en-us/library/1ecy8h51.aspx) do the trick for you? If not, it looks like the code sample on that page describes how to do custom formatting of a `TimeSpan` object. | I just built a few TimeSpan Extension methods. Thought I could share:
```
public static string ToReadableAgeString(this TimeSpan span)
{
return string.Format("{0:0}", span.Days / 365.25);
}
public static string ToReadableString(this TimeSpan span)
{
string formatted = string.Format("{0}{1}{2}{3}",
span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? string.Empty : "s") : string.Empty,
span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? string.Empty : "s") : string.Empty);
if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
return formatted;
}
``` | How do I convert a TimeSpan to a formatted string? | [
"",
"c#",
"timespan",
""
] |
What is a portable way (e.g. for Linux and Windows) to get the current user's username? Something similar to `os.getuid()` would be nice:
```
>>> os.getuid()
42
# Does not currently exist in Python
>>> os.getusername()
'slartibartfast'
```
The [`pwd`](https://docs.python.org/3/library/pwd.html) module works for Unix only. Some people suggest that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service). | Look at [`getpass`](http://docs.python.org/library/getpass.html) module
```
import getpass
getpass.getuser()
'kostya'
```
Availability: Unix, Windows
---
p.s. Per comment below "*this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other).*" | Combine `os.getuid()` with `pwd.getpwuid()`:
```
import os
import pwd
def get_username():
return pwd.getpwuid(os.getuid())[0]
```
See [`pwd`](http://docs.python.org/library/pwd.html) docs for more details. | Is there a portable way to get the current username in Python? | [
"",
"python",
"portability",
""
] |
When implementing a factory or simple factory, what would go against using a Type instead of an Enum to specify the class to instantiate?
For example
```
public class SimpleFactory
{
public static ITest Create(Type type)
{
if (type == typeof(ConcreteTest1))
return new ConcreteTest1();
if (type == typeof(ConcreteTest2))
return new ConcreteTest2();
throw new Exception("Invalid type");
}
}
``` | Using an enum is more restrictive, which means that it is less likely that the user will try to use your factory with an unsupported type.
I find that it's good to do everything possible when defining an API to discourage usage patterns that will cause exceptions to be thrown. Allowing "Type" in this case opens up millions of ways to call your function that will result in:
```
throw new Exception("Invalid type");
```
Using an enum would eliminate this. The only way an enum would throw would be if the user did something noticably wrong. | Factories are only useful if they perform configuration or initialization on your objects to put them in a valid state. I wouldn't bother with a factory if all it does is new up and return objects.
I would create a factory for each class hierarchy. For example:
```
public abstract class Vehicle {}
public class Car : Vehicle {}
public class Truck : Vehicle {}
public class VehicleFactory
{
public Vehicle CreateVehicle<T>() where T : Vehicle
{
// Get type of T and delegate creation to private methods
}
}
``` | Factory Pattern: Enums or Types? | [
"",
"c#",
"design-patterns",
""
] |
Let's say I have a Javascript associative array (a.k.a. hash, a.k.a. dictionary):
```
var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;
```
How can I iterate over the keys in sorted order? If it helps simplify things, I don't even need the values (they're all just the number 1). | You cannot iterate over them directly, but you can find all the keys and then just sort them.
```
var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;
function keys(obj)
{
var keys = [];
for(var key in obj)
{
if(obj.hasOwnProperty(key))
{
keys.push(key);
}
}
return keys;
}
keys(a).sort(); // ["a", "b", "z"]
```
However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:
```
var a = {};
a["key"] = "value";
``` | You can use the [Object.keys](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) built-in method:
```
var sorted_keys = Object.keys(a).sort()
```
(Note: this does not work in very old browsers not supporting EcmaScript5, notably IE6, 7 and 8. For detailed up-to-date statistics, see [this table](http://caniuse.com/#search=es5)) | Iterate over a Javascript associative array in sorted order | [
"",
"javascript",
""
] |
I looked at a couple other questions on SO - and not really sure they answer this question.
We are building C++ applications for Win32 and Linux. Right now we have some scripts (bat files for win32) that run on a schedule to do builds.
We'd like to have CI for our projects, but I'd like to have only one CI server that handles building on both platforms. Integration with SVN is important.
Is it possible to have one configuration/one CI product/server do this?
Has anyone done this successfully? Bamboo looks like it might solve our needs, but I hate to jump into an expenditure like that as a bootstrapped startup if we can avoid the cost. | You might want to have a go at [Hudson](http://hudson-ci.org/) or [Jenkins](https://jenkins-ci.org/) . Though primarily for Java-based projects, you could tweak them to suit your needs.
They integrate with SVN smoothly, plus you could use the muti-step build feature to call your (existing) batch files, and process further. | Buildbot is definetly one tool to look at - <http://buildbot.net/trac>. Central server which monitors all the projects and notifies agents of new tasks so you can build on any environment you really need without setting up cross compilation environment.
You could also look at Cruise Control @ <http://cruisecontrol.sourceforge.net>. While it looks like its more geared towards java building, you can do quite a lot with it. I have a setup that builds linux arm & i386 binaries and packages those into debs and maintains a debian repository from build results - run unittests and all kinds of stuff on the code..
But what i really wanted to say is that basicly, allmost all ci server software that i've used are mainly just "task schedulers" and you still need to build/configure the build environment yourself which is - in multiplatform scenarios atleast - bigger tasks that configuring a software that executes the builds and produces nice reports from them.. | Is there a tool for cross platform continuous integration (c++ Win32 and linux) | [
"",
"c++",
"continuous-integration",
"cross-platform",
""
] |
I want a behavior similar to e.g. Firefox where the list of available tabs does only show up if at least two tabs exist.
I wasn't able to find anything like that, yet.
The best idea I had was changing the layout manually:
* in case of one component, just add that to the surrounding panel
* if a component is added, remove the component from the surrounding panel, add a JTabbedPane instead and add both the previous and the new component to that pane.
* if a component is removed and only one component is left in the pane, remove the pane and add the contained component instead.
While this would probably work it feels like a hack or workaround...
Any better idea?
A solution should ideally work in both Java 1.5 and 1.6... but I'd be happy about a 1.6-only solution, too. | I believe you'll have to do it manually. Apparently [it has been done before](http://www-mipl.jpl.nasa.gov/vicar/vicar350/html/javadoc/jpl/mipl/mars/viewer/util/HideableTabbedPane.html), but only as a small bit of a system which seems to not be available.
Your approach looks good to me. I would do it just like you laid it out, and wrap all that logic in a custom `JComponent` so it will feel less hackish. | You can override the UI method that calculates the height for the tab button area, forcing the height to `0` when there's only one tab:
```
tabbed_pane.setUI(new BasicTabbedPaneUI() {
@Override
protected int calculateTabAreaHeight(int tab_placement, int run_count, int max_tab_height) {
if (tabbed_pane.getTabCount() > 1)
return super.calculateTabAreaHeight(tab_placement, run_count, max_tab_height);
else
return 0;
}
});
``` | Is there a way to hide the tab bar of JTabbedPane if only one tab exists? | [
"",
"java",
"user-interface",
"swing",
"jtabbedpane",
""
] |
I have 5 queries I'd like to join together. Basically what they do is they go though the database and select how much a tenant has paid, and how much a tenant owes based on how long ago he or she was charged.
I have four categories
Charge < 30 days old
Charge < 60 AND >= 30 days old
Charge < 90 AND >= 60 days old
Charge > 90 days old
I know how to get all those values separately, but how can I get them together, plus the amount the tenant has paid?
Here are my queries:
**Amount the Tenant Has Paid**
```
SELECT TransactionCode, TenantID, SUM(Amount) AS Paid FROM tblTransaction
WHERE Amount > 0
GROUP BY TransactionCode, TenantID
```
**Charge is less than 30 days old**
```
SELECT TransactionCode, TenantID, SUM(Amount) AS ChargedCurrent FROM tblTransaction
WHERE Amount < 0 AND TransactionDate > DATEADD("dd", -30, GETDATE())
GROUP BY TransactionCode, TenantID
```
**Charge is less than 60 days old, but older than 29 days**
```
SELECT TransactionCode, TenantID, SUM(Amount) AS ChargedOver30 FROM tblTransaction
WHERE Amount < 0 AND TransactionDate > DATEADD("dd", -60, GETDATE()) AND TransactionDate <= DATEADD("dd", -30, GETDATE())
GROUP BY TransactionCode, TenantID
```
**Charge is less than 90 days old, but older than 59 days**
```
SELECT TransactionCode, TenantID, SUM(Amount) AS ChargedOver60 FROM tblTransaction
WHERE Amount < 0 AND TransactionDate > DATEADD("dd", -90, GETDATE()) AND TransactionDate <= DATEADD("dd", -60, GETDATE())
GROUP BY TransactionCode, TenantID
```
**Charge is older than 89 days**
```
SELECT TransactionCode, TenantID, SUM(Amount) AS ChargedOver90 FROM tblTransaction
WHERE Amount < 0 AND TransactionDate <= DATEADD("dd", -90, GETDATE())
GROUP BY TransactionCode, TenantID
```
How can I get these all with one query? | It can be done like this:
```
SELECT TransactionCode, TenantID,
SUM(CASE WHEN Amount > 0 then Amount ELSE 0 END) AS Paid,
SUM(CASE WHEN Amount < 0 AND TransactionDate > DATEADD("dd", -30, GETDATE()) THEN Amount ELSE 0 END) AS ChargedCurrent,
SUM(CASE WHEN Amount < 0 AND TransactionDate > DATEADD("dd", -60, GETDATE()) AND TransactionDate <= DATEADD("dd", -30, GETDATE()) THEN Amount ELSE 0 END) AS ChargedOver30
SUM(CASE WHEN Amount < 0 AND TransactionDate > DATEADD("dd", -90, GETDATE()) AND TransactionDate <= DATEADD("dd", -60, GETDATE()) then Amount Else 0 END) AS ChargedOver60,
SUM(CASE WHEN Amount < 0 AND TransactionDate <= DATEADD("dd", -90, GETDATE()) THEN Amount ELSE 0 END) AS ChargedOver90
FROM tblTransaction
GROUP BY TransactionCode, TenantID
``` | using UNION to stitch the result sets together would work. You may want to translate it using the PIVOT capabilities to get the amounts into separate columns. Sorry I can't be more specific, I don't have my notes and I don't know the exact syntax for this stuff off the top of my head. | How can I combine these queries? | [
"",
"sql",
"sql-server-2005-express",
""
] |
I'm trying to make a Bison parser to handle UTF-8 characters. I don't want the parser to actually interpret the Unicode character values, but I want it to parse the UTF-8 string as a sequence of bytes.
Right now, Bison generates the following code which is problematic:
```
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
```
The problem is that many bytes of the UTF-8 string will have a negative value, and Bison interprets negative values as an EOF, and stops.
Is there a way around this? | `bison` yes, `flex` no. The one time I needed a bison parser to work with UTF-8 encoded files I ended up writing my own `yylex` function.
*edit*: To help, I used a lot of the Unicode operations available in [glib](https://developer.gnome.org/glib/2.60/glib-Unicode-Manipulation.html) (there's a `gunicode` type and some file/string manipulation functions that I found useful). | `flex` being the issue here, you might want to take a look at [`zlex`](http://www.cs.binghamton.edu/~zdu/zlex/). | Can Bison parse UTF-8 characters? | [
"",
"c++",
"utf-8",
"bison",
""
] |
There is a banking site that I cannot login to unless I allow all cookies to be accepted. I am using Firefox 3.0 and I have set it to not accept cookies except from the defined list (Tools - Options - Privacy - Cookies - Exceptions). I've added all the sites captured by Live HTTP Headers to the whitelist, but the login is still disabled. I've tried to enable all cookies and login, then look at the cookies I got - didn't see any new site to be added to the Exceptions list. Obviously the site is somehow checking if I'm accepting an arbitrary cookie. How can I find out what site needs to be whitelisted? Or do I not understand something about cookies, and accepting all cookies is somehow not the same as having all the right sites whitelisted?
The site is <https://www.citizensbank.ca/> and it shows the login fields only if any cookies are allowed, otherwise it shows the message "To login to online banking, you must have JavaScript and cookies enabled." | I'd get myself another machine (or a VMWare image), delete all cookies, allow all cookies from all sites, then go to your site and log in (which sounds similar to what you've already tried).
Then, after your banking session is finished (or during, if they create a short-lived cookie just for testing you have them enabled), have a look at your cookie jar to see what the bank added. That should tell you the domains you need to add to your real machine.
If that doesn't work, contact the bank and explain your issues. They'll either tell you which ones you need to allow or they'll tell you to allow them all. If the latter, you need to decide if they're still worth keeping as your bank.
Alternatively, you can either:
* use that VM you set up as a sandbox for accessing the bank if you don't want all cookies appearing on your main box.
* set up a script to delete all non-whitelisted cookies after FF shuts down.
* stop worrying about cookies altogether and just allow them (I don't think I've ever heard of cookies being used as an attack vector).
If you'd like, send me your account details (user/password) and I'll see if I can debug it from here :-) Just kidding (in case it wasn't immediately obvious).
**Update:**
Your bank has a particularly nefarious way of checking requirements. They check to see if you're accepting ALL cookies, something they have no business doing at all. They should just see if they can create a cookie and read it back, which would make them compatible with cookie managers.
The code they have is:
```
function testCookie() {
if (typeof navigator.cookieEnabled !== "undefined") {
return !!navigator.cookieEnabled;
} else{
document.cookie="testcookie";
return document.cookie.indexOf("testcookie")!=-1;
}
}
if(!testCookie()){
var browserWarningString = '';
browserWarningString += '<div class="warning">';
browserWarningString += '<p>To login to online banking, you must have
JavaScript and cookies enabled.</p>';
browserWarningString += '</div>\n';
document.getElementById("loginAuth").innerHTML = browserWarningString;
}
```
It's that first bit of `testCookie()`, the `return !!navigator.cookieEnabled` bit which is problematic. No amount of whitelisting URLs is going to help you here since that would only be checked once the global `cookieEnabled` is set to true (which it isn't for you, and rightly so).
Ideally, you'd just be able to replace that `testCookie()` function in the HTML that comes down.
I've found a similar site that talks about the same problem from a different bank (I guess banks are where all the brain-dead Javascript kiddies end up :-) [here](http://forums.mozillazine.org/viewtopic.php?f=38&t=547857&start=0&st=0&sk=t&sd=a), along with two proposed solutions.
The first was to install GreaseMonkey and use this script [here](http://userscripts.org/scripts/show/12163). Obviously this would need to be changed for your bank (URLs, function name and so on).
The last post on that first link above (at the moment, look for "afternoonnap, February 15th, 2009, 10:10 am" post) also shows how to achieve the same result using NoScript. This involves replacing the cookieEnabled script (for that specific page) with a more rational one, although I'd probably just opt for replacing it with `"return true"` and hang the consequences :-).
Hope that helps somewhat.
For completeness (in case the links ever disappear), I'll include the two scripts here. The GreaseMonkey one boils down to:
```
// ==UserScript==
// @name TD Canada Trust EasyWeb Repair
// @namespace tag:GossamerGremlin,2007-04-28:Repair
// @description Repair TD Canada Trust EasyWeb website.
// @include https://easyweb*.tdcanadatrust.com/*
// @exclude
// ==/UserScript==
var scriptName = "TD Canada Trust EasyWeb Repair";
// The above @include pattern is overbroad because it exposes this
// user script to potential attacks from URLs such as this:
// https://easyweb.evil.example.com/not.tdcanadatrust.com/bad.html
// The following check eliminates such possibilities:
if (location.href.match(/^https:\/\/easyweb\d\d[a-z].tdcanadatrust.com\//))
{
// Visibly mark page to remind that this script is in use.
if (document.body)
{
host = document.location.host;
dummyDiv = document.createElement('div');
dummyDiv.innerHTML = '<div><span style="color: red">Greased by: ' +
scriptName + ' (' + host + ')</span></div>';
document.body.insertBefore(dummyDiv.firstChild,
document.body.firstChild);
}
unsafeWindow.navigator.__defineGetter__("cookieEnabled",
canStoreCookieFixed);
}
```
```
// canStoreCookieFixed()
// TD's version relies on navigator.cookieEnabled, which is not set
// if customer has cookie manager, even when cookies are allowed for
// EasyWeb. The only reliable check for enabled cookies is to actually
// test if session cookie settings succeed, as done in this function
// replacement.
function canStoreCookieFixed()
{
var testSessionCookie ="testSessionCookie=Enabled";
document.cookie = testSessionCookie;
return (document.cookie.indexOf(testSessionCookie) != -1);
}
```
The NoScript version boils down to "add the following to about:config":
```
noscript.surrogate.nce.sources=@easyweb*.tdcanadatrust.com
noscript.surrogate.nce.replacement=navigator.__defineGetter__(
"cookieEnabled",function(){
var ed=new Date;
ed.setTime(0);
var tc="__noscriptTestCookie_"+Math.round((Math.random()*99999))
.toString(16)+"=1";
document.cookie=tc;
var ok=document.cookie.indexOf(tc)>-1;
document.cookie=tc+";expires="+ed.toGMTString();
return ok
}
);
```
**Test and update:**
When I install noscript and turn off cookies altogether in FF3, then add the following `about:config` items, the login prompt shows up for your bank, so I think this is probably the way to go:
```
noscript.surrogate.nce.sources = *.citizensbank.ca
noscript.surrogate.nce.replacement =
navigator.__defineGetter__("cookieEnabled",function(){return true});
```
I suggest you do this and test it to make sure you still have all your functionality. | you should add their registered base domain, so www.citizensbank.ca should work. You could also try to just allow cookies while logging on, and hitting ctl+shift+del when you're done. | How to figure out what site to add to cookie whitelist? | [
"",
"javascript",
"cookies",
"safe-browsing",
""
] |
Is there a way to call a url and get a response using javascript?
I need the equivalent of ASP.NET:
```
WebRequest req = HttpWebRequest.Create("http://someurl.com");
WebResponse webResponse = req.GetResponse();
```
I have an external url that holds some information I need and I want to call this url from javascript and parse the response in order to determine what to do in my application. | You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the [get](http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype) method.
```
$.get('http://someurl.com',function(data,status) {
...parse the data...
},'html');
```
If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.
Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain. | ```
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
//document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}
req.send(null);
``` | Call a url from javascript | [
"",
"javascript",
""
] |
When is about writing code into C++ using VS2005, how can you measure the performance of your code?
Is any default tool in VS for that? Can I know which function or class slow down my application?
Are other external tools which can be integrated into VS in order to measure the gaps in my code? | If you have the Team System edition of Visual Studio 2005, you can use the built-in profiler.
* <http://msdn.microsoft.com/en-gb/library/z9z62c29(VS.80).aspx> | [AMD CodeAnalyst](http://developer.amd.com/CPU/CODEANALYST/Pages/default.aspx) is available for free for both Windows and Linux and works on most x86 or x64 CPUs (including Intel's).
It has extra features available when you have an AMD processor, of course. It also integrates into Visual Studio.
I've had pretty good luck with it.
---
Note that there are generally at least two common forms of profiler:
* **instrumenting**: alters your build to record information at the beginning and end of certain areas (usually per function)
* **sampling**: periodically looks at what code is running to record information
The types of information recorded can include (but are not limited to): elapsed time, # of CPU cycles, cache hits/misses, etc.
Instrumenting can be specific to certain areas of the code (just certain files or just code you compile, not libraries you link to). The overhead is much higher (you're adding code to the project, which takes time to execute, so you're altering timing; you may change program behavior for e.g. interrupt handlers or other timing-dependent code). You're guaranteed that you will get information about the functions/areas you instrument, though.
Sampling can miss very small or very sporadic functions, but modern machines have hardware help to allow you to sample much more thoroughly. Note that some sampling systems may still inject timing differences, although they generally will be much much smaller.
Some profiling tools support a mixture of the above, depending on how you use them. | C++ code performance | [
"",
"c++",
"visual-studio",
"performance",
"visual-studio-2005",
""
] |
Every visit to my website updates a user's individual hit counter and updates a column for `time()` based on their ip address and id stored in a cookie. So when coming to output the data, what's a more efficient way of my following code with less database calls, as it's essentially a copy of itself:
```
<?
$last1Min = time()-60;
$last5Mins = time()-300;
$last1Hr = time()-6000;
$last1Dy = time()-144000;
$last1Wk = time()-1008000;
$last1Mnth = time()-30240000;
//last1Min
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last1Min";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last minute: " . $rows['COUNT(*)'] . "<br />\n";
}
//last5Mins
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last5Mins";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last 5 minutes: " . $rows['COUNT(*)'] . "<br />\n";
}
//last1Hr
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last1Hr";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last hour: " . $rows['COUNT(*)'] . "<br />\n";
}
//last1Dy
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last1Dy";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last day: " . $rows['COUNT(*)'] . "<br />\n";
}
//last1Wk
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last1Wk";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last week: " . $rows['COUNT(*)'] . "<br />\n";
}
//last1Mnth
$sql = "SELECT COUNT(*) FROM usersonline WHERE lastOnline > $last1Mnth";
while($rows = mysql_fetch_array(mysql_query($sql))) {
echo "Users online in the last month: " . $rows['COUNT(*)'] . "<br /><br />\n";
}
```
If there is a more efficient way of presenting this data, I'm wanting to extend it to show not only how many users for each of these metrics is online on my entire site, but record and output the data for every page on my site. | ```
SELECT
SUM(lastOnline <= 60) AS one_minute,
SUM(lastOnline <= 300) AS five_minutes,
...
SUM(lastOnline <= 30240000) AS one_month
FROM usersonline
```
Using this method, you can get everything you need in a single query with a single table scan; it doesn't get much more efficient than that. As others have mentioned, you should cache the result, as it's relatively expensive (even in this optimized form). There's no point in calculating this on every page load, especially if you're seeing multiple hits per second (which is extremely likely if you, say, hit the front page of digg)
lastOnline <= 60 evaluates to 1 for rows where the condition is true, and 0 for rows where the condition is false; SUM() sums these 1s and zeros, giving you a count of the number of rows for which the condition is true.
Learned this technique from a user comment in the mysql docs a few years ago; there are [similar examples elsewhere](http://en.wikibooks.org/wiki/MySQL/Pivot_table) | Set up a cron job that calculates the correct values only once every minute/5 minutes/etcetera. Cache the result and display that instead. There's really no need to calculate these kinds of stats X times a second when they only change once a minute or once ever half hour. | Find out how many users are online in PHP? | [
"",
"php",
"count",
""
] |
I need a `shared_ptr` like object, but which automatically creates a real object when I try to access its members.
For example, I have:
```
class Box
{
public:
unsigned int width;
unsigned int height;
Box(): width(50), height(100){}
};
std::vector< lazy<Box> > boxes;
boxes.resize(100);
// at this point boxes contain no any real Box object.
// But when I try to access box number 50, for example,
// it will be created.
std::cout << boxes[49].width;
// now vector contains one real box and 99 lazy boxes.
```
Is there some implementation, or I should to write my own? | It's very little effort to roll your own.
```
template<typename T>
class lazy {
public:
lazy() : child(0) {}
~lazy() { delete child; }
T &operator*() {
if (!child) child = new T;
return *child;
}
// might dereference NULL pointer if unset...
// but if this is const, what else can be done?
const T &operator*() const { return *child; }
T *operator->() { return &**this; }
const T *operator->() const { return &**this; }
private:
T *child;
};
// ...
cout << boxes[49]->width;
``` | Using `boost::optional`, you can have such a thing:
```
// 100 lazy BigStuffs
std::vector< boost::optional<BigStuff> > v(100);
v[49] = some_big_stuff;
```
Will construct 100 lazy's and assign one real `some_big_stuff` to `v[49]`. `boost::optional` will use no heap memory, but use placement-new to create objects in a stack-allocated buffer. I would create a wrapper around `boost::optional` like this:
```
template<typename T>
struct LazyPtr {
T& operator*() { if(!opt) opt = T(); return *opt; }
T const& operator*() const { return *opt; }
T* operator->() { if(!opt) opt = T(); return &*opt; }
T const* operator->() const { return &*opt; }
private:
boost::optional<T> opt;
};
```
This now uses `boost::optional` for doing stuffs. It ought to support in-place construction like this one (example on `op*`):
```
T& operator*() { if(!opt) opt = boost::in_place(); return *opt; }
```
Which would not require any copy-ing. However, the current boost-manual does not include that assignment operator overload. The source does, however. I'm not sure whether this is just a defect in the manual or whether its documentation is intentionally left out. So i would use the safer way using a copy assignment using `T()`. | Is there C++ lazy pointer? | [
"",
"c++",
"pointers",
""
] |
I use macros to code unrolled loops like this: (silly example)
```
#define foreach_small_prime(p, instr) { \
int p; \
p = 2; instr; \
p = 3; instr; \
p = 5; instr; \
p = 7; instr; \
}
foreach_small_prime(pp, cout << pp);
int sum = 0;
foreach_small_prime(pp, {
sum += pp;
if (sum >= 10) cout << sum << endl;
});
```
But in some cases I might use for construct:
```
#define foreach_small_even(ii) for(int ii = 0; ii < 20; ii += 2)
int sum = 0;
foreach_small_even(pp) {
sum += pp;
if (sum >= 10) cout << sum << endl;
}
```
I like this macros because I can pass a variable *name* as a parameter.
Question: Is there a way to define loop like the first one in a for-like syntax like the second macro? | You could check out the Boost [preprocessor](http://www.boostpro.com/tmpbook/preprocessor.html) library. It can do all sorts of looping things. The syntax isn't great, but I believe it works. I have not used it myself, however. | Do you have a good reason to avoid using an iterator object?
You have to consider your first macro pastes 4x your instr code...
Otherwise, a simple :
```
#define foreach_smallprime(ii) for(int ii = 0; ii <= 7; ii = next_prime(ii) )
```
with `next_prime(ii)` defined in the same file as the macro. | c++ loop macros | [
"",
"c++",
"macros",
"for-loop",
""
] |
Folks,
Please, what's a good way of writing really big XML documents (upto say 500 MB) in C# .NET 3.5? I've had a bit of search around, and can't seem to find anything which addresses this specific question.
My previous thread ([What is the best way to parse (big) XML in C# Code?](https://stackoverflow.com/questions/676274/what-is-the-best-way-to-parse-big-xml-in-c-code)) covered reading similar magnitude Xml documents... With that solved I need to think about how to write the updated features (<http://www.opengeospatial.org/standards/sfa>) to an "update.xml" document.
**My ideas:** Obviously one big DOM is out, considering the maximum size of the document to be produced. I'm using XSD.EXE to generate binding classes form the schema... which works nicely with the XmlSerializer class, but I think it builds a DOM "under the hood". Is this correct?. I can't hold all the features (upto 50,000 of them) in memory at one time. I need to read a feature form the database, serialize it, and write it to file. So I'm thinking I should use the XmlSerializer to write a "doclet" for each individual feature to the file. I've got no idea (yet) if this is even possible/feasible.
**What do you think?**
**Background:** I'm porting an old VB6 MapInfo "client plugin" to C#. There is an existing J2EE "update service" (actually just a web-app) which this program (among others) must work with. I can't change the server; unless absapositively necessary; especially of that involves changing the other clients. The server accepts an XML document with a schema which does not specificy any namespaces... ie: there is only default namespace, and everything is in it.
**My experience:** I'm pretty much a C# and .NET newbie. I've been programming for about 10 year in various languages including Java, VB, C, and some C++.
Cheers all. Keith.
PS: It's dinner time, so I'll be AWOL for about half an hour. | For writing large xml, `XmlWriter` (directly) is your friend - but it is harder to use. The other option would be to use DOM/object-model approaches and combine them, which is probably doable *if* you seize control of the`XmlWriterSettings` and disable the xml marker, and get rid of the namespace declarations...
```
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
public class Foo {
[XmlAttribute]
public int Id { get; set; }
public string Bar { get; set; }
}
static class Program {
[STAThread]
static void Main() {
using (XmlWriter xw = XmlWriter.Create("out.xml")) {
xw.WriteStartElement("xml");
XmlSerializer ser = new XmlSerializer(typeof(Foo));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
foreach (Foo foo in FooGenerator()) {
ser.Serialize(xw, foo, ns);
}
xw.WriteEndElement();
}
}
// streaming approach; only have the smallest amount of program
// data in memory at once - in this case, only a single `Foo` is
// ever in use at a time
static IEnumerable<Foo> FooGenerator() {
for (int i = 0; i < 40; i++) {
yield return new Foo { Id = i, Bar = "Foo " + i };
}
}
}
``` | Use a [XmlWriter](http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx):
> [...] a writer that provides a fast,
> non-cached, forward-only means of
> generating streams or files containing
> XML data. | How to write (big) XML to a file in C#? | [
"",
"c#",
"xml",
""
] |
One of the users of a Java swing GUI program that I wrote is having an issue where the main swing window doesn't render to the screen properly and the GUI freezes up. Here's a comparison of the screenshot on his screen (top) and what is supposed to show up (bottom):
[alt text http://www.shapecollage.com/temp/SwingCorruption.jpg](http://www.shapecollage.com/temp/SwingCorruption.jpg)
He is running Windows XP SP3 with Java 1.6.0\_13 and his graphics card is an ATI X1600 with a dual monitor set-up.
The program (if you would like to test for yourself) is at:
[www.shapecollage.com/download.html](http://www.shapecollage.com/download.html)
I have several thousand users and no one else has reported this error and I have tested it thoroughly on Windows XP. Anything computational is done in a separate thread from that of the regular GUI thread and the program works on many other computers, so I don't think it's a problem with the program itself, but rather, something wrong with his particular set-up.
Has anyone seen this type of error before on a system or have any suggestions as to what might be wrong on this user's system that would cause such a problem?
Thanks,
Vincent | We had a very similar problem, which was fixed by updating the graphics driver. The problem might come from the dual monitor setup leading to VRAM corruption, so your customer might try if it will work better with only a single monitor. While you might expect Java would not be very dependent on the hardware, our graphics-intensitive application always manages to BSOD when run through a particular projector type... | Maybe there's a problematic interaction between Java and the graphics driver and/or graphics hardware.
There are [several flags that can influence how Java draws to the screen](http://java.sun.com/j2se/1.5.0/docs/guide/2d/flags.html).
You might want to try to start the applications with any of those flags:
* `-Dsun.java2d.opengl=true`
* `-Dsun.java2d.d3d=false`
* `-Dsun.java2d.noddraw=true`
Those flags toggle the OpenGL pipeline, turn of using Direct3D and disable use of DirectDraw respectively.
If any of those solves your problem, then you might consider filing a Bug with sun, because then it's probably not the applications that's at fault here. | Corrupted Java Swing Window | [
"",
"java",
"windows",
"swing",
""
] |
I need to burn CD/DVD disks from my C++ program. Can you recommend me a method?
Edit: The platform is Windows. | On Windows, I have previously used the IMAPI2 interface very successfully. [This](http://www.codeproject.com/KB/winsdk/IMAPI2.aspx) site gives a really good set of sample code for this. You may need to extensively modify the code for your implementation, but it works, and works well.
One thing about the IMAPI2 interface; it's what you pretty much need to use if you're going to be writing to DVDs, as previous iterations of the IMAPI interface had inconsistent handling of writing to DVDs. | Why not call a cdrecord or growisofs or whatever console utility?
That's easy, doesn't requires anything, just drag that small executable with you.
They are also known to work just fine. | Burn CD/DVD from C++ program | [
"",
"c++",
""
] |
I'm scraping a site with HttpWebRequest, but the site is returning an error. The page works fine when I hit it from my browser. I'd like to compare them to see what may be causing the error. I know how to intercept the request from my browser to inspect the headers, but how do I view the data sent by HttpWebRequest? | In order to compare what you do in code, and what the browser does, I am sure a HTTP debugging tool such as [Fiddler](http://www.fiddler2.com/fiddler2/), would be the easiest solution.
Fiddler acts as a proxy between client and server, and displays all information sent over the HTTP protocol.
It is possible that you will need to configure your .NET app to use the proxy that Fiddler provides. [This blog post](http://www.west-wind.com/weblog/posts/596348.aspx) provides details on the subject. | <http://www.fiddler2.com/fiddler2/> is a great tool for such things. | How to view the headers sent by HttpWebRequest | [
"",
"c#",
""
] |
I have some text in an element in my page, and i want to scrap the price on that page without any text beside.
I found the page contain price like that:
```
<span class="discount">now $39.99</span>
```
How to filter this and just get "$39.99" just using JavaScript and regular expressions.
*The question may be too easy or asked by another way before but i know nothing about regular expressions so asked for your help :).* | ```
<script language="javascript">
window.onload = function () {
// Get all of the elements with class name "discount"
var elements = document.getElementsByClassName('discount');
// Loop over each <span class="discount">
for (var i=0; i < elements.length; i++) {
// get the text, e.g. "now $39.99"
var rawText = elements[i].innerHTML;
// Here's a regular expression to match one or more digits (\d+)
// followed by a period (\.) and one or more digits again (\d+)
var priceAsString = rawText.match(/\d+\.\d+/)
// You'll want to make the price a floating point number if you
// intend to do any calculations with it.
var price = parseFloat(priceAsString);
// Now what do you want to do with the price? I'll just write it out
// to the console (using FireBug or something similar)
console.log(price);
}
}
</script>
``` | ```
document.evaluate("//span[@class='discount']",
document,
null,
XPathResult.ANY_UNORDERED_NODE_TYPE,
null).singleNodeValue.textContent.replace("now $", "");
```
EDIT: This is standard [XPath](http://en.wikipedia.org/wiki/XPath). I'm not sure what kind of explanation you're seeking. For outdated browsers, you will need a third-party library like [Sarissa](http://dev.abiss.gr/sarissa/) and/or [Java-line](http://developer.javeline.com/). | How to filter using Regex and javascript? | [
"",
"javascript",
"html",
"regex",
""
] |
I've a problem with date in Javascript.
I need to increase by 1 day a date and I'm using this:
```
var myDate = new Date();
myDate.setDate(myDate.getDate() + 1);
```
but when is the 30th of june the increased date will be the 31th of june and not the 1st of lst of july.
how can I obtain a correct increased data??? | No it won't. Try this snippet, works just fine.
```
var myDate = new Date();
myDate.setDate(30); // it's June as of the writing of this question
// so we're setting it to June 30th.
myDate.setDate(myDate.getDate() + 1);
alert(myDate)
```
**Update:** I tried this in IE, Firefox, Chrome and Safari and it worked just fine. | How about setting time of the myDate:
myDate.setTime(myDate.getTime() + 24 \* 60 \* 60 \* 1000) | date problem in javascript | [
"",
"javascript",
""
] |
How do you build your own FastCGI interface in PHP?
I'd like to do something similar to what [they're doing in Perl](http://www.perl.com/doc/manual/html/lib/CGI/Fast.html), but in PHP. Is it even possible? Would it be faster?
(That is, I'd like to be able to load a web app framework *once* into memory, and then just have FastCGI call a method I provide for every request. So not the more generic preloading of the PHP-interpreter that is happening in the "default" PHP FastCGI setup.)
cheers!
(*Edit*: Isn't Mongrel and RoR doing this as well?)
Ok I've made a freakin' diagram now :)
 | I may be mistaken (it's late) but aren't you just trying to do some form of caching? Regardless, the FastCGI interface seems to be fairly well defined. So, it should be possible to do whatever you want, fairly easily. | You can *not* do it *in* PHP *for* PHP, you can do it in C for *cgi-sapi* but you probably want to use [APC](http://php.net/apc) instead. | Custom PHP FastCGI interface? (Faster?) | [
"",
"php",
"apache",
"fastcgi",
"lighttpd",
""
] |
Using Python, I'd like to compare every possible pair in a list.
Suppose I have
```
my_list = [1,2,3,4]
```
I'd like to do an operation (let's call it foo) on every combination of 2 elements from the list.
The final result should be the same as
```
foo(1,1)
foo(1,2)
...
foo(4,3)
foo(4,4)
```
My first thought was to iterate twice through the list manually, but that doesn't seem very pythonic. | Check out [`product()`](http://docs.python.org/library/itertools.html#itertools.product) in the `itertools` module. It does exactly what you describe.
```
import itertools
my_list = [1,2,3,4]
for pair in itertools.product(my_list, repeat=2):
foo(*pair)
```
This is equivalent to:
```
my_list = [1,2,3,4]
for x in my_list:
for y in my_list:
foo(x, y)
```
**Edit:** There are two very similar functions as well, [`permutations()`](http://docs.python.org/library/itertools.html#itertools.permutations) and [`combinations()`](http://docs.python.org/library/itertools.html#itertools.combinations). To illustrate how they differ:
`product()` generates every possible pairing of elements, including all duplicates:
```
1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
4,1 4,2 4,3 4,4
```
`permutations()` generates all unique orderings of each unique pair of elements, eliminating the `x,x` duplicates:
```
. 1,2 1,3 1,4
2,1 . 2,3 2,4
3,1 3,2 . 3,4
4,1 4,2 4,3 .
```
Finally, `combinations()` only generates each unique pair of elements, in lexicographic order:
```
. 1,2 1,3 1,4
. . 2,3 2,4
. . . 3,4
. . . .
```
All three of these functions were introduced in Python 2.6. | I had a similar problem and found the solution [here](http://www.wellho.net/resources/ex.php4?item=y104/tessapy). It works without having to import any module.
Supposing a list like:
```
people = ["Lisa","Pam","Phil","John"]
```
A simplified one-line solution would look like this.
**All possible pairs**, including duplicates:
```
result = [foo(p1, p2) for p1 in people for p2 in people]
```
**All possible pairs, excluding duplicates**:
```
result = [foo(p1, p2) for p1 in people for p2 in people if p1 != p2]
```
**Unique pairs**, where order is irrelevant:
```
result = [foo(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))]
```
---
In case you don't want to operate but just to get the pairs, removing the function `foo` and using just a tuple would be enough.
**All possible pairs**, including duplicates:
```
list_of_pairs = [(p1, p2) for p1 in people for p2 in people]
```
Result:
```
('Lisa', 'Lisa')
('Lisa', 'Pam')
('Lisa', 'Phil')
('Lisa', 'John')
('Pam', 'Lisa')
('Pam', 'Pam')
('Pam', 'Phil')
('Pam', 'John')
('Phil', 'Lisa')
('Phil', 'Pam')
('Phil', 'Phil')
('Phil', 'John')
('John', 'Lisa')
('John', 'Pam')
('John', 'Phil')
('John', 'John')
```
**All possible pairs, excluding duplicates**:
```
list_of_pairs = [(p1, p2) for p1 in people for p2 in people if p1 != p2]
```
Result:
```
('Lisa', 'Pam')
('Lisa', 'Phil')
('Lisa', 'John')
('Pam', 'Lisa')
('Pam', 'Phil')
('Pam', 'John')
('Phil', 'Lisa')
('Phil', 'Pam')
('Phil', 'John')
('John', 'Lisa')
('John', 'Pam')
('John', 'Phil')
```
**Unique pairs**, where order is irrelevant:
```
list_of_pairs = [(people[p1], people[p2]) for p1 in range(len(people)) for p2 in range(p1+1,len(people))]
```
Result:
```
('Lisa', 'Pam')
('Lisa', 'Phil')
('Lisa', 'John')
('Pam', 'Phil')
('Pam', 'John')
('Phil', 'John')
```
*Edit: After the rework to simplify this solution, I realised it is the same approach than Adam Rosenfield. I hope the larger explanation helps some to understand it better.* | Operation on every pair of element in a list | [
"",
"python",
"cartesian-product",
""
] |
I have the following problem:
```
public Boolean Exists(String userName)
{
IRepository<User> = new UserRepository();
User user = userRepository.First(u => u.Name == userName);
if (user == null) return false;
// Exists!
return true;
}
```
The problem is now, that I can't check the User object for null. Before I get there, I get an `InvalidOperationException` saying "**The sequence contains no elements**".
This seems really weird to me, especially as I don't want to establish control flow with exceptions (e.g. encapsulate in try..catch and return true/false in the respective parts).
What's going on here? Is this normal or is there something wrong with my respository (hint?!)
**By the way, this code works *perfectly* when the element that I'm looking for exists (the User is retrieved etc.). It only doesn't work when there is no match.** | Use FirstOrDefault instead of First. This will return null in the face of an empty collection.
```
IRepository<User> = new UserRepository();
User user = userRepository.FirstOrDefault(u => u.Name == userName);
``` | Try changing `.First()` to `.FirstOrDefault()`. | Sequence contains no elements error but I want to check for null | [
"",
"c#",
"asp.net-mvc",
"linq",
""
] |
I'm using the following code to update a DataGridView's cell value. This is called inside the 'CellDoubleClick' event handler for the DataGridView.
The problem is the cell only updates after I click onto another cell. Is there a better way of doing this?
```
string value = "";
if (_dataGrid1.CurrentRow.Cells[e.ColumnIndex].Value != null)
value = _dataGrid1.CurrentRow.Cells[e.ColumnIndex].Value.ToString();
FormEdit form = new FormEdit(value); // takes a string value
if (form.ShowDialog() == DialogResult.OK)
{
_dataGrid1.CurrentRow.Cells[e.ColumnIndex].Value = form.SourceText;
_dataGrid1.UpdateCellValue(e.ColumnIndex, e.RowIndex);
}
```
*Some variable names were changed to protect their identity* | I returned to the project that this is for today, and discovered my answer was easy. Suspend/ResumeLayout was the solution:
```
if (form.ShowDialog() == DialogResult.OK)
{
_dataGridView.SuspendLayout();
_dataGridView.CurrentRow.Cells[e.ColumnIndex].Value = form.TextBoxText;
_dataGridView.UpdateCellValue(e.ColumnIndex, e.RowIndex);
_dataGridView.ResumeLayout(true);
}
```
This was for double clicking a gridview cell, and editing the content in a modal form with a textbox. | Does calling \_dataGrid1.CommitEdit solve the problem? | UpdateCellValue() in a Datagridview | [
"",
"c#",
".net",
"datagridview",
""
] |
I need to add an index to a table, and I want to recompile only/all the stored procedures that make reference to this table. Is there any quick and easy way?
EDIT:
from SQL Server 2005 Books Online, Recompiling Stored Procedures:
As a database is changed by such actions as adding indexes or changing data in indexed columns, the original query plans used to access its tables should be optimized again by recompiling them. This optimization happens automatically the first time a stored procedure is run after Microsoft SQL Server 2005 is restarted. It also occurs if an underlying table used by the stored procedure changes. **But if a new index is added from which the stored procedure might benefit, optimization does not happen until the next time the stored procedure is run after Microsoft SQL Server is restarted.** In this situation, it can be useful to force the stored procedure to recompile the next time it executes
Another reason to force a stored procedure to recompile is to counteract, when necessary, the "parameter sniffing" behavior of stored procedure compilation. When SQL Server executes stored procedures, any parameter values used by the procedure when it compiles are included as part of generating the query plan. If these values represent the typical ones with which the procedure is called subsequently, then the stored procedure benefits from the query plan each time it compiles and executes. If not, performance may suffer | You can exceute sp\_recompile and supply the table name you've just indexed. all procs that depend on that table will be flushed from the stored proc cache, and be "compiled" the next time they are executed
See this from the msdn docs:
[sp\_recompile (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms181647.aspx) | They are generally recompiled automatically. I guess I don't know if this is guaranteed, but it has been what I have observed - if you change (e.g. add an index) the objects referenced by the sproc then it recompiles.
```
create table mytable (i int identity)
insert mytable default values
go 100
create proc sp1 as select * from mytable where i = 17
go
exec sp1
```
If you look at the plan for this execution, it shows a table scan as expected.
```
create index mytablei on mytable(i)
exec sp1
```
The plan has changed to an index seek.
EDIT: ok I came up with a query that appears to work - this gives you all sproc names that have a reference to a given table in the plan cache. You can concatenate the sproc name with the sp\_recompile syntax to generate a bunch of sp\_recompile statements you can then execute.
```
;WITH XMLNAMESPACES (default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
,TableRefs (SProcName, ReferencedTableName) as
(
select
object_name(qp.objectid) as SProcName,
objNodes.objNode.value('@Database', 'sysname') + '.' + objNodes.objNode.value('@Schema', 'sysname') + '.' + objNodes.objNode.value('@Table', 'sysname') as ReferencedTableName
from sys.dm_exec_cached_plans cp
outer apply sys.dm_exec_sql_text(cp.plan_handle) st
outer apply sys.dm_exec_query_plan(cp.plan_handle) as qp
outer apply qp.query_plan.nodes('//Object[@Table]') as objNodes(objNode)
where cp.cacheobjtype = 'Compiled Plan'
and cp.objtype = 'Proc'
)
select
*
from TableRefs
where SProcName is not null
and isnull(ReferencedTableName,'') = '[db].[schema].[table]'
``` | add SQL Server index but how to recompile only affected stored procedures? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"indexing",
""
] |
How to access the system clock in C#? I want to use system clock for time delay purpose instead of using thread.sleep();. | ```
DateTime time = DateTime.Now;
```
will get you the current time.
So if you want to `sleep` until a specific time you can use the `TimeSpan` to calculate the number of milliseconds until then. You still will need to use `thread.sleep` or better still [`System.Threading.Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) (or [`System.Timers.Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx)) to pause the process.
If, however, you want to start a process at a specific time, you'd be better off creating a separate application and creating a scheduled task to control it. This is accessed via the Control Panel. | Your best bet for delay purposes instead of sleep is to use a [Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx). You set it for a how often you want it to "tick" and you get events when that happens. | How to access the system clock in C# | [
"",
"c#",
""
] |
suppose I want to write ls or dir. how do I get the list of files in a given directory?
something equivalent of .NET's Directory.GetFiles, and additional information.
not sure about the string syntax, but:
```
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
``` | Look at the FindFirstFile and FindNextFile APIs
<http://msdn.microsoft.com/en-us/library/aa364418.aspx> | Check out [boost::filesystem](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm), an portable and excellent library.
**Edit**: An example from the library:
```
int main(int argc, char* argv[])
{
std::string p(argc <= 1 ? "." : argv[1]);
if (is_directory(p))
{
for (directory_iterator itr(p); itr!=directory_iterator(); ++itr)
{
cout << itr->path().filename() << ' '; // display filename only
if (is_regular_file(itr->status())) cout << " [" << file_size(itr->path()) << ']';
cout << '\n';
}
}
else cout << (exists(p) : "Found: " : "Not found: ") << p << '\n';
return 0;
}
``` | how to get filenames from folder in C++ | [
"",
"c++",
"file",
""
] |
Is it a standard way to assign to multiple variables from an array in JavaScript?
In Firefox and Opera, you can do:
```
var [key, value] = "key:value".split(":");
alert(key + "=" + value); // will alert "key = value";
```
But it doesn't work in IE8 or Google Chrome.
Does anyone know a nice way to do this in other browsers without a tmp variable?
```
var tmp = "key:value".split(":");
var key=tmp[0], value=tmp[1];
```
Is this something that will come in an upcoming JavaScript version, or just custom implementation in FF and Opera? | If you want to know what's coming, read the section on Destructuring Assignment.
<https://developer.mozilla.org/en/New_in_javascript_1.7>
What language features you can use is always dependent on your environment.
Developing for Mobile Safari (or a web stack for other browsers like the Palm Pre, Android, etc.) or AIR, for example, is more predictable than developing for the web at large (where you still have to take even IE6 into account).
---
A cross-browser solution to the problem at hand would be to initialize an array that had a list of the variables you want to fill in window.variable format, then just loop through. Can't imagine why you'd do it though. Seems like there would always be a better solution. | Destructuring assignment was standardized in ECMAScript 2015 (a.k.a. ES6). But not all browsers have implemented destructuring yet (as of March 2016), and even when they do it will take a while before users update to a browser with support. See [examples](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring#examples) in the spec for all the awesome things you can do. Here are some:
```
// Assign from array elements
var [key, value] = "key:value".split(":");
// key => 'key'
// value => 'value'
// Assign from object properties
var {name: a, age: b} = {name: 'Peter', age: 5};
// a => 'Peter'
// b => 5
// Swap
[a, b] = [b, a]
// a => 5
// b => 'Peter'
```
Because this feature breaks backwards compatibility, you'll need to [transpile](http://en.wikipedia.org/wiki/Transpile) the code to make it work in all browsers. Many of the existing transpilers support destructuring. [Babel](http://babeljs.io/) is a very popular transpiler. See [Kangax´s table of browser and transpiler ES6-support](http://kangax.github.io/compat-table/es6/).
More info:
[Compatibility table for ES6 browser support](http://kangax.github.io/es5-compat-table/es6/#Destructuring)
[Exploring ES6 - Destructuring chapter](http://exploringjs.com/es6/ch_destructuring.html) | Possible to assign to multiple variables from an array? | [
"",
"javascript",
""
] |
In SQL Server 2000 or above is there anyway to handle an auto generated primary key (identity) column when using a statement like the following?
```
Insert Into TableName Values(?, ?, ?)
```
My goal is to NOT use the column names at all. | By default, if you have an identity column, you do *not* need to specify it in the VALUES section. If your table is:
```
ID NAME ADDRESS
```
Then you can do:
```
INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')
```
This will auto-generate the ID for you, and you don't have to think about it at all. If you `SET IDENTITY_INSERT MyTbl ON`, you can assign a value to the ID column. | Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window. | Handling identity columns in an "Insert Into TABLE Values()" statement? | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"identity",
""
] |
How can i find the execution path of a installed software in c# for eg media player ,vlc player . i just need to find their execution path . if i have a vlc player installed in my D drive . how do i find the path of the VLC.exe from my c# coding | This method works for any executable located in a folder which is defined in the windows PATH variable:
```
private string LocateEXE(String filename)
{
String path = Environment.GetEnvironmentVariable("path");
String[] folders = path.Split(';');
foreach (String folder in folders)
{
if (File.Exists(folder + filename))
{
return folder + filename;
}
else if (File.Exists(folder + "\\" + filename))
{
return folder + "\\" + filename;
}
}
return String.Empty;
}
```
Then use it as follows:
```
string pathToExe = LocateEXE("example.exe");
```
Like Fredrik's method it only finds paths for some executables | Using C# code you can find the path for some excutables this way:
```
private const string keyBase = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
private string GetPathForExe(string fileName)
{
RegistryKey localMachine = Registry.LocalMachine;
RegistryKey fileKey = localMachine.OpenSubKey(string.Format(@"{0}\{1}", keyBase, fileName));
object result = null;
if (fileKey != null)
{
result = fileKey.GetValue(string.Empty);
fileKey.Close();
}
return (string)result;
}
```
Use it like so:
```
string pathToExe = GetPathForExe("wmplayer.exe");
```
However, it may very well be that the application that you want does not have an App Paths key. | how to find the execution path of a installed software | [
"",
"c#",
"windows",
""
] |
The query I'm running is as follows, however I'm getting this error:
> #1054 - Unknown column 'guaranteed\_postcode' in 'IN/ALL/ANY subquery'
```
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE `guaranteed_postcode` NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
```
My question is: why am I unable to use a fake column in the where clause of the same DB query? | You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
> Standard SQL doesn't allow you to
> refer to a column alias in a WHERE
> clause. This restriction is imposed
> because when the WHERE code is
> executed, the column value may not yet
> be determined.
Copied from [MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/problems-with-alias.html)
As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: [WHERE vs HAVING](https://stackoverflow.com/questions/2905292/where-vs-having/18710763#18710763). | Maybe my answer is too late but this can help others.
You can enclose it with another select statement and use where clause to it.
```
SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0
```
calcAlias is the alias column that was calculated. | Using column alias in WHERE clause of MySQL query produces an error | [
"",
"mysql",
"sql",
"mysql-error-1054",
""
] |
I am using datagridview and its datasource is a BindingList.
But when I try to change the visibility of first row, I am getting InvalidOperationException.
How can I change first row's visible value?
Thanks in advance. | I found how to do it.
You must specify:
datagridview.CurrentCell = null;
before setting:
row.Visible = false;
because if currentCell is in the row which is wanted to be hide, then mentioned problem occurs.
regards | Apply a filter perhaps on the DataSource or the grid. | How to change visibility of first row in datagridview | [
"",
"c#",
"datagridview",
"visibility",
""
] |
What I need is just a dynamically growing array. I don't need random access, and I always insert to the end and read it from the beginning to the end.
slist seems to be the first choice, because it provides just enough of what I need. However, I can't tell what benefit I get by using slist instead of vector. Besides, several materials I read about STL say, "vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence". Therefore, my question is: for my needs, is slist really a better choice than vector? Thanks in advance. | For starters, `slist` is non-standard.
For your choice, a linked list will be slower than a vector, count on it. There are two reasons contributing to this:
1. First and foremost, cache locality; vectors store their elements linearly in the RAM which facilitates caching and pre-fetching.
2. Secondly, appending to a linked list involves dynamic allocations which add a large overhead. By contrast, vectors most of the time do *not* need to allocate memory.
However, a `std::deque` will probably be even faster. [In-depth performance analysis](http://www.codeproject.com/KB/stl/vector_vs_deque.aspx) has shown that, despite bias to the contrary, `std::deque` is almost always superior to `std::vector` in performance (if no random access is needed), due to its improved (chunked) memory allocation strategy. | Yes, if you are always reading beginning to end, [slist](http://www.sgi.com/tech/stl/Slist.html) (a linked list) sounds like the way to go. The possible exception is if you will be inserting a large quantity of elements at the end at the same time. Then, the vector could be better if you use reserve appropriately.
Of course, profile to be sure it's better for *your* application. | Benefit of slist over vector? | [
"",
"c++",
"list",
"stl",
"vector",
""
] |
I'm working on an application with a co-worker at the moment - she is writing a web form that allows users to enter and manage text that will be saved to the database and then displayed within a desktop application.
I'm using a Rich Text Box to display the text from the database. We want to allow the users to use basic formatting (bold, italic, underline) in the web app, and then display that formatting in the desktop app.
I'm wondering if there is a tag or something that can be entered into the web form (like or [b] etc), that will automatically display the formatting within the RTB.
If that isn't possible, what will be the best way to achieve this functionality?
I'm using C# windows form for the desktop application.
Update:
The web form is in PHP. | I played around with this a few years back - basically I had text in a database that I was marking up to emphasize certain words. I marked it up in a stored procedure, and then translated that to RTF on the client side.
I tried looking into the RTF spec, but it's somewhat challenging to just read the spec and know what to do.
I suggest popping open Wordpad (Start -> Run... -> wordpad), and mess around with different font styles and such. Then save it off as an RTF document somewhere. Open up that document in a plain-text editor of your choice (I use [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm)), and that'll help you figure out RTF a lot easier.
Here's an example of a simple RTF document I created:
```
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{\colortbl ;\red0\green0\blue255;}
{\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 Hello World.\par
\b This text is bold.\b0\par
\i This text is italicized.\i0\par
\cf1 This text is blue.\cf0\par
}
```
Some of those tags are just extra markup that you can probably do without. Play around with it and see.
Eventually you should be able to do something along the lines of:
```
string rtf = GetMarkupTextFromServer();
rtf = rtf.Replace("[b]", @"\b");
rtf = rtf.Replace("[/b]", @"\b0");
rtf = rtf.Replace("[i]", @"\i");
rtf = rtf.Replace("[/i]", @"\i0");
...
mRichTextBox.Rtf = rtf;
``` | If the user won't be able to edit the data on the Windows side but only on the web side, you can store the HTML source in the DB and display that in a Webbrowser control in your windows app... | How to save rich text from a web application and display it in a rich text box | [
"",
"c#",
"winforms",
"formatting",
"webforms",
"richtextbox",
""
] |
I am looking for an editor/comparator for i18n property files that would help me keep different language files in sync.
Basically, something that would compare a bunch a of property files and show which keys are not present in a particular language.
a property would look something like
```
component.titlepage.title = hello world
```
A simple diff is not possible since the right-hand-side will be different from a language to another.
Our current infrastructure:
* Java application
* Built using maven2
* Different i18n property files for different components of the system. (1 property file per language per component) | The [Checkstyle](http://checkstyle.sourceforge.net/) tool, which I typically run as part of every continuous integration build which is done after every check-in to the main branch, will tell you if any given set of properties files has an inconsistent set of properties. When I first started using Checkstyle, I indeed found that a few of my properties files were missing a small number of properties.
This won't help on the editor end, but it *will* help you efficiently identify any gaps. | If you are using Eclipse, I find the ResourceBundle Editor plugin very handy. You can edit several properties files at the same time and you have warnings when a key is missing in one of the files. | Keeping i18n resources synced | [
"",
"java",
"properties",
"editor",
"internationalization",
""
] |
how to find unused functions in a c++ project vc2008 | I always use "/OPT:REF" when creating release versions. This flag removes all unreferenced functions and will reduce the final binary substantially if there are many functions not being used (in our case we have a kernel with loads of methods used differently from different customized applications).
The "/VERBOSE" will send information about the linking session to the output window, or to stdout if you are linking on the command line. In the latter you can always redirect this to a file.
Using both flags together will make the output contain all eliminated functions and/or data that is never referenced.
Cheers! | Select "Run code Analysis on 'your project name'" from the Analyze/Build menu (according to your VS edition), VS will show a warning if there is an unused functions. | Find unused function in vc2008? | [
"",
"c++",
"function",
""
] |
I need to be able to pass a typename as a parameter:
```
int X = FileRead(file, 9, char);
```
The concept is for FileRead(std::fstream, int pos, ???) to read pos\*sizeof(whatever the type is) to get the desired position. I tried templates:
```
template<typename T>
T FileRead(std::fstream file, int pos, T type)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
```
but that required that I create a variable of the type to use every time I wanted to use FileRead, and I really don't feel like redesigning an entire program just because of one function, so is there anyway to use a typename as a parameter? | To use the name of a type as a parameter, use a template.
```
template<typename T>
T FileRead(std::fstream &file, int pos)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(T));
return data;
}
```
This assumes that the type is default constructible. If it is not, I guess you would have difficulty streaming it out of a file anyway.
Call it like this:
```
char value=FileRead<char>(file, pos);
```
If you do not want to have to specify the type in the call, you could modify your API:
```
template<typename T>
void FileRead(std::fstream &file, int pos, T &data)
{
file.read(reinterpret_cast<char*>(&data), sizeof(T));
}
```
Then call it like this - the type is inferred:
```
char value;
FileRead(file, pos, value);
``` | Very simple:
```
template<typename T>
T FileRead(std::fstream file, int pos)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
```
and call it via:
```
char x = FileRead<char>(file, pos);
``` | How to take a typename as a parameter in a function? (C++) | [
"",
"c++",
"file-io",
"typename",
"function-parameter",
""
] |
I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use.
For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness" in the green domain.
For example, a response may be 'abcd', and my "background colors" data may be:
```
[0.0, 1.0, 0.5, 1.0]
```
This would mean the first character 'a' needs to have a background of dark green (e.g. 004000), the second character 'b' needs to have a background of bright green (e.g. 00ff00), the third character 'c' needs to have a "middle" brightness (e.g. 00A000), and so on.
I don't want to use a template but rather just return "plain text" response. Is that possible?
If not - what would be the simplest template I could use for that?
Thanks | It could be something like this:
```
aString = 'abcd'
newString =''
colors= [0.0, 1.0, 0.5, 1.0]
for i in aString:
newString = newString + '<span style="background-color: rgb(0,%s,0)">%s</span>'%(colors.pop(0)*255,i)
response = HttpResponse(newString)
```
untested | you can use something like this to generate html in the django view itself
and return it as text/html
```
data = "abcd"
greenShades = [0.0, 1.0, 0.5, 1.0]
out = "<html>"
for d, clrG in zip(data,greenShades):
out +=""" <div style="background-color:RGB(0,%s,0);color:white;">%s</div> """%(int(clrG*255), d)
out += "</html>"
``` | HTML Newbie Question: Colored Background for Characters in Django HttpResponse | [
"",
"python",
"html",
"django",
"colors",
""
] |
I'm porting some code to Windows, and the Microsoft compiler (Visual C++ 8) is telling me that `strerror()` is unsafe.
Putting aside the annoyance factor in all the safe string stuff from Microsoft, I can actually see that some of the deprecated functions are dangerous. But I can't understand what could be wrong with `strerror()`. It takes a code (`int`), and returns the corresponding string, or the empty string if that code is not known.
Where is the danger?
Is there a good alternative in C?
Is there a good alternative in C++?
[edit]
Having had some good answers, and now understanding that some implementations may be crazy enough to actually write to a common shared buffer - unsafe to reentrancy within a single-thread, never mind between threads! - my question stops being "Why can't I use it, and what are the alternatives?" to "Are there any decent, succinct alternatives in C and/or C++?"
Thanks in advance | `strerror` is deprecated because it's not thread-safe. `strerror` works on an internal static buffer, which may be overwritten by other, concurrent threads. You should use a secure variant called `strerror_s`.
The secure variant requires that the buffer size be passed to the function in order to validate that the buffer is large enough before writing to it, helping to avoid buffer overruns that could allow malicious code to execute. | `strerror` by itself is not unsafe. In the olden days before threading it simply wasn't a problem. With threads, two or more threads could call `strerror` leaving the returned buffer in an undefined state. For single-threaded programs, it shouldn't hurt to use `strerror` unless they're playing some weird games in libc, like common memory for all apps in a DLL.
To address this there's a new interface to the same functionality:
```
int strerror_r(int errnum, char *buf, size_t buflen);
```
Note that the caller provides the buffer space and the buffer size. This solves the issue. Even for single-threaded applications, you might as well use it. It won't hurt a bit, and you might as well get used to doing it the safer way.
NOTE: the above prototype is from the POSIX spec for [`strerror_r()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strerror_r.html). It may vary per platform or with compiler options or `#define` symbols. GNU, for instance, makes that or their own version available depending on a `#define`. | Why can't I use strerror? | [
"",
"c++",
"c",
"deprecated",
""
] |
The query below is perfectly functional, and queries a single table to find the last 50 usernames added via a sequential `userid` number column.
Logic so far is to: find out the highest userid; subtract 50 from that; pull usernames back where greater.
However, it doesn't look elegant, and uses two subqueries to achieve it's goal:
```
SELECT username
FROM table
WHERE userid IN
(SELECT userid
FROM table
WHERE userid >
(SELECT MAX(userid) -50
FROM table))
```
Is there a way to make this less nested? More efficient? More elegant? Any help would be much appreciated, as this can't be the best way!
Cheers & many thanks
Ali | The answers provided are along the right lines.
You can use ROWNUM to select TOP-N style results.
Please be careful though and note that the rownum is assigned to the query results after predication but before the ORDER BY. Try something like the following:
```
SELECT username
FROM
(SELECT username
FROM table
ORDER BY userid DESC)
WHERE rownum <= 50
``` | ```
SELECT * FROM (SELECT UserName FROM Table ORDER BY UserID DESC)
WHERE RowNum <= 50
```
... I think... been a while since I fiddled with Oracle.
This is roughly the same as
`SELECT Top 50` in SQLServer
and
`SELECT ... LIMIT` 50 in MySql | More elegant SQL? | [
"",
"sql",
"database",
"oracle",
""
] |
I have an array of buttons which shall all call the same method but with the index of the button as an argument.
```
using System;
using Gtk;
public class Input : Gtk.Window {
private Gtk.Button[] plus;
public Input() : base(Gtk.WindowType.Toplevel) {
plus = new Button[10];
```
[...]
```
for (uint i = 0; i < 10; i++) {
plus[i] = new Button();
plus[i].Name = i.ToString();
plus[i].ButtonPressEvent += AddButtonPressed;
}
}
```
I tried it using this method, but it seems it gets not even called as there is no output:
```
protected virtual void AddButtonPressed(object sender, System.EventArgs e) {
Console.WriteLine("Button pressed");
for (uint i = 0; i < plus.Length; i++) {
if (sender.Equals(plus[i])) {
uint index = i;
i = (uint)plus.Length;
Console.WriteLine(index);
}
}
```
Maybe someone can point me in the right direction?
Thanks. | Quick answer:
```
[GLib.ConnectBefore]
protected virtual void AddButtonPressed(object sender, EventArgs e) {
Console.WriteLine("Button pressed");
for (uint i = 0; i < plus.Length; i++) {
if (sender.Equals(plus[i])) {
uint index = i;
i = (uint)plus.Length;
Console.WriteLine(index);
}
}
}
```
Rambling explanation:
This is actually an interesting question. It took a bit of searching to find, but [GTK#'s FAQ](http://gtk-sharp.sourceforge.net/faq.html#3.3) (but I guess not frequently linked to) says,
> "As of release 0.15, Gtk# started
> using the CONNECT\_AFTER flag when
> connecting event handlers to signals.
> This means that the event handlers are
> not run until after the default signal
> handlers, which means that the widget
> will be updated when the event
> handlers run. A side effect of this
> change is that in the case where
> default handlers return true to stop
> signal propogation, Gtk# events will
> not be emitted. This is the case for
> example in Gtk.Button, where the
> button-press-event default signal
> handler is overridden to emit Pressed
> events.
>
> While potentially confusing, this is
> not really a bug. When you use a
> Gtk.Button, you are getting a widget
> that emits Pressed events in response
> to Button1 presses. If you also want
> your Button to change colors, or popup
> a context menu on Button3 presses,
> that's not a Gtk.Button. The correct
> way to implement such a widget is to
> subclass Gtk.Button and override the
> OnButtonPressEvent virtual method to
> implement the new behaviors you
> desire."
If it weren't for, "public outcry" (rarely a sign of a good interface), there would be no way to avoid this, except subclassing which is sometimes annoying in C# due to the lack of anonymous classes. But luckily, you're not the first person to have this issue. So that's where the GLib.ConnectBefore attribute comes in. It basically says, call this event handler first so the event isn't devoured by Gtk+.
The annoyance doesn't end there though. I originally was going to suggest applying a good proven solution to passing "extra" parameters to event handlers. In this case, this would allow you to find the index without using equals or the `Name` string It basically involves creating a wrapper delegate that "pretends" to be a ButtonPressEventHandler but internally passes an int to your backing method:
```
Func<uint, ButtonPressEventHandler> indexWrapper = ((index) => ((s, e) => { AddButtonPressed_wrapped(s, e, index); }));
...
plus[i].ButtonPressEvent += indexWrapper(i);
...
protected virtual void AddButtonPressed_wrapped(object sender, EventArgs e, uint index)
{
Console.WriteLine("Button pressed");
Console.WriteLine("Index = {0}", index);
}
```
It compiles and runs without errors, but it has the same problem, the event never fires. I realized that you can't put an attribute directly on a delegate/lambda. So even though the backing method has `[GLib.ConnectBefore]` the delegate doesn't, so it fails.
As a final note, you could use the Clicked event as in [this API example](http://www.go-mono.com/docs/index.aspx?tlink=root:/classlib-gnome). I verified that it works as expected. One would think that it would only fire on mouse-clicks, but it actually does fire on spacebar as well. | ```
for (uint i = 0; i < 10; i++)
{
plus[i] = new Button();
plus[i].Data.Add("Index",i);
plus[i].ButtonPressEvent += AddButtonPressed;
Add(plus[i]);
}
```
Handler:
```
protected virtual void AddButtonPressed(object sender, System.EventArgs e) {
Console.WriteLine("Button pressed");
Gtk.Button button = sender as Gtk.Button;
Console.WriteLine("Index: {0}", button.Data["Index"]);
}
``` | C#: Get which button was pressed in an array of gtk#-buttons? | [
"",
"c#",
"arrays",
"events",
"button",
"gtk#",
""
] |
How do i add a TAB (\t) to a string resource ?
"\tText" doesn't work | You have two options that I am aware of:
1. Do a string replace after reading your resource string: s = s.Replace("\\t","\t");
2. Enter the escape sequence directly into your resource string at creation time by typing Alt-012 (I think that's tab) on the numeric keypad.
Articles on the same [here](https://web.archive.org/web/20210506001046/http://www.devx.com/tips/Tip/31408) and [here](https://web.archive.org/web/20210415070954/https://www.devx.com/tips/Tip/34769). | You have to explicitly add the tab in. The easiest way of doing this is probably to type out your string in notepad (with the tab explicitly set in place rather then using an escape character) and copy and paste the text into the resource editor.
You will have a similar problem with newlines, the easiest way of adding them in is to - again - add newlines in explicitly by using the shift-enter key combination. | tabbing in C# resource file | [
"",
"c#",
"visual-studio",
"string",
""
] |
Sometimes application can't exit when I called **[Application.Shutdown](http://msdn.microsoft.com/en-us/library/ms597013.aspx)**, the UI was closed, but the process is still running. how to shutdown application with close all threads? does the **[Environment.Exit](http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx)()** could close all thread? or we should call Win32 API **TerminateThread** to do it? | [Environment.Exit()](http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx) is a more brutal way of closing down your application, yes. But in general, if you need to kill your application to make it close then I think you're looking at the problem in the wrong way.
You should rather look into why the other threads aren't closing gracefully.
You could look into the [FormClosing event](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx) on the main form and close down any resources that are hanging up the application, preventing it from closing.
This is how I have found resources hanging up the app.
1. In debug mode, enable showing of [threads](https://stackoverflow.com/questions/164600/how-can-i-see-my-applications-threads-while-debugging-in-visual-studio). (This will allow you to see all the threads your application is running.)
2. Close the application in the way that it does not close correctly.
3. Press pause in Visual studio.
4. Look at the threads list, and click on them to see where is the code they are hanging. Now that you can see what resources are blocking your application from closing, go to your FormClosing event and close/dispose them there.
5. Repeat until the app closes correctly :)
Be aware that the threads list in debug mode will show some threads that are run but not under your control. These threads rarely have a name and when you click on them you get a message saying you have no symbols. These can be safely ignored.
One of the reasons for making sure your application is closing gracefully is that some resources (let's say a [FileStream](http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx)) are not done working, so using some API to force it to quit can make all sorts of "random" problems come in, like settings/data files not being written and so on. | 1. [You should **NEVER** call TerminateThread](https://web.archive.org/web/20071221023907/http://blogs.msdn.com/cbrumme/archive/2003/08/20/51504.aspx)
2. Make sure that all the threads that you spawn are mark as background, this way when you close the application it won't wait for them to complete. | what's difference between Environment.Exit() and Application.Shutdown()? | [
"",
"c#",
".net",
""
] |
I'm using Smarty and utilizing the config\_load respective `{#VAR#}` variables to implement localization. This is working perfectly fine as long as the content is within the templates, but fails as soon as I have to add dynamic content within the TPL file, i.e. with:
```
{if isset($var) }
{foreach from=$var item=line}
{$line}<br>
{/foreach}
{/if}
```
Please note each entry within $var contains usually one `{#VAR#}` entry - and they are **not translated** (the user will see `{#VAR#}`).
What is the proper way to implement localization in this case?
---
**Solution**
I ended up by only replacing `{$line}<br>` in the code above with:
```
{eval var=$line}
```
That did the trick for me. | You are probably looking for something like {eval}
Take a look at [{eval}](http://www.smarty.net/manual/en/language.function.eval.php) documentation.
On your situation, you could try this:
# example.php
```
<?php
(...)
$var = array("{#OK#}", "{#CANCEL#}");
$smarty->assign('var', $var);
$smarty->display('example.tpl');
?>
```
# example.config
```
OK = Okay
CANCEL = Nevermind
```
# example.tpl
```
{config_load file='example.config'}
<h1>Template stuff</h1>
{if isset($var) }
{foreach from=$var item=line}
{eval var=$line}<br>
{/foreach}
{/if}
```
Hope that helps! :) | a great aproach I've seen was use modifiers for translations. this allow you to translate dynamic content.
all the code its just an example, wont work, just to give you an idea
lets say
## your tpl
```
{"Hello word! How are you %s?"|translate:"Gabriel"}
{$myvar|translate:"Gabriel"}
```
## your modifier
```
function smarty_modifier_translate($content, $args) {
$lang = Env::getLanguage();
return vsprintf($lang->getTranslation($content), $args);
}
``` | Dynamic content with PHP & Smarty | [
"",
"php",
"localization",
"smarty",
""
] |
I want to implement SO like tags on userpost. I have a table called tag\_data with columns tagId, title, count. I have a separate table that links the relationship between a post and the many tags it may use.
Heres the problem, how do i get the current count, increase or decrease it by one and store it SAFELY. So no other connection/thread will update it between the time i do select and update? | I assume you also want the new count, other wise this is a no brainer, just update set count=count+1.
If your db support output clause on UPDATE (eg. SQL Server 2K5 or 2K8):
```
UPDATE table
SET count = count + 1
OUTPUT inserted.count
WHERE id=@id;
```
otherwise:
```
begin transaction
update table
set counter=counter+1
where id=@id;
select counter
from table
where id=@id;
commit;
``` | SET Count = Count + 1 is IMHO the easiest solution..
More generally the concept of being able to get data, process it and while its being processed demand there be no underlying changes before writing the results of the processing is ususally not a reasonable one to have if you also require a scalable system.
You can of course do this and in many environments get away with it.. however these approaches will put severe limits on the scalaibility and complexity of an application before concurrency issues render the system unusable.
IMHO the better approach is to take an optimistic route and detect/retry if in the unususal case something you care about did change.
SELECT Count AS old ... FROM ...
.. processing ...
UPDATE ... SET Count = oldplus1 WHERE Count = old AND ...
Unless UPDATE gives you the rowcount your expecting you assume the data was modified and try again until it succeeds. | Update a count (field) safely in SQL | [
"",
"sql",
"concurrency",
""
] |
Is there a way to select a database from a variable?
```
Declare @bob as varchar(50);
Set @bob = 'SweetDB';
GO
USE @bob
``` | Unfortunately, no.
Unless you can execute the rest of your batch as dynamic SQL.
Using `execute` to dynamically execute SQL will change the context for the scope of the `execute` statement, but will not leave a lasting effect on the scope you execute the `execute` statement from.
In other words, this:
```
DECLARE @db VARCHAR(100)
SET @db = 'SweetDB'
EXECUTE('use ' + @db)
```
Will not set the current database permanently, but if you altered the above code like this:
```
DECLARE @db VARCHAR(100)
SET @db = 'SweetDB'
EXECUTE('use ' + @db + ';select * from sysobjects')
select * from sysobjects
```
Then the result of those two queries will be different (assuming you're not in SweetDB already), since the first select, executed inside `execute` is executing in SweetDB, but the second isn't. | ```
declare @NewDB varchar(50)
set @NewDB = 'NewDB'
execute('use ' + @NewDB)
``` | Is there a way to select a database from a variable? | [
"",
"sql",
"sql-server",
"dynamic-sql",
""
] |
I am successfully exporting to excel with the following statement:
```
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\template.xls;',
'SELECT * FROM [SheetName$]')
select * from myTable
```
Is there any standard way to use this template specifying a new name for the excel sheet so that the template never gets written to or do I have to come up with some work-around?
What's the best way to do this in people experience? | You'd have to use dynamic SQL. `OPENROWSET` etc only allows literals as parameters.
```
DECLARE @myfile varchar(800)
SET @myfile = 'C:\template.xls'
EXEC ('
insert into OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',
''Excel 8.0;Database=' + @myfile + ';'',
''SELECT * FROM [SheetName$]'')
select * from myTable
')
```
> Remember: the path is relative to where SQL Server is running | Couldn't you make a copy of your template first, then pass the copy's filename into OPENROWSET? | SQL Server export to Excel with OPENROWSET | [
"",
"sql",
"sql-server",
"excel",
"export-to-excel",
"openrowset",
""
] |
I'm finding myself coding a big project in Javascript. I remember the last one was quite an adventure because hacky JS can quickly becomes unreadable and I want this code to be clean.
Well, I'm using objects to construct a lib, but there are several ways to define things in JS, implying important consequences in the scope, the memory management, the name space, etc. E.G :
* using `var` or not;
* defining things in the file, or in a `(function(){...})()`, jquery style;
* using `this`, or not;
* using `function myname()` or `myname = function()`;
* defining methods in the body of the object or using "prototype";
* etc.
So what are really the best practices when coding in OO in JS ?
Academic explanations really expected here. Link to books warmly welcome, as long as they deal with quality and robustness.
EDIT :
Got some readings, but I'm still very interested in answers to the questions above and any best practices. | ### Using `var` or not
You should introduce any variable with the `var` statement, otherwise it gets to the global scope.
It's worth mentioning that in strict mode (`"use strict";`) [undeclared variable assignments throws `ReferenceError`](http://hacks.mozilla.org/2011/01/ecmascript-5-strict-mode-in-firefox-4/).
At present JavaScript does not have a block scope. The Crockford school teaches you to [put var statements at the beginning of the function body](http://javascript.crockford.com/code.html#variable%20declarations), while Dojo's Style Guide reads that [all variables should be declared in the smallest scope possible](http://docs.dojocampus.org/developer/styleguide). (The [`let` statement and definition](https://developer.mozilla.org/en/New_in_JavaScript_1.7#let_statement) introduced in JavaScript 1.7 is not part of the ECMAScript standard.)
It is good practice to bind regularly-used objects' properties to local variables as it is faster than looking up the whole scope chain. (See [Optimizing JavaScript for extreme performance and low memory consumption](http://codeutopia.net/blog/2009/04/30/optimizing-javascript-for-extreme-performance-and-low-memory-consumption/).)
### Defining things in the file, or in a `(function(){...})()`
If you don't need to reach your objects outside your code, you can wrap your whole code in a function expression—-it's called the module pattern. It has performance advantages, and also allows your code to be minified and obscured at a high level. You can also ensure it won't pollute the global namespace. [Wrapping Functions in JavaScript](http://peter.michaux.ca/articles/wrapping-functions-in-javascript) also allows you to add aspect-oriented behaviour. Ben Cherry has an [in-depth article on module pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth).
### Using `this` or not
If you use pseudo-classical inheritance in JavaScript, you can hardly avoid using `this`. It's a matter of taste which inheritance pattern you use. For other cases, check Peter Michaux's article on [JavaScript Widgets Without "this"](http://peter.michaux.ca/articles/javascript-widgets-without-this).
### Using `function myname()` or `myname = function();`
`function myname()` is a function declaration and `myname = function();` is a function expression assigned to variable `myname`. The latter form indicates that functions are first-class objects, and you can do anything with them, as with a variable. The only difference between them is that all function declarations are hoisted to the top of the scope, which may matter in certain cases. Otherwise they are equal. `function foo()` is a shorthand form. Further details on hoisting can be found in the [JavaScript Scoping and Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) article.
### Defining methods in the body of the object or using "prototype"
It's up to you. JavaScript has four object-creation patterns: pseudo-classical, prototypical, functional, and parts ([Crockford, 2008](http://oreilly.com/catalog/9780596517748/)). Each has its pros and cons, see [Crockford in his video talks](http://yuiblog.com/crockford/) or get his book *The Good Parts* as [Anon already suggested](https://stackoverflow.com/questions/907225/object-oriented-javascript-best-pratices/907275#907275).
### Frameworks
I suggest you pick up some JavaScript frameworks, study their conventions and style, and find those practices and patterns that best fit you. For instance, the [Dojo Toolkit](http://docs.dojocampus.org/dojo/declare) provides a robust framework to write object-oriented JavaScript code which even supports multiple inheritance.
### Patterns
Lastly, there is a blog dedicated to [explore common JavaScript patterns and anti-patterns](http://www.jspatterns.com/category/patterns/object-creation/). Also check out the question *[Are there any coding standards for JavaScript?](https://stackoverflow.com/questions/211795/are-there-any-coding-standards-for-javascript)* in Stack Overflow. | I am going to write down some stuffs that I read or put in application since I asked this question. So people reading it won't get frustrated, as most of the answers are RTMF's in disguise (even if I must admit, suggested books ARE good).
## Var usage
Any variable is supposed to be already declared at the higher scope in JS. So when ever you want a new variable, declare it to avoid bad surprises like manipulating a global var without noticing it. **Therefore, always use the var keyword.**
In an object make, var the variable private. If you want to just declare a public variable, use `this.my_var = my_value` to do so.
## Declaring methods
In JS, they are numerous way of declaring methods. For an OO programmer, the most natural and yet efficient way is to use the following syntax:
Inside the object body
```
this.methodName = function(param) {
/* bla */
};
```
There is a drawback: inner functions won't be able to access "this" because of the funny JS scope. Douglas Crockford recommends to bypass this limitation using a conventional local variable named "that". So it becomes
```
function MyObject() {
var that = this;
this.myMethod = function() {
jQuery.doSomethingCrazy(that.callbackMethod);
};
};
```
## Do not rely on automatic end of line
JS tries to automatically add `;` at the end of the line if you forget it. Don't rely on this behavior, as you'll get errors that are a mess to debug. | Object Oriented Javascript best practices? | [
"",
"javascript",
"oop",
""
] |
In particular, is there a standard `Exception` subclass used in these circumstances? | From the Java documentation:
> Thrown to indicate that the requested operation is not supported.
>
> ― [java.lang.UnsupportedOperationException](http://java.sun.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html)
Example usage:
```
throw new UnsupportedOperationException("Feature incomplete. Contact assistance.");
``` | Differentiate between the two cases you named:
* To indicate that the requested operation is not supported and most likely never will, throw an [`UnsupportedOperationException`](http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html).
* To indicate the requested operation has not been implemented yet, choose between this:
1. Use the [`NotImplementedException`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/NotImplementedException.html) from [apache commons-lang](http://commons.apache.org/proper/commons-lang/) which was available in commons-lang2 and has been re-added to commons-lang3 in version 3.2.
2. Implement your own `NotImplementedException`.
3. Throw an [`UnsupportedOperationException`](http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) with a message like "Not implemented, yet". | What is the standard exception to throw in Java for not supported/implemented operations? | [
"",
"java",
""
] |
I have two classes, one for articles and another for the cart. The cart consists of an object-array, which contains `article` objects.
I need to sum up the prices of the articles with a foreach-loop within the constructor. When I write the method (that is probably wrong) within the constructor than its type is not accepted as double. How can I sum up fields of objects within an object-array and how do I do this inside a constructor (<- this looks like a bad design decision, but it is part of may class work).
Here are my classes:
```
package org.teubler.sucks.aufgaben;
public class Artikel {
public enum Warengruppe{
A, B, C, S
}
String name;
double verkaufspreis;
Warengruppe Art;
Artikel(String name, double preis){
this.name = name;
this.verkaufspreis = preis;
this.Art = Warengruppe.S;
}
public double getVerkaufspreis() {
return verkaufspreis;
}
public void setWarengruppe(Warengruppe Art) {
switch(Art){
case A:Art = Warengruppe.A;
case B:Art = Warengruppe.B;
case C:Art = Warengruppe.C;
default: Art = Warengruppe.S;
}
}
}
```
second class
```
package org.teubler.sucks.aufgaben;
import java.util.Random;
public class Warenkorb {
String kunde;
Artikel artikelliste[];
int sessionid;
Random s = new Random();
Warenkorb(String kunde, Artikel[] artikel){
this.kunde = kunde;
this.artikelliste = artikel;
this.sessionid = s.nextInt();
public double gesamtpreis(){
double summe = 0;
for(Artikel preis : artikel){
summe += artikel.getVerkaufspreis();
}
return summe;
}
}
}
``` | You're trying to create an extra *method* within the constructor. That's not a good idea. You're also trying to index an array by an object, which won't work. Finally, you're trying to call `getVerkaufspreis()` on an `Object`, instead of a strongly-typed `Artikel`. Try this:
```
Warenkorb(String kunde, Artikel[] artikel){
this.kunde = kunde;
this.artikelliste = artikel;
this.sessionid = s.nextInt();
double summe = 0;
for (Artikel preis : artikel) {
summe += preis.getVerkaufspreis();
}
}
```
Now by the end of the loop you'll have the sum - but what do you want to do with it? I suspect you want to create a field for it...
If you absolutely *have* to use an `Object[]` instead of an `Artikel[]` then you should cast on each iteration:
```
Warenkorb(String kunde, Object[] artikel){
this.kunde = kunde;
this.artikelliste = artikel;
this.sessionid = s.nextInt();
double summe = 0;
for (Object preis : artikel) {
summe += ((Artikel)preis).getVerkaufspreis();
}
}
``` | First, you should have an array of `Artikel`, not `Object`. You can't do much with `Objects`.
Assuming you change `artekelliste` to `Artikel[]`, the summation would go like this:
```
for(Artikel preis : artikelliste){
summe += artikel.getVerkaufspreis();
}
```
When you use an enhanced-for loop, there is no need for explicit array indexing.
Also, you can't put a method inside a constructor. You need to pull `gesamtpreis()` out of the constructor, like this:
```
Warenkorb(String kunde, Artikel[] artikel){
this.kunde = kunde;
this.artikelliste = artikel;
this.sessionid = s.nextInt();
}
public double gesamtpreis(){
double summe = 0;
for(Artikel preis : artikelliste){
summe += artikel.getVerkaufspreis();
}
return summe;
}
```
As a side note, you can never use an `Object` as an array index; the equivalent standard-for loop would be
```
for(int i = 0; i < artikelliste.length; i++) {
summe += artikelliste[i].getVerkaufspreis();
}
``` | Sum of fields of objects in objectarray, all within the constructor? | [
"",
"java",
"arrays",
"sum",
""
] |
I am not totally new to PHP or XML but I am 100% new to paring XML with PHP. I have an XML string that has several nodes but the only ones I am insterested in are the < keyword > nodes which there are an uncertain number of each containing a phrase like so: < keyword >blue diamond jewelry< /keyword > for example say the string looked like this:
```
<xml>
<pointless_node/>
<seq>
<keyword>diamond ring</keyword>
<keyword>ruby necklace</keyword>
<keyword>mens watch</keyword>
</seq>
<some_node/>
</xml>
```
I would want an array like this:
```
['diamond ring','ruby necklace','mens watch']
```
I tried looking at the PHP manual and just get confused and not sure what to do. Can someone please walk me through how to do this? I am using PHP4.
THANKS! | > This turns $keywords into an array of
> Objects. Is there a way to get the
> text from the objects?
Sure, see this.
```
$dom = domxml_open_mem($str);
$keywords = $dom->get_elements_by_tagname('keyword');
foreach($keywords as $keyword) {
$text = $keyword->get_content();
// Whatever
}
``` | see: <http://www.php.net/simplexml-element-xpath>
Try the following xpath and array construction
```
$string = "<xml>
<pointless_node/>
<seq>
<keyword>diamond ring</keyword>
<keyword>ruby necklace</keyword>
<keyword>mens watch</keyword>
</seq>
<some_node/>
</xml>";
$xml = domxml_open_mem($xmlstr)
$xpath = $xml->xpath_new_context();
$result = xpath_eval($xpath,'//keyword');
foreach ($result->nodeset as $node)
{
$result[] = $node->dump_node($node);
}
```
edit: modified code to reflect php 4 requirements
edit: modified to account for poorly documented behaviour of xpath\_new\_context (php docs comments point out the error) | PHP: Get array of text from perticular XML node type? | [
"",
"php",
"xml",
"php4",
""
] |
The Development version of Django has aggregate functions like Avg, Count, Max, Min, StdDev, Sum, and Variance ([link text](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id8)). Is there a reason Median is missing from the list?
Implementing one seems like it would be easy. Am I missing something? How much are the aggregate functions doing behind the scenes? | Because median isn't a SQL aggregate. See, for example, the [list of PostgreSQL aggregate functions](http://www.postgresql.org/docs/8.3/static/functions-aggregate.html) and [the list of MySQL aggregate functions](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html). | Here's your missing function. Pass it a queryset and the name of the column that you want to find the median for:
```
def median_value(queryset, term):
count = queryset.count()
return queryset.values_list(term, flat=True).order_by(term)[int(round(count/2))]
```
That wasn't as hard as some of the other responses seem to indicate. The important thing is to let the db sorting do all of the work, so if you have the column already indexed, this is a super cheap operation.
*(update 1/28/2016)*
If you want to be more strict about the definition of median for an even number of items, this will average together the value of the two middle values.
```
def median_value(queryset, term):
count = queryset.count()
values = queryset.values_list(term, flat=True).order_by(term)
if count % 2 == 1:
return values[int(round(count/2))]
else:
return sum(values[count/2-1:count/2+1])/Decimal(2.0)
``` | Missing 'Median' Aggregate Function in Django? | [
"",
"python",
"django",
"aggregate-functions",
""
] |
I am looking to do something like this:
1. access records in db with a datareader. I won't know how many records will come back - somewhere between 1 and 300 most of the time. The data will look something like this "0023","Eric","Harvest Circle", "Boston" for each record.
2. I wanted to immediately populate something (array, list?) and close the connection.
3. Pass the filled object back to my webservice where I will convert it to JSON before sending on to client.
The problem I am running into is what object/objects to populate with data from the datareader. I started out using an ArrayList (and have now read about using List instead), but although I could get back all the records (in this case just 2 Items), I could not access the individual fields inside each Item (Eric, Boston, etc).
Enter Plan B: foreach record in datareader, add the individual column values to an array and then add each array to the List. I think this will work, but I am not sure how to instantiate an array when I don't know how many would need to be instantiated. In other words, I would normally do this string[] myarray = new string[]{"eric", "boston", "etc"};
But if I have multiple records, what does that look like? Populate array, add to List, clear original array and then repopulate it, add it to List, etc?
Any help would be greatly appreciated! Also, I am very open to alternative ways of doing this.
Thanks! | The standard answer here, short of using a persistence layer like the Entity Framework, is to create "entity" classes with the fields you need. Something like:
```
class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
```
... and then collect these up in a collection of some kind. A `List<Customer>` is fine.
```
List<Customer> customers = new List<Customer>();
string connectionString = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("GetData");
using (IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Customer c = new Customer();
c.Id = (int)reader["ID"];
c.FirstName = (string)reader["FirstName"];
c.LastName = (string)reader["LastName"];
customers.Add(c);
}
}
}
```
If you have a large number of tables, or a mutable list of fields, this can get hard to maintain. For simple tasks, though, this works fine. | Odds are you don't need a concrete class like a `List` or array. An `IEnumerable` is probably good enough. With that in mind, this is my favorite pattern:
```
public IEnumerable<IDataRecord> GetData()
{
using (var cn = getOpenConnection(connectionString))
using (var cmd = new SqlCommand("GetData", cn))
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
```
You could also modify that to create strongly-typed business objects, but I generally keep that in a separate layer/tier. Iterator blocks will do lazy evaluation/deferred execution and so the extra translation tier will *not* require an additional iteration of the results.
There is one trick with this code. You need to be sure you copy the data in each record to a real object at some point. You can't bind directly to it, or you'll get potentially-surprising results. One variation I use more often is to make the method generic and require a `Func<IDataRecord, T>` argument to translate each record as it is read. | looking for suggesions re: accessing data and populating List/arraylist/list | [
"",
"c#",
"arrays",
"list",
"sqldatareader",
""
] |
I'm looking Ruby on Rails and PHP hosting service(shared space or a dedicated server).
I would like to see two options first before buying one of them:
1. PHP and can upgrade to Ruby on Rails later with additional cost
2. Ruby on Rails and PHP
I've looked at [Dreamhost](http://dreamhost.com/), [Bluehost](http://www.bluehost.com/) and [RailsPlayground](http://railsplayground.com/) and all of them seem to have pros and cons. Does anyone have experience with either? Does anyone have a different recommendation? | See my comments here:
<https://stackoverflow.com/questions/162144/what-is-a-good-ruby-on-rails-hosting-service/162213#162213>
Dreamhost is a great option. You can run both PHP and Rails and with Private Server option you can move sites that need more resources to a more dedicated platform. | I have dreamhost, while it's cheap and offers a lot of space, it's speed can vary greatly. They have decent PHP support (file\_get\_contents() is disabled, among other various things). Their Rails support is okay, they offer Phusion Passenger(<http://www.modrails.com/>) to host your Rails apps. | What is a good Ruby on Rails and PHP hosting? | [
"",
"php",
"ruby-on-rails",
"hosting",
""
] |
My question actually comes in two parts hence the ambiguous title.
**Part One**
As far as I'm aware, you should never swallow an exception. Not even logging it and forgetting about. In general cases, I try to solve an exception and retry the code - for example, let's say I get a FileNotFound exception.
I prompt the user to check the file exists and try again, offering another file chooser dialog and hoping for the best. Failing attempting to solve the problem I end up notifying the user and logging the exception. I've been told that this isn't the correct thing to do in a catch block, so am I doing it right by attempting to solve the issue?
I can't think what else I should do. I suspect I'm being fed misinformation - I'm a gullable soul.
**Part Two**
Creating a log in my program directory to log an exception is fine I think, but again I'm being told that exceptions should be written to the windows eventlog. Is this correct? Under what circumstances should you write to the event log?
Silly questions need silly answers.
Edit:
There is no context to this question other than a general vague domain. My friend and I were blabbering about the right things to do in particular circumstances. | First off if you ever hear the word **Never** your ears should perk up... That is why they are called "Best Practices" and not "Rules written in Stone that you must follow..."
here is Microsoft's [Exception Handling Best Practices Guide](http://msdn.microsoft.com/en-us/library/seyhszts(VS.71).aspx)
And there are going to be plenty others...
It really boils down to you as a developer, your teams standards, your customer, etc. What do you want the application to do?
**Question 1:** Do you want the application to be able to continue on if an exception it thrown? Then I would "swallow" the exception.
**Question 2**: Is there a benefit to logging a particular exception to the event log or is it just going to bloat it with useless information, You may want to write every exception to the log during development and testing and have verbose information and then in production streamline it... I hope I have answered your question even though there really isn't an generic one...
I would say you should have some general guidelines and then if you have more **specific situations** then it would be a good time to re-post to this site and get some feedback from people that have tried different routes and can speak to the pros and cons. | The [Code Analysis Team Blog](http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx) is a great place to start on this topic. Also look at
[Martin Fowler - Fail Fast](http://www.martinfowler.com/ieeeSoftware/failFast.pdf)
[MSDN on Exception Handling](http://msdn.microsoft.com/en-us/library/ms229005.aspx)
[Checked vs Unchecked Exceptions](http://www.javapractices.com/topic/TopicAction.do?Id=129)
The second part of your question really depends. In many applications where you need central exception reporting, writing to the event log is a good idea. There are plenty of other cases where it would be a waste of time to do that, you'll have to use your own judgment on that. | All About Exceptions: What to do and Where to log? | [
"",
"c#",
"design-patterns",
"exception",
""
] |
How does one set the color of text in a Java Swing textbox at run-time? At startup, the color is grayish and when the user enters the textbox, I wish to change the color to the normal text color. I am currently using the following code:
```
private void txtScheduleInfoFocusGained(java.awt.event.FocusEvent evt)
{
try
{
if (currentClassIsNewClass() && txtScheduleInfo.getDocument().getText(0, txtScheduleInfo.getDocument().getLength()).equals(PASTE_SI_HERE))
{
txtScheduleInfo.setText("");
txtScheduleInfo.setForeground(java.awt.SystemColor.textText);
}
}
catch (BadLocationException ex)
{
JOptionPane.showMessageDialog(this, "BLE\nContact Zian", "Unexpected Problem", JOptionPane.ERROR_MESSAGE);
}
}
```
At this time, when the code runs, the text still shows up in gray.
Additional Code:
Declaration (as a field):
```
private javax.swing.JTextPane txtScheduleInfo;
```
Instantiation:
```
txtScheduleInfo = new javax.swing.JTextPane();
```
Initialization:
```
txtScheduleInfo.setForeground(java.awt.SystemColor.textInactiveText);
txtScheduleInfo.setText("Paste schedule information here");
txtScheduleInfo.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
txtScheduleInfoFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
txtScheduleInfoFocusLost(evt);
}
});
``` | try this instead
```
private void txtScheduleInfoFocusGained(java.awt.event.FocusEvent evt)
{
try
{
if (currentClassIsNewClass() && txtScheduleInfo.getDocument().getText(0, txtScheduleInfo.getDocument().getLength()).equals(PASTE_SI_HERE))
{
txtScheduleInfo.setForeground(java.awt.SystemColor.textText);
txtScheduleInfo.setText("");
}
}
catch (BadLocationException ex)
{
JOptionPane.showMessageDialog(this, "BLE\nContact Zian", "Unexpected Problem", JOptionPane.ERROR_MESSAGE);
}
}
```
(The only change is swapping the order. Now you're setting the foreground colour before clearing the text.) | Did you make sure the JTextBox is enabled? You can call `setEnabled(true)` on it to make sure. Not trying to be rude, that's just the most likely cause (there's code in Swing to force graying-out of disabled components).
If that doesn't fix it, you can also trigger a repaint by calling txtScheduleInfo.repaint(), which might cause it to repaint.
If neither of these things helps, you could post some code so we can see what's going on. | Set the text color in a Java textbox | [
"",
"java",
"swing",
"textbox",
"colors",
""
] |
I am a C++ programmer and recently joined a new company that uses a lot of C. When they reviewed my code, they were thinking I over-designed some of the things which I totally disagreed. The company is doing everything in embedded system, so my code needs to be memory
efficient, but the stuff I am doing is not CPU intensive. I would like to know how you guys think what my design. Here is the list.
1. I have some arrays that need to pass around and eventually need to pass to some C code. I could pass a pointer and a size all over of the place. But I chose to create a class that represents this -- a class that has a fixed size (we know the maximum size) buffer, and a length which should be always <= the size of the buffer, otherwise assert. In this way, I can pass the array around with only one variable instead of two, and if the maximum size changes in the future, I should be able to change it easily. I don't use dynamic allocation for the array because it is embedded system and memory allocation could potentially fail and we don't use exception. The class is probably less than 30 lines code, and I use it for quite a few places. They said I over-designed it.
2. They have their own containers implementation in C. I needed to use one of them, but I wanted to hide all the detailed code away from my main logic, so I created a wrapper class
for it. The wrapper class is similar to stl, so I have iterators and it manages the memory
allocation internally, but unlike stl, it returns a error code when it can't allocate more
memory. Their argument on this one is that I am the only one uses it, so they don't want it to be in the repository. I found it stupid to be honest.
EDIT: The following class is more or less that I used for point 1. All I wanted to do is to have something to pass around without carrying the length all the time.
```
class A
{
static const MAX_SIZE = 20;
int m_Array[MAX_SIZE];
size_t m_Len;
public:
A(const int* array, size_t len)
{
assert(len <= MAX_SIZE);
memcpy(m_Array, array, len);
m_Len = len;
}
size_t GetLen() const { return m_Len; }
const int* GetArray() const { return m_Array; }
};
``` | You're probably right, but on the other hand if everyone in the company decided that they don't like the existing APIs, and each designed their own shims and helper functions, that only they used, then maintenance would be tricky.
If your array wrapper is "over-designed", then I'd question whether the code reviewer considers *any* amount of design to be acceptable. It looks harmless to me[\*]. I suppose you could have just made it a struct with two public members, and lose the benefit of read-onliness. How keen are your colleagues on const-correctness in general?
I think the goal for 2 should be to reach consensus on whether that C API should be used directly from C++, or wrapped. If it should be wrapped (and the arguments for that are probably quite strong, what with namespacing and RAII), design a wrapper that everyone will use, and designate it "the C++ API for this module" rather than "a C++ wrapper that one module uses for this other module".
It's possible that everyone else genuinely prefers the API as it is, over a more OO API or using STL. Following their conventions will make it easiest for them to maintain your code, as long as their conventions are solid C programming style. C++ is a multi-paradigm language, and "C with a limited number of bells and whistles" isn't the paradigm you're used to. But it is a valid paradigm, and if it's what the existing codebase uses then you have to question whether what your company needs right now is a one-man revolution, however enlightened.
[\*] (the API, that is. They might question whether it will be passed by value inappropriately, and whether it's wise for every instance to have to be as big as the biggest. That's all for you to argue out with the reviewer, but is nothing to do with "over-design". | First things first: You joined a new company, so you can expect that you need to learn to play by their rules. You're still "the new guy" and there will be some resistance to "your way" of doing things, even if it is better. Get used to them and slowly integrate yourself and your ideas.
As to #1, passing a pointer+size is certainly a pain for the programmer, but it's the most memory-efficient way of doing things. Your class is not "over"-designed, but what happens if MAXSIZE becomes really large at some point in the future? All of your instances will take that much space each, even when they don't need to. You could wind up running out of space simply because the MAXSIZE changed, even if nothing needed that much space.
As to #2, it's a tossup on whether it's an unnecessary layer (perhaps it would be better suited to improve their wrapper instead of simply wrapping it again?), but this will come down to how well you integrate with them and make suggestions.
In summary, I wouldn't call it "overdesigned", but in an embedded situation you need to be very wary of generalizing code to save yourself effort vs saving memory.. | When I created my helper classes, am I over designing? | [
"",
"c++",
"c",
""
] |
Bashing our heads against the wall here
We are an ISV and have hundreds of companies using our software with no problems. The software is Winforms/C# on .NET 2.0.
One of our clients has installed our software and it crashes on startup on all of their machines, apart from on one guy's laptop where it works fine.
On calling OdbcConnection.Open(), we get the following exception:
```
The type initializer for 'System.Transactions.Diagnostics.DiagnosticTrace' threw an exception.
at System.Transactions.Diagnostics.DiagnosticTrace.get_Verbose()
at System.Transactions.Transaction.get_Current()
at System.Data.Common.ADP.IsSysTxEqualSysEsTransaction()
at System.Data.Common.ADP.NeedManualEnlistment()
at System.Data.Odbc.OdbcConnection.Open()
at OurCompany.OurForm.connectionTestWorker_DoWork(Object sender)
```
This has an InnerException:
```
Configuration system failed to initialize
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
```
Google just says "app.config is syntactically incorrect, rebuild it" yet the same app.config works fine on hundreds of other machines.
Here's app.config, as requested:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="OurApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.diagnostics>
</system.diagnostics>
<applicationSettings>
<OurApp.Properties.Settings>
<setting name="OurApp_WebServices_OurServiceName" serializeAs="String">
<value>http://ourdomain.com/OurService.asmx</value>
</setting>
</OurApp.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="WorkflowEngine" value="old" />
<add key="ProductID" value="3" />
<add key="EnableMigrationWizard" value="false" />
<add key="UseAlternativeFtpPort" value="true" />
<add key="FeedbackWhileConnecting" value="true" />
</appSettings>
</configuration>
```
A repair of the .NET Framework hasn't fixed this. I'm at a total loss. Any ideas? | Solved this by overwriting machine.config with a known working copy from another machine at the same SP/patch level. | Check machine.config and user.config. Along with app.config, those are the [3 that make up the config sections](http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx).
Reflector shows `EnsureInit` has 2 exception paths:
```
catch (Exception exception) {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"), exception);
throw this._initError;
} catch {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"));
throw this._initError;
}
```
Since the 2nd would only handle a [non-CLS exception](http://msdn.microsoft.com/en-us/library/ms404228.aspx), I'd guess that you're hitting the first one. If that's the case, you probably need to recursively go through InnerException to get the full details. | Strange exception coming out of OdbcConnection.Open() | [
"",
"c#",
".net",
"winforms",
"exception",
""
] |
I'm trying to access a config file from a a servlet inside of .war-file. The problem is, that the default file path is the tomcat root itself and hardcoding the path to the file seems not like an option either. Is it possible to get any information through the ServletContext or any Tomcat variables? | If you put the file in the 'classes' directory under your specific webapps directory (./webapps/{servlet}/classes) then you can access it from inside a Java class by doing this :
```
Class.getResourceAsStream(<filename>);
```
so if you had a conf file at /webapps/myServlet/classes/conf.xml
```
Class.getResourceAsStream("conf.xml");
``` | Gandalf has provided the "correct" answer. You can safely use this anywhere. It's all you need.
Just a caution. Some people assume that because there are ways to READ data from inside a WAR, that that means it's also OK to WRITE data inside a WAR. In the literal sense, sometimes that's true. But not always. And it's almost NEVER safe.
I mention this because I inherited an webapp that did exactly that. Stored a whole directory tree of files inside an exploded WAR directory. First software upgrade that came along, "Poof!" all those carefully uploaded data files were gone.
So treat WARs as read-only. If you need to write, designate a directory OUTSIDE the appserver. Preferably as a configurable parameter in your web.xml file so you can use JNDI to look it up and you can override it for testing purposes without having to modify source code. | How can I access a config file from a servlet deployed as a .war-file and running in Tomcat 5.5? | [
"",
"java",
"tomcat",
""
] |
In C#, which one is faster?
* System.Convert.ToString(objThatIsAString)
* (string)objThatIsAString
* objThatIsAString.ToString() | The direct cast doesn't have to do any checking except a runtime type check - I would *expect* that the cast is quicker.
You might also want to consider `objThatIsString.ToString()`; since (for `string`) this is just `return this;`, it should be quick - certainly quicker than the `Convert.ToString`. Then the race is between a runtime type-check and a virtual call; in reality, both are very, very quick. | @thijs:
Here's a quick test:
```
public class ToStringTest
{
private object mString = "hello world!";
Stopwatch sw = new Stopwatch();
private List<long> ConvertToStringTimes = new List<long>();
private List<long> ToStringTimes = new List<long>();
private List<long> CastToStringTimes = new List<long>();
public ToStringTest()
{
for (int i = 0; i < 100000; i++)
{
sw.Start();
ConvertToString();
sw.Stop();
ConvertToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
sw.Start();
ToString();
sw.Stop();
ToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
sw.Start();
CastToString();
sw.Stop();
CastToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Average elapsed ticks after converting {0} strings",ConvertToStringTimes.Count);
Console.WriteLine("ConvertToString: {0} ticks", ConvertToStringTimes.Average() );
Console.WriteLine("ToString: {0} ticks", ToStringTimes.Average());
Console.WriteLine("CastToString: {0} ticks", CastToStringTimes.Average());
}
private string ConvertToString()
{
return Convert.ToString(mString);
}
public override string ToString()
{
return mString.ToString();
}
public string CastToString()
{
return (string) mString;
}
}
```
Results in:
Average elapsed ticks after converting 100000 strings
ConvertToString: 611.97372 ticks
ToString: 586.51461 ticks
CastToString: 582.25266 ticks | In C#, which one is faster — Convert.ToString(), (string)casting or .ToString()? | [
"",
"c#",
"string",
"casting",
"converters",
"tostring",
""
] |
I'm working on some old AJAX code, written in the dark dark days before jQuery. Strangely, it has been working fine for years, until today when it suddenly stopped firing its callback. Here's the basic code:
```
var xml = new XMLHttpRequest(); // only needs to support Firefox
xml.open("GET", myRequestURL, true);
xml.onreadystatechange = function() { alert ('test'); };
xml.send(null);
```
Checking the Firebug console, the request is being sent with no worries, and it is receiving the correct XML from the request URL, but the `onreadystatechange` function is not working at all. There's no javascript errors or anything else strange happening in the system.
I wish I could just rewrite everything using jQuery, but I don't have the time right now. What could possibly be causing this problem??
---
A further update - I've been able to test my code in a different browser (FFx 3.0) and it was working there, so it must be a problem with my browser. I'm running Firefox 3.5b4 on Vista, and I've tried it now with all my addons disabled with no luck. It's still really bugging me because I was working on this site yesterday (with the same browser setup) and there were no problems at all...
Actually I just took a look back in my Addons window and saw that Firebug was still enabled. If I disable Firebug, it works perfectly. If I enable it, it's broken. Firebug version 1.40.a31 | is the url malformed?
have you tried putting the whole thing in a try-catch and alerting the errors (if any)
is it failing on an authorization check?
does the url in question require http-auth? (though there should be state changes in this case, I'll admit)
edit:
I have a really funny thought here. Are you using firefox 3.5 beta4? I develop a firefox extension for a browser-based game and recently discovered some odd behvaviour. With my extension or firebug observing the ajax requests made from the page, the script ccreating them would never get calledback. The request would be correctly observed and processed by both firebug and my extension (I could observe what was sent and received)... but the page itself would never hear from the request again -- like it had disappeared into a black hole.
Try turning off firebug (or at least turn off listening to 'Net' for that domain) and test it again | Known Firefox bug affecting Firebug; see <http://code.google.com/p/fbug/issues/detail?id=1569&q=xhr&colspec=ID%20Type%20Status%20Owner%20Test%20Summary> for details :-) | What might cause an XMLHttpRequest to never change state in Firefox? | [
"",
"javascript",
"ajax",
""
] |
What is the difference between `__method__`, `method` and `_method__`?
Is there any or for some random reason people thought that `__doc__` should be right like that instead of `doc`. What makes a method more special than the other? | * `__method`: private method.
* `__method__`: special Python method. They are named like this to prevent name collisions. [Check this page for a list of these special methods.](http://www.python.org/doc/2.5.2/ref/specialnames.html)
* `_method`: This is the recommended naming convention for protected methods in the [Python style guide](http://www.python.org/dev/peps/pep-0008/).
From the style guide:
> * `_single_leading_underscore`: weak "internal use" indicator. E.g. `from M
> import *` does not import objects whose name starts with an underscore.
> * `single_trailing_underscore_`: used by convention to avoid conflicts with
> Python keyword, e.g.
>
> ```
> Tkinter.Toplevel(master, class_='ClassName')
> ```
> * `__double_leading_underscore`: when naming a class attribute, invokes name
> mangling (inside class `FooBar`, \_\_boo becomes `_FooBar__boo`; see below).
> * `__double_leading_and_trailing_underscore__`: "magic" objects or
> attributes that live in user-controlled namespaces. E.g. `__init__`,
> `__import__` or `__file__`. Never invent such names; only use them
> as documented. | * `method` is just a normal method
* `_method` should not be called unless you know what you are doing, which normally means that you have written the method yourself.
* `__method` the 2 underscores are used to prevent name mangeling. Attributes or methods like this are accessible over `instance._ClassName__method`. Although a lot of people call this "private" it is *not*. You should never use this to prevent someone from accessing this method, use `_method` instead.
* `__method__` is used for special methods which modify the behavior of the instance. Do not name your own methods like this. | Difference between "__method__" and "method" | [
"",
"python",
"methods",
""
] |
I have one HTML <form>.
The form has only one `action=""` attribute.
However I wish to have two different `target=""` attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target? | It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
```
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
```
With this javascript:
```
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
```
Approaches that bind code to the submit button's click event will not work on IE. | **Update 2015:**
This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
**Update 2023:**
I would definitely be writing a lot of logic in the front end Javascript code and would be using the Fetch API these days.
*Original answer follows:*
---
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
```
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
```
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable `retry` exists and has a value then retry was pressed, and if the variable `abort` exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript. | HTML form with two submit buttons and two "target" attributes | [
"",
"javascript",
"html",
"forms",
"submit",
""
] |
I'd like to know what can be done in a browser UI (using a browser+CSS+javascript, not using Flash or Silverlight). For example, I think it's possible to:
* Drag and drop
* Arrange list items horizontally, and make them behave like menu items
* Make things on page visible or invisible, depending on where the mouse is hovering
I admit this is a broad question, but that's what I'm looking for: an overview of available UI techniques (preferably with, also, at least a little clue or hyperlink as to how to implement each one).
Do you know of such a list or dictionary?
I'm especially interested in any techniques for interaction and user input (i.e. not simply page layout and navigation where the end-user is only consuming information).
---
**Edit:** people answered that I should look to see what functionality is implemented in various 'JavaScript UI toolkits'. FWIW, the following are my brief review/summary after looking at some of the suggestions.
* <http://demos.mootools.net/> -- implements a small (not wide) variety of UI features
* <http://ajaxian.com/by/topic/ui> -- not an organized or coherent reference, more like a blog that reviews various things.
* <http://jqueryui.com/demos/> -- concise, organized introduction to a dozen interactions and/or widgets
* <http://plugins.jquery.com/> -- a library of a couple of thousand 'plug-ins' in 20 categories ... vaster and not so immediately understandable nor so consistently documented as the jqueryui demos
* <http://www.dojotoolkit.org/> -- takes a bit of navigating ... the easiest introduction to all functionality might be <http://dojocampus.org/explorer/>
* <http://script.aculo.us/> -- not very big
* <http://extjs.com/> -- quite a variety of powerful features, with a good set of demos at <http://extjs.com/deploy/dev/examples/samples.html>
* <http://mochikit.com/> -- this is another small library
* <http://developer.yahoo.com/yui/> -- includes about 20 widget classes, thorough documentation (each class description includes a link to demos), and special mention for having "Layout Manager" and "CSS Reset".
* <http://www.midorijs.com/> -- quite small and simple, no demos
To summarize, I think the best answers (i.e. the easiest-to-browse collections of the most functionality) are:
* <http://extjs.com/deploy/dev/examples/samples.html>
* <http://dojocampus.org/explorer/>
* <http://developer.yahoo.com/yui/examples/> | Try any of these javascript libraries:
* <http://www.dojotoolkit.org/>
* <http://mootools.net/>
* <http://jquery.com/>
* <http://script.aculo.us/>
* <http://extjs.com/>
* <http://mochikit.com/>
* <http://developer.yahoo.com/yui/>
* <http://www.midorijs.com/>
If you accept the [HTML Canvas](http://en.wikipedia.org/wiki/Canvas_(HTML_element)) as valid HTML (Microsoft doesn't), you can do even more (requires Canvas support in your browser):
* <https://developer.mozilla.org/en/Canvas_tutorial>
* <http://www.blobsallad.se/>
* <http://www.benjoffe.com/code/demos/canvascape/> - 3rd person shooter | A [very](http://maettig.com/code/javascript/3d_dots.html) [great](http://www.kawa.net/works/js/animation/cube-e.html) [many](http://www.javascriptgaming.com/search/label/DHTML?Tech&max-results=10) [things](http://www.noupe.com/javascript/10-smart-javascript-techniques-for-manipulating-content.html) [can](http://demos.mootools.net/) [be](http://devsnippets.com/article/ajax/7-free-powerful-file-managers.html) [done](http://ajaxpatterns.org/Javascript_Effects_Frameworks) in JS. | List of in-browser UI techniques? | [
"",
"javascript",
"css",
"dom",
"user-interface",
""
] |
I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python? | You have two main options, install the python 2.3 from [macports](http://www.macports.org/) (easy) or install from source.
For macports, run `port install python23`
For the 2nd, you'll have to go to <http://www.python.org/download/releases/2.3.7/> to download the source tarball. Once you have that open a terminal and run `./configure --prefix /home/(your homedir)/software MACOSX_DEPLOYMENT_TARGET=10.5` then `make` and `make install`. This should place a separate install in the software directory that you can access directly. | One alternative is to use a virtual machine.
With something like VMWare Fusion or Virtualbox you could install a complete Linux system with Python2.3, and do your testing there. The advantage is that it would be completely sand-boxed, so wouldn't affect your main system at all. | Install older versions of Python for testing on Mac OS X | [
"",
"python",
"version",
"installation",
""
] |
I created a report as part of a C# application using Reporting Services and I cant find some functionality I am used to seeing in other environments. I believe both MS Access and Crystal reports have an option called "Keep Together" so that you can keep a specific grouping of data on one page instead of the information being split over two pages.
How do I do that using 2005 Reporting Services when my report is rendered locally in a C# app and viewed using the .net report viewer. Essentially, I want to keep all records for a certain year on one page. I am using Visual Studio 2008.
The year is one of the columns and the number of rows for one year is always smaller than a page. My report uses just one table and has an innermost grouping by year and then another outer grouping by client name.
Currently I can fit two years of data on the report, however, if the data starts half way through the first year, then I get the following:
Example:
Page one:
1/2 of 2004 because the data started half way through 04
All of 2005
First half of 2006
Page2:
Second Half of 2006
What I would rather do is push all of 2006 to page two.
I am currently using a table for all of the data in the report. There is a keep together option at the Table level, but I need one at the Group level. In this case the Grouping by year.
Any help that can be provided will be much appreciated. | The problem was that I needed two years on a page and never 1/2 year even if the specific set of records started half way through the year. It turns out that even though there is a "Keep Together" option at the table level, there is not one at the group level. I needed this option at a group level. Instead of using a format solution I altered the underlying SQL for the report. In cases where there was only 1/2 year of data I created records for the other part of the year with correct dates, but zeros for all other values. This means that if the page is formatted properly to hold two years then it will always show two complete years and one year will never be broken over two pages. I also thought the answers provided by Mozy and John Sansom were good and I voted them both up.
Thanks for the help! | 1. Insert a "List" into the report.
2. Under its "Tablix Properties" set the "Dataset Name" property to your dataset name.
3. From the design view right-click on the list and then select "Row Group > Group Properties".
4. On the "Group Properties" window, click "Add" button under "Group Expressions" then choose the field that you want to group within a page.
5. After that you can insert a "Table" for your detail data inside the row group.
6. Once you render the report the report will keep data inside the group together between page breaks. | Keep Group on One Page using Reporting Services | [
"",
"c#",
".net",
"sql-server",
"reporting-services",
""
] |
In the past, I used WAMPserver on windows to parse PHP for me. This is a pre-configured package, focussed on working with MySQL.
When I tried to run PostgreSQL, I got error messages that said that my version of PHP wasn't compiled to work with PostgreSQL.
So, I've recently uninstalled WAMP and every associated with it. I've downloaded Apache 2.2.11 with openSSL, installed as admin(you know, run the command prompt as administrator, cd to the directory where the download was done and have it executed, so the install was done as admin).
That's that. I now have Apache installed, "it works" shows up, so I'm that far.
Now I'm wondering, do I download the exe and install, or the zip, or something else.
What is the best thing to do to make sure that the PHP on my system can handle everything I can ever throw at it?
Also, PHP first, or MySQL/Postgre first.
And lastly, what about PEAR? I need PEAR installed, which isn't standard on Windows. I'm guessing the pear.bat file in the PHP downloads will do that for me?
EDIT: I see one close vote, yet no comment as to why. It makes me wonder how people who are so lazy and rude got to have somany points. | I would recommend downloading the zip package, as configuring php is not really that difficult, and it allows you to add features as needed.
As for whether first to install php or MySQL/PostgreSQL, - it does not really matter. You can install them in any order.
Your guess regarding PEAR is quite correct | i haven't used wamp before, so i can't comment on that
i do however use xampp which sounds very similar
in xampp if i want to enable postgres support i edit the php.ini file and uncomment the postgres section of the ini file, same with any of the extensions that i need
perhaps this might be an alternative you can try if you get stuck | Best PHP download to keep all my options open? | [
"",
"php",
"windows-vista",
"installation",
"development-environment",
""
] |
This might be stupid, but I'm want to know if it's possible, lets start with 5x5 a matrix
```
int[][] x = new int[5][5];
Random rg = new Random();
```
now let's fill it with Pseudo Random information
```
for(int i=0;i<5;i++){
for(int j =0; j<5;j++){
x[i][j] = rg.nextInt();
}
}
```
but how can I do this right with one Single for?
```
for(int i=0, j=0; i<5; (j==5?i++, j=0:j++){
x[i][j] = rg.nextInt();
}
```
this is not working :( | You need to compute the row and column from a single index, then:
```
for(int i = 0; i < 5 * 5; i++)
{
int row = i / 5;
int column = i % 5;
x[row][column] = rg.nextInt();
}
```
The use of / and % is classic, here: as you iterate over the indices of the matrix, the division is used to figure out which row you're on. The remainder (%) is then the column.
This gorgeous ASCII art shows how the 1-dimensional indices are located in the 2D matrix:
```
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
```
It should be clear that for any value in the first row, that value divided by 5 is the row index itself, i.e. they're all 0. | You really will not gain anything from doing that. **keep your code readable**. it's actually more intensive to do the multiplications and divisions unwind suggested then to just to a loop. (multiply divide and mod are actually a complex set of instructions in an ALU) | How to combine two FORs into one | [
"",
"java",
""
] |
Many posts around about restoring a WinForm position and size.
Examples:
* [www.stackoverflow.com/questions/92540/save-and-restore-form-position-and-size](http://www.stackoverflow.com/questions/92540/save-and-restore-form-position-and-size)
* [www.codeproject.com/KB/dialog/restoreposition.aspx?fid=1249382&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2595746](http://www.codeproject.com/KB/dialog/restoreposition.aspx?fid=1249382&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2595746)
But I have yet to find code to do this with multiple monitors.
That is, if I close my .NET Winform app with the window on monitor 2, I want it to save the windows size, location, and state to the application settings, so it could later restore to monitor 2 when I restart the app. It would be nice if, like in the codeproject example above, it includes some sanity checks, as in if the saved location is mostly off-screen it "fixes" it. Or if the saved location is on a monitor that is no longer there (e.g. my laptop is now by itself without my second monitor) then it correctly moves it to monitor 1.
Any thoughts?
My environment: C#, .NET 3.5 or below, VS2008 | The answer provided by VVS was a great help! I found two minor issues with it though, so I am reposting the bulk of his code with these revisions:
(1) The very first time the application runs, the form is opened in a Normal state but is sized such that it appears as just a title bar. I added a conditional in the constructor to fix this.
(2) If the application is closed while minimized or maximized the code in OnClosing fails to remember the dimensions of the window in its Normal state. (The 3 lines of code--which I have now commented out--seems reasonable but for some reason just does not work.) Fortunately I had previously solved this problem and have included that code in a new region at the end of the code to track window state as it happens rather than wait for closing.
---
With these two fixes in place, I have tested:
A. closing in normal state--restores to same size/position and state
B. closing in minimized state--restores to normal state with last normal size/position
C. closing in maximized state--restores to maximized state and remembers its last size/position when one later adjusts to normal state.
D. closing on monitor 2--restores to monitor 2.
E. closing on monitor 2 then disconnecting monitor 2--restores to same position on monitor 1
David: your code allowed me to achieve points D and E almost effortlessly--not only did you provide a solution for my question, you provided it in a complete program so I had it up and running almost within seconds of pasting it into Visual Studio. So a big thank you for that!
```
public partial class MainForm : Form
{
bool windowInitialized;
public MainForm()
{
InitializeComponent();
// this is the default
this.WindowState = FormWindowState.Normal;
this.StartPosition = FormStartPosition.WindowsDefaultBounds;
// check if the saved bounds are nonzero and visible on any screen
if (Settings.Default.WindowPosition != Rectangle.Empty &&
IsVisibleOnAnyScreen(Settings.Default.WindowPosition))
{
// first set the bounds
this.StartPosition = FormStartPosition.Manual;
this.DesktopBounds = Settings.Default.WindowPosition;
// afterwards set the window state to the saved value (which could be Maximized)
this.WindowState = Settings.Default.WindowState;
}
else
{
// this resets the upper left corner of the window to windows standards
this.StartPosition = FormStartPosition.WindowsDefaultLocation;
// we can still apply the saved size
// msorens: added gatekeeper, otherwise first time appears as just a title bar!
if (Settings.Default.WindowPosition != Rectangle.Empty)
{
this.Size = Settings.Default.WindowPosition.Size;
}
}
windowInitialized = true;
}
private bool IsVisibleOnAnyScreen(Rectangle rect)
{
foreach (Screen screen in Screen.AllScreens)
{
if (screen.WorkingArea.IntersectsWith(rect))
{
return true;
}
}
return false;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// only save the WindowState if Normal or Maximized
switch (this.WindowState)
{
case FormWindowState.Normal:
case FormWindowState.Maximized:
Settings.Default.WindowState = this.WindowState;
break;
default:
Settings.Default.WindowState = FormWindowState.Normal;
break;
}
# region msorens: this code does *not* handle minimized/maximized window.
// reset window state to normal to get the correct bounds
// also make the form invisible to prevent distracting the user
//this.Visible = false;
//this.WindowState = FormWindowState.Normal;
//Settings.Default.WindowPosition = this.DesktopBounds;
# endregion
Settings.Default.Save();
}
# region window size/position
// msorens: Added region to handle closing when window is minimized or maximized.
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
TrackWindowState();
}
protected override void OnMove(EventArgs e)
{
base.OnMove(e);
TrackWindowState();
}
// On a move or resize in Normal state, record the new values as they occur.
// This solves the problem of closing the app when minimized or maximized.
private void TrackWindowState()
{
// Don't record the window setup, otherwise we lose the persistent values!
if (!windowInitialized) { return; }
if (WindowState == FormWindowState.Normal)
{
Settings.Default.WindowPosition = this.DesktopBounds;
}
}
# endregion window size/position
}
``` | Try this code. Points of interest:
* Checks if the window is (partially) visible on any screen's working area. E.g. dragging it behind the task bar or moving it completely offscreen resets the position to windows default.
* Saves the correct bounds even if the Form is minimized or maximized (common error)
* Saves the WindowState correctly. Saving FormWindowState.Minimized is disabled by design.
The bounds and state are stored in the appsettings with their corresponding type so there's no need to do any string parsing. Let the framework do its serialization magic.
```
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// this is the default
this.WindowState = FormWindowState.Normal;
this.StartPosition = FormStartPosition.WindowsDefaultBounds;
// check if the saved bounds are nonzero and visible on any screen
if (Settings.Default.WindowPosition != Rectangle.Empty &&
IsVisibleOnAnyScreen(Settings.Default.WindowPosition))
{
// first set the bounds
this.StartPosition = FormStartPosition.Manual;
this.DesktopBounds = Settings.Default.WindowPosition;
// afterwards set the window state to the saved value (which could be Maximized)
this.WindowState = Settings.Default.WindowState;
}
else
{
// this resets the upper left corner of the window to windows standards
this.StartPosition = FormStartPosition.WindowsDefaultLocation;
// we can still apply the saved size
this.Size = Settings.Default.WindowPosition.Size;
}
}
private bool IsVisibleOnAnyScreen(Rectangle rect)
{
foreach (Screen screen in Screen.AllScreens)
{
if (screen.WorkingArea.IntersectsWith(rect))
{
return true;
}
}
return false;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// only save the WindowState if Normal or Maximized
switch (this.WindowState)
{
case FormWindowState.Normal:
case FormWindowState.Maximized:
Settings.Default.WindowState = this.WindowState;
break;
default:
Settings.Default.WindowState = FormWindowState.Normal;
break;
}
// reset window state to normal to get the correct bounds
// also make the form invisible to prevent distracting the user
this.Visible = false;
this.WindowState = FormWindowState.Normal;
Settings.Default.WindowPosition = this.DesktopBounds;
Settings.Default.Save();
}
}
```
The settings file for reference:
```
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="ScreenTest" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="WindowPosition" Type="System.Drawing.Rectangle" Scope="User">
<Value Profile="(Default)">0, 0, 0, 0</Value>
</Setting>
<Setting Name="WindowState" Type="System.Windows.Forms.FormWindowState" Scope="User">
<Value Profile="(Default)">Normal</Value>
</Setting>
</Settings>
</SettingsFile>
``` | Restoring Window Size/Position With Multiple Monitors | [
"",
"c#",
"winforms",
"multiple-monitors",
"appsettings",
""
] |
I'm working on a little Java game in which all sorts of events can happen. There are at least a couple of dozen basic events that various event handlers may be interested in. There are also several places in the code where these events might be triggered. Rather than forcing the event listeners to know which class they need to register with, I'd like to create some sort of a centralized message-dispatching system, which some classes would submit events into and interested classes could hook into to listen for certain kinds of events.
But I have some questions. Firstly, this seems like an obvious and common problem. Are there favorite implementations of simple, in-VM messaging systems? Seems like there would be.
Secondly, and more importantly, I'm trying to work out a reasonably elegant way for the dispatching class to know as little as possible about types of messages. I'd love to be able to create new kinds of events without modifying the message dispatcher at all. However, I have an opposite concern. I'd really like for the method signatures of the handling methods to be clear. In other words, I would prefer the following:
```
public class CollisionConsoleHandler implements CollisionListener {
@Override
public void spaceshipCollidedWithMeteor( Spaceship spaceship, Meteor meteor ) {
//...
}
}
```
over something more generic and harder to read:
```
public class CollisionConsoleHandler implements GameMessageListener {
@Override
public void handleMessage( GameMessage message ) {
if( message instanceof SpaceshipCollisionMessage ) {
Spaceship spaceship = ((SpaeshipCollisionMessage)message).getSpaceship();
Meteor meteor = ((SpaeshipCollisionMessage)message).getMeteor();
//...
}
}
}
```
But I don't see any good ways to keep type-specific knowledge out of the dispatcher while at the same time keeping the method signatures clean and readable.
Ideas? | If there is a specific listener interface for each event. Each event is able to issue listeners calls itself. Then, the role of the dispatcher is to identify target listeners and to trigger the event notification on them.
For example, a generic event definition can be:
```
public interface GameEvent<L> {
public void notify( final L listener);
}
```
If your CollisionListener is:
```
public interface CollisionListener {
public void spaceshipCollidedWithMeteor( Spaceship spaceship, Meteor meteor );
}
```
Then, the corresponding event can be:
```
public final class Collision implements GameEvent<CollisionListener> {
private final Spaceship ship;
private final Meteor meteor;
public Collision( final Spaceship aShip, final Meteor aMeteor ) {
this.ship = aShip;
this.meteor = aMeteor;
}
public void notify( final CollisionListener listener) {
listener.spaceshipCollidedWithMeteor( ship, meteor );
}
}
```
You can imagine a dispatcher which is able to propagate this event on the target listeners like in the following scenario (Events is the dispatcher class):
```
// A unique dispatcher
final static Events events = new Events();
// Somewhere, an observer is interested by collision events
CollisionListener observer = ...
events.listen( Collision.class, observer );
// there is some moving parts
Spaceship aShip = ...
Meteor aMeteor = ...
// Later they collide => a collision event is notified trough the dispatcher
events.notify( new Collision( aShip, aMeteor ) );
```
In this scenario, the dispatcher did not require any knowledge on events and listeners. It triggers an individual event notification to each listener, using only the GameEvent interface. Each event/listener pair chooses it's own dialog modalities (they can exchange many messages if they want).
A typical implementation of a such dispatcher should be something like:
```
public final class Events {
/** mapping of class events to active listeners **/
private final HashMap<Class,ArrayList> map = new HashMap<Class,ArrayList >( 10 );
/** Add a listener to an event class **/
public <L> void listen( Class<? extends GameEvent<L>> evtClass, L listener) {
final ArrayList<L> listeners = listenersOf( evtClass );
synchronized( listeners ) {
if ( !listeners.contains( listener ) ) {
listeners.add( listener );
}
}
}
/** Stop sending an event class to a given listener **/
public <L> void mute( Class<? extends GameEvent<L>> evtClass, L listener) {
final ArrayList<L> listeners = listenersOf( evtClass );
synchronized( listeners ) {
listeners.remove( listener );
}
}
/** Gets listeners for a given event class **/
private <L> ArrayList<L> listenersOf(Class<? extends GameEvent<L>> evtClass) {
synchronized ( map ) {
@SuppressWarnings("unchecked")
final ArrayList<L> existing = map.get( evtClass );
if (existing != null) {
return existing;
}
final ArrayList<L> emptyList = new ArrayList<L>(5);
map.put(evtClass, emptyList);
return emptyList;
}
}
/** Notify a new event to registered listeners of this event class **/
public <L> void notify( final GameEvent<L> evt) {
@SuppressWarnings("unchecked")
Class<GameEvent<L>> evtClass = (Class<GameEvent<L>>) evt.getClass();
for ( L listener : listenersOf( evtClass ) ) {
evt.notify(listener);
}
}
}
```
I suppose its fulfills your requirements:
* very light,
* fast,
* no casts (at usage),
* Every thing is checked at compile
time (no possible mistake),
* No API constraints on listeners (each event
choose it's own messages),
* Evolutive (no dependencies between
different events and/or listeners),
* The dispatcher is a generic black
box,
* Consumers and producers don't need to
know each other. | If you want to avoid `instanceof`, then your only bet is to use inheritance to route a method call to the right method. You cannot use method overloading, since that is decided at compile time by the *declared* type of the variable you are passing to a method. You have to use inheritance.
If you cannot use inheritance, then your only other choice (that I'm aware of) involves a lot of `instanceof`.
Regarding a messaging system, you can use [ActiveMQ](http://activemq.apache.org/) as an in-the-JVM message transport. You do not have to use it via socket or other means. I can't imagine that ActiveMQ would not be efficient enough for your means. | Simple java message dispatching system | [
"",
"java",
"design-patterns",
"events",
""
] |
I can't understand this code. If this is a RegExp, can it be done in a simpler way? Or is this already widely compatible? (with IE6 and newer browsers)
```
var u = navigator.userAgent;
// Webkit - Safari
if(/webkit/i.test(u)){
// Gecko - Firefox, Opera
}else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
}
```
Is this just:
```
String.indexOf("webkit")
``` | First it looks for "webkit" (ignoring case) in the string `u` in an attempt to determine that the browser is Safari.
If it doesn't find that, it looks for "mozilla" (without "compati") or "opera" in an attempt to determine that the browser is Firefox or Opera. Again, the searches are ignoring case (`/i`).
**EDIT**
The `/.../i.test()` code is a regular expression, these are built into JavaScript. | test() in javascript is a regular expression test function. You can read more about it [here.](http://www.devguru.com/Technologies/Ecmascript/Quickref/regexp_test.html)
> This method tests for a match of a regular expression in a string, returning true if successful, and false if not. The test method can be used with either a string literal or a string variable.
Code:
```
rexp = /er/
if(rexp.test("the fisherman"))
document.write("It's true, I tell you.")
```
Output:
```
It's true, I tell you.
```
Also [here's](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/Test) another great page that goes into more detail on this function.
> Executes the search for a match between a regular expression and a specified string. Returns true or false. | I can't understand this simple JS code | [
"",
"javascript",
""
] |
Assuming that the `enum` or `struct` is not nested within a particular class i.e. it belongs to the project namespace, should it be defined in:
* Its own file
* A general-purpose file called `Enums.cs` or `Structs.cs` where all the `enums`/`structs` that belong to the project namespace would be defined
* Somewhere else... | [This MSDN article on enum best practices](http://msdn.microsoft.com/en-us/library/ms229058.aspx) makes no recommendation on where to store enum definitions.
You'll get different recommendations. Personally, I tend to store enums in the same file as the class they're related to. I like to keep my file structure the same as my namespace structure, as much as possible, and so if my enums naturally fall into a particular namespace, I'll store the definition in the corresponding file.
My suggestion is, find a scheme that works for you, and stick with it. | Personally, I prefer the one type, one file philosophy. I even go so far as having nested types in separate files with partial classes used to allow the separation.
I mainly do this because I've seen far too much of the opposite. Single files that contain dozens of classes. The experience changed me. | What is good practice when deciding where enums and structs should be defined? | [
"",
"c#",
""
] |
How do I search a sub directory in my ASP.Net web site?
I know if this was a regular Winform project, I could easily get it by the following:
```
Environment.CurrentDirectory
```
or
```
System.IO.Directory.GetCurrentDirectory()
```
then
```
string[] directories = System.IO.Path.Combine(Environment.CurrentDirectory, "Portfolio")
```
How do I build the path to a subfolder called Portfolio in ASP.Net?
I'm having a problem building everything from the <http://??????????/Portfolio>. How do I find the ?????? part?
I tried the code above but got a completely different directory...
I don't want to hard code everything before that last subfolder because it will be different on another server. | Calling `Directory.GetCurrentDirectory()` can be misleading when calling it from an ASP.NET app. The best way to do get around this is to use [`Server.MapPath()`](http://msdn.microsoft.com/en-us/library/ms524632.aspx) instead, which will allow you to map a web folder to its location on disk.
So for example, running this code:
```
string path = Server.MapPath("~/Portfolio");
```
will set '`path`' equal to the location of that folder on disk.
If you're running this code from outside the context of a `Page` or control class, you won't be able to access the `Server` object directly. In this case, your code would look like this:
```
string path = HttpContext.Current.Server.MapPath("~/Portfolio");
``` | If I understand you right, you can just access it with:
```
"/portfolio"
```
The system will concatenate "/portfolio" to the url, if, for example it is "<http://site.com>" you will get "<http://site.com/portfolio>"
If you want the physical path, you can use
```
server.mappath("/portfolio")
```
and it will return the physical directory associated (for example E:\websites\site\portfolio") | ASP.Net search subdirectory | [
"",
"c#",
"asp.net",
""
] |
I have a function that I want to be sure is compiled JIT (i.e. right before it's called). Are there attributes or assembly settings that will ensure this? If not, then how can I guarantee that a function is compiled JIT?
Thanks!
**EDIT:**
I want to do this to prevent my application from crashing due to a missing referenced assembly. If my function is compiled JIT, I can wrap the function call that references the missing assembly in a try...catch block and gracefully handle the situation.
It is my understanding that there could be times when whole classes (or even the whole application) could be Jitted - this would cause an error I couldn't possibly catch. | If I read this correctly, you are worried about errors occurring when a class/method is first compiled. This requires awareness of the boundaries. It is obtainable with an extra layer.
If something is 'wrong with SuspectType (ie a required assembly not loading), the try/catch in the following is of no use because the Jitting of Scenario1() itself will fail.
```
void Scenario1()
{
try
{
var x = new SuspectType();
...
}
catch (..) { ... }
}
```
It could be rewritten as
```
void Scenario1a()
{
try
{
Scenario1b();
}
catch (..) { ... }
}
void Scenario1b()
{
var x = new SuspectType();
...
}
```
But, per Jon Skeet's comment, I'm not sure if this holds for the CFx. | I may be answering the wrong question, but it looks like you mainly want to be able to intercept assembly load failures (whole classes being JITted defeat the try/catch guards around the calls but that's a side effect of using explicit guards around method calls).
If you want to catch assembly resolution woes, instead of specifying a try/catch around every possible call, you could just listen to the global AssemblyResolve event and respond to the assembly loading failures (we're talking about .Net assemblies here, native dll's load failures would have to be tracked with a different mechanism).
```
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveFailure;
//...
}
static Assembly OnResolveFailure(object sender, ResolveEventArgs args)
{
//Do something here...
}
```
The downside of this is you can't do much, except looking for the assembly somewhere else (or logging the error). Specific and graceful logic when a resolution fails is not provided with this way of catching load failures. | Is there any way to ensure a function is compiled JIT? | [
"",
"c#",
"compilation",
"jit",
""
] |
As in the question, how do I automatically reset an Oracle sequence's value back to 0 every year in Oracle 10g?
I'm using the sequence to generate an identifier in the format `YYYY<sequence value>` and the sequence value has to be reset to 0 every year.
`YYYY` is obtained from java and concatenated with the sequence value from Oracle. The format of the identifier can't be changed due to external 3rd party requirements. Thanks for any help in advance. | Sequences aren't really designed to be reset. But there are some cases where resetting a sequence is desirable, for example, when setting up test data, or merging production data back into a test environment. This type of activity is *not* normally done in production.
IF this type of operation is going to be put into production, it needs to thoroughly tested. (What causes the most concern is the potential for the reset procedure to be accidentally performed at the wrong time, like, in the middle of the year.
Dropping and recreating the sequence is one approach. As an operation, it's fairly straightforward as far as the SEQUENCE goes:
```
DROP SEQUENCE MY_SEQ;
CREATE SEQUENCE MY_SEQ START WITH 1 INCREMENT BY 1 MINVALUE 0;
```
[EDIT] As Matthew Watson correctly points out, every DDL statement (such as a DROP, CREATE, ALTER) will cause an implicit commit. [/EDIT]
But, any privileges granted on the SEQUENCE will be dropped, so those will need to be re-granted. Any objects that reference the sequence will be invalidated. To get this more generalized, you would need to save privileges (before dropping the sequence) and then re-grant them.
A second approach is to ALTER an existing SEQUENCE, without dropping and recreating it. Resetting the sequence can be accomplished by changing the INCREMENT value to a negative value (the difference between the current value and 0), and then do exactly one .NEXTVAL to set the current value to 0, and then change the INCREMENT back to 1. I've used a this same approach before (manually, in a test environment), to set a sequence to a larger value as well.
Of course, for this to work correctly, you need to **insure** no other sessions reference the sequence while this operation is being performed. An extra .NEXTVAL at the wrong instant will screw up the reset. (NOTE: achieving that on the database side is going to be difficult, if the application is connecting as the owner of the sequence, rather than as a separate user.)
To have it happen every year, you'd need to schedule a job. The sequence reset will have to be coordinated with the reset of the YYYY portion of your identifier.
Here's an example:
<http://www.jaredstill.com/content/reset-sequence.html>
[EDIT]
**UNTESTED** placeholder for one possible design of a PL/SQL block to reset sequence
```
declare
pragma autonomous_transaction;
ln_increment number;
ln_curr_val number;
ln_reset_increment number;
ln_reset_val number;
begin
-- save the current INCREMENT value for the sequence
select increment_by
into ln_increment
from user_sequences
where sequence_name = 'MY_SEQ';
-- determine the increment value required to reset the sequence
-- from the next fetched value to 0
select -1 - MY_SEQ.nextval into ln_reset_increment from dual;
-- fetch the next value (to make it the current value)
select MY_SEQ.nextval into ln_curr from dual;
-- change the increment value of the sequence to
EXECUTE IMMEDIATE 'alter sequence MY_SEQ increment by '
|| ln_reset_increment ||' minvalue 0';
-- advance the sequence to set it to 0
select MY_SEQ.nextval into ln_reset_val from dual;
-- set increment back to the previous(ly saved) value
EXECUTE IMMEDIATE 'alter sequence MY_SEQ increment by '
|| ln_increment ;
end;
/
```
NOTES:
* how to best protect the sequence from access while it's being reset, RENAME it?
* Several test cases to work through here.
* First pass, check normative cases of positive, ascending, increment 1 sequence.
* would a better approach be to create new SEQUENCE, add permissions, rename existing and new sequences, and then re-compile dependencies? | Just throwing this out there as an idea:
If you want a solution that requires no ongoing DDL (i.e. no dropping and creating or resetting sequences), or even any jobs, you could consider something like this (this is in principle only, I haven't tested this approach but I'm sure it'll work):
1. Create a single sequence.
2. Create a reference table, with one row for each year, e.g.
YEARS (year NUMBER(4,0) PRIMARY KEY, starting\_value NUMBER)
3. When you get `NEXTVAL` from the sequence, you then have to subtract the `starting_value` when queried from the YEARS table for the current year. If the year is not found, a new row should be inserted (i.e. the first process run in any given year will insert the new value).
e.g. a function, e.g. `get_year_starting_value (pn_year IN NUMBER) RETURN NUMBER` could query this table and return the `starting_value` for the given year; if it gets `NO_DATA_FOUND`, it could call a procedure to insert it using the `NEXTVAL` from the sequence (committed in an autonomous transaction so that the new value is immediately available to other sessions, and so that the function doesn't fail due to the side effect)
Probably not a solution for all cases, but I think this approach may help in at least some scenarios. | How do I automatically reset a sequence's value to 0 every year in Oracle 10g? | [
"",
"sql",
"oracle",
""
] |
I have a little problem understanding the Java language
```
public class PhonebookEntryList extends List<PhonebookEntry>
{
public PhonebookEntryList(String filename) throws IOException
{
//loadListFromFilename(filename);
}
public void saveListToFilename(String filename) throws IOException
{
//Do something to save it to a file
}
}
```
I can't do this, because List is a generic Type (of course). I know what that means, but at the moment I can't think of a Solution for this problem.
Can you help me to solve it? Thanx! | No, your only problem is that you're `extend`ing an `interface`; you must `implement` it instead.
```
public class PhonebookEntryList implements List<PhonebookEntry>
```
should work; or you might prefer to extend a concrete class:
```
public class PhonebookEntryList extends ArrayList<PhonebookEntry>
```
or
```
public class PhonebookEntryList extends LinkedList<PhonebookEntry>
``` | You can't do that because List is an interface. But!
You shouldn't extend or implement a List class to make a PhonebookEntryList, it's a design error.
You should do:
```
public class PhonebookEntryList
{
private List<PhonebookEntry> entries;
public PhonebookEntryList(String filename) throws IOException
{
//loadListFromFilename(filename);
}
public void saveListToFilename(String filename) throws IOException
{
//Do something to save it to a file
}
}
```
I.e. your PhonebookEntryList should contain a list instead of inheriting it. | Java: Deriving from a generic List/Collection | [
"",
"java",
"list",
"generic-list",
""
] |
I've seen many web pages with a simple sound on /sound off button which plays music or some mp3 file when you press sound on and turns it off when you press off.
How do I do that?
Hi, I wasn't planning on using Flash -- if there is a standard plugin I could use and then make modification to the script, that'd be cool.
I'm open to whatever is the "standard" way to do it. | I used google and then I used pixel1 standalone | Here's the proper way to do it in AS3.
**Initialization:**
```
var sound:Sound;
var channel:SoundChannel;
var pos:Number;
var numLoops:Number = 0; // 0 to loop forever
sound = new Sound();
sound.load( new URLRequest("song.mp3") );
channel = sound.play( 0, numLoops );
```
**Stop playback:**
```
pos = channel.position;
channel.stop();
```
**Start playback:**
```
channel = sound.play( pos, numLoops );
```
It's true that you could toggle the volume to zero and back, but this leaves needless overhead, and when you restart the sound it will have advanced from where you "stopped" it. | How do I create a "sound on/ sound off" button? | [
"",
"javascript",
"html",
"flash",
"audio",
"mp3",
""
] |
How much of a difference are these two as far as performance?
```
tmp = []
tmp.append(True)
print tmp[0]
```
And
```
tmp = {}
tmp[0] = True
print tmp[0]
``` | The `timeit` module in the standard library is designed just to answer such questions! Forget the `print` (which would have the nasty side effect of spewing stuff to your terminal;-) and compare:
```
$ python -mtimeit 'tmp=[]; tmp.append(True); x=tmp[0]'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit 'tmp={}; tmp[0]=True; x=tmp[0]'
1000000 loops, best of 3: 0.515 usec per loop
```
So, the dict is the winner -- by 0.2 microseconds...!-) | Not only is micro-optimization usually pointless in general, I find it is especially difficult and arcane for Python in particular. It is very easy to actually make your code simultaneously slower and more complicated. See [this Stack Overflow question](https://stackoverflow.com/questions/900420/elegant-way-to-compare-sequences) for an example where the simplest, clearest, and shortest Python solutions also turned out to be the fastest.
As others have shown with actual tests, the speed difference between your two choices is quite small. What is less small is the semantic difference. Lists and dictionaries are not merely two implementations of the same concept, but are intended for different uses. Pick the one which better fits your use. | Is a list or dictionary faster in Python? | [
"",
"python",
"data-structures",
""
] |
I want to have the [addthis](http://www.addthis.com) widget available for my users, but I want to lazy load it so that my page loads as quickly as possible. However, after trying it via a script tag and then via my lazy loading method, it appears to only work via the script tag. In the obfuscated code, I see something that looks like it's dependent on the DOMContentLoaded event (at least for Firefox).
Since the DOMContentLoaded event has already fired, the widget doesn't render properly. What to do?
I could just use a script tag (slower)... or could I fire (in a cross browser way) the DOMContentLoaded (or equivalent) event? I have a feeling this may not be possible because I believe that (like jQuery) there are multiple tests of the content ready event, and so multiple simulated events would have to occur.
Nonetheless, this is an interesting problem because I have seen a couple widgets now assume that you are including their stuff via static script tags. It would be nice if they wrote code that was more useful to developers concerned about speed, but until then, is there a work around? And/or are any of my assumptions wrong?
**Edit:**
Because the 1st answer to the question seemed to miss the point of my problem, I wanted to clarify the situation.
This is about a specific problem. I'm not looking for yet another lazy load script or check if some dependencies are loaded script. **Specifically** this problem deals with
1. external widgets that you do not
have control over and may or may not
be obfuscated
2. delaying the load of the
external widgets until they
are needed or at least, til
substantially after everything else
has been loaded including other deferred elements
3. b/c of the how
the widget was written, precludes
existing, typical lazy loading
paradigms
While it's esoteric, I have seen it happen with a couple widgets - where the widget developers assume that you're just willing to throw in another script tag at the bottom of the page. I'm looking to save those 500-1000 ms\*\* though as numerous studies by Yahoo, Google, and Amazon show it to be important to your user's experience.
\*\*My testing with hammerhead and personal experience indicates that this will be my savings in this case. | This code solves the problem and saves the loading time that I was looking for.
After reading this [post](http://www.zachleat.com/web/2008/12/04/domcontentloaded-inconsistencies/) about how most current js libraries implement tests for a dom loaded event. I spent some time with the obfuscated code, and I was able to determine that addthis uses a combination of the mentioned doscroll method, timers, and the DOMContentLoaded event for various browsers. Since only those browsers dependent on the DOMContentloaded event would need the following code anyway:
```
if( document.createEvent ) {
var evt = document.createEvent("MutationEvents");
evt.initMutationEvent("DOMContentLoaded", true, true, document, "", "", "", 0);
document.dispatchEvent(evt);
}
```
and the rest depend on timers testing for existence of certain properties, I only had to accommodate this one case to be able to lazy load this external JS content rather than using the static script tags, thus saving the time that I was hoping for. :) | The simplest solution is to set parameter **domready** to 1 when embedding addthis script into your page. Here is an example:
```
<script type="text/javascript"
src="http://s7.addthis.com/js/250/addthis_widget.js#username=addthis&domready=1">
</script>
```
I have tested it on IE, Firefox, Chrome, and Safari, and all worked fine. More information on addthis configuration parameters is available [here](http://www.addthis.com/help/menu-api). | Lazy loading the addthis script? (or lazy loading external js content dependent on already fired events) | [
"",
"javascript",
"optimization",
"widget",
"dom-events",
""
] |
Could someone explain to me why it is considered inapropriate to have a try-catch in the main() method to catch any unhandled exceptions?
```
[STAThread]
static void Main()
{
try
{
Application.Run(new Form1());
}
catch (Exception e)
{
MessageBox.Show("General error: " + e.ToString());
}
}
```
I have the understanding that this is bad practice, but not sure why. | I don't think its *necessarily* bad practice. There are a few caveats however...
I believe the point of whoever called this "bad practice" was to reinforce the idea that you should be catching exceptions *closest to where they occur* (i.e. as high up the call stack as possible/appropiate). A blanket exception handler isn't typically a good idea because its drastically reduces the control flow available to you. Coarse-grained exception handling is quite importantly *not* a reasonable solution to program stability. Unfortunately, many beginner developers think that it is, and take such approaches as this blanket try-catch statement.
Saying this, *if* you have utilised exception handling properly (in a fine-grained and task-specific manner) in the rest of your program, and handled the errors accordingly there (rather than juist displaying a generic error box), *then* a general try-catch for all exceptions in the `Main` method is probably a useful thing to have. One point to note here is that if you're *reproducably* getting bugs caught in this `Main` try-catch, then you either have a bug or something is wrong with your localised exception handling.
The primary usage of this try-catch with `Main` would be purely to prevent your program from crashing in very unusual circumstances, and should do hardly any more than display a (vaguely) user-friendly "fatal error" message to the user, as well as possibly logging the error somewhere and/or submitting a bug report. So to conclude: this method *does* have its uses, but it must be done with great care, and not for the wrong reasons. | Well, this method will only capture exceptions thrown in your main thread. If you use both the [Application.ThreadException](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx) and the [AppDomian.UnhandledException](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx) events instead then you'll be able to catch and log all exceptions. | Why are try-catch in main() bad? | [
"",
"c#",
"exception",
""
] |
I have a Observable collection which is bind to listview which contains date and time.
When a time in the collection occurs a messagebox should be shown.
I do as
```
public class Reminder
{
public string Name { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}
ObservableCollection<Reminder> reminderList = new ObservableCollection<Reminder>();
Reminder newItem = new Reminder
{
Name = name,
Date = date,
Time = time
};
reminderList.Add( newItem );
```
How can I show a message when a time in collection occurs? | Have your Reminder class implement INotifyPropertyChanged like so:
```
public class Reminder : INotifyPropertyChanged
{
private string time;
public string Name { get; set; }
public string Date { get; set; }
public string Time
{
get
{
return this.time;
}
set
{
if (this.time != value)
{
this.time = value;
this.OnTimeChanged();
}
}
}
protected void OnTimeChanged()
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("Time"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
```
Then, when you new up your Reminder object, hook into the PropertyChanged event. If the property that changed is "Time" and the time is the one you want, show your message:
```
var newItem = new Reminder
{
Name = name,
Date = date,
Time = time
};
newItem.PropertyChanged += (o, ex) =>
{
if (ex.PropertyName == "Time" && newItem.Time == specificTime)
{
//do what you need to do
}
};
reminderList.Add( newItem );
``` | How about creating a Timer object, and in its Tick event handler getting it to iterate through the list to see anything that has expired? | Show message by iterating observable collection containing date and time | [
"",
"c#",
".net",
"wpf",
""
] |
I am writing a web server in C# and I'm trying to add support for PHP. I have it mostly working, except I don't know how to past GET and POST data to the PHP executable when i pass the file to it. I've been testing with GET since I haven't gotten to getting POST requests handled on the server, and I have the string of the arguments that gets passed separated, but I don't know how to feed the information to the php parser. Some tips would be appreciated. | For GET:
The Easy Way (That i've found):
```
php-cgi.exe <script-file-name> <parameter1>=<value1> <parameter2>=<value2> [...] <parameterN>=<valueN>
```
The Harder Way (via php-cgi and windows cli) would be:
```
SET "QUERY_STRING=<parameter1>=<value1>&<parameter2>=<value2>&[...]&<paramterN>=<valueN>"
SET SCRIPT_NAME=<script-file-name>
SET REQUEST_METHOD=GET
SET REDIRECT_STATUS=0
php-cgi.exe
```
I'd assume there would be a way to set environment variable via C#/.Net. The environment variables would have to be unset after php-cgi.exe completes.
More info for CGI environment variables you could set (and CGI in general) at <http://www.ietf.org/rfc/rfc3875.txt>. Might also be of use would be PHP's $\_SERVER variable documentation. Security considerations for running PHP as CGI also in PHP documentation at php.net. | Are you familiar with [CGI](http://hoohoo.ncsa.illinois.edu/cgi/)? This is normally how web servers will execute arbitrary external programs.
There are certainly more modern alternatives to CGI, but (almost) every web server and external program today will support CGI. | How to pass GET and POST data to the php executable? | [
"",
"php",
"post",
"get",
"webserver",
""
] |
I'm making a neural network and wanted to use a hash\_map to keep weight references for output neurons for each neuron:
```
class Neuron; //forward declaration was there (sorry I forgot to show it earlier)
typedef double WEIGHT;
typedef stdext::hash_map<boost::shared_ptr<Neuron>,WEIGHT> NeuronWeightMap;
class Neuron
{
private:
NeuronWeightMap m_outputs;
//...
public:
Neuron();
~Neuron();
//...
WEIGHT GetWeight(const boost::shared_ptr<Neuron>& neuron) const
{
NeuronWeightMap::const_iterator itr = m_outputs.find(neuron);
if( itr != m_outputs.end() )
{
return itr->second;
}
return 0.0f;
}
};
```
I realize that I can't use the boost::shared\_ptr as the key of a stdext::hash\_map, so what would be another suggestion? Are there any work-arounds or is the only option to use a different key or maybe switch to an std::map?
Thanks!
Here is the errors:
```
1>c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(61) : error C2440: 'type cast' : cannot convert from 'const boost::shared_ptr<T>' to 'size_t'
1> with
1> [
1> T=Neuron
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(99) : see reference to function template instantiation 'size_t stdext::hash_value<_Kty>(const _Kty &)' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(98) : while compiling class template member function 'size_t stdext::hash_compare<_Kty,_Pr>::operator ()(const _Kty &) const'
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Pr=std::less<boost::shared_ptr<Neuron>>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\hash_map(80) : see reference to class template instantiation 'stdext::hash_compare<_Kty,_Pr>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Pr=std::less<boost::shared_ptr<Neuron>>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(119) : see reference to class template instantiation 'stdext::_Hmap_traits<_Kty,_Ty,_Tr,_Alloc,_Mfl>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Ty=common_ns::WEIGHT,
1> _Tr=stdext::hash_compare<boost::shared_ptr<Neuron>,std::less<boost::shared_ptr<Neuron>>>,
1> _Alloc=std::allocator<std::pair<const boost::shared_ptr<Neuron>,common_ns::WEIGHT>>,
1> _Mfl=false
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\hash_map(90) : see reference to class template instantiation 'stdext::_Hash<_Traits>' being compiled
1> with
1> [
1> _Traits=stdext::_Hmap_traits<boost::shared_ptr<Neuron>,common_ns::WEIGHT,stdext::hash_compare<boost::shared_ptr<Neuron>,std::less<boost::shared_ptr<Neuron>>>,std::allocator<std::pair<const boost::shared_ptr<Neuron>,common_ns::WEIGHT>>,false>
1> ]
1> FILE_PATH_REMOVED\neuralnet.h(21) : see reference to class template instantiation 'stdext::hash_map<_Kty,_Ty>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Ty=common_ns::WEIGHT
1> ]
1>NeuralNet.cpp
1>c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(61) : error C2440: 'type cast' : cannot convert from 'const boost::shared_ptr<T>' to 'size_t'
1> with
1> [
1> T=Neuron
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(99) : see reference to function template instantiation 'size_t stdext::hash_value<_Kty>(const _Kty &)' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(98) : while compiling class template member function 'size_t stdext::hash_compare<_Kty,_Pr>::operator ()(const _Kty &) const'
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Pr=std::less<boost::shared_ptr<Neuron>>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\hash_map(80) : see reference to class template instantiation 'stdext::hash_compare<_Kty,_Pr>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Pr=std::less<boost::shared_ptr<Neuron>>
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\xhash(119) : see reference to class template instantiation 'stdext::_Hmap_traits<_Kty,_Ty,_Tr,_Alloc,_Mfl>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Ty=common_ns::WEIGHT,
1> _Tr=stdext::hash_compare<boost::shared_ptr<Neuron>,std::less<boost::shared_ptr<Neuron>>>,
1> _Alloc=std::allocator<std::pair<const boost::shared_ptr<Neuron>,common_ns::WEIGHT>>,
1> _Mfl=false
1> ]
1> c:\program files (x86)\microsoft visual studio 8\vc\include\hash_map(90) : see reference to class template instantiation 'stdext::_Hash<_Traits>' being compiled
1> with
1> [
1> _Traits=stdext::_Hmap_traits<boost::shared_ptr<Neuron>,common_ns::WEIGHT,stdext::hash_compare<boost::shared_ptr<Neuron>,std::less<boost::shared_ptr<Neuron>>>,std::allocator<std::pair<const boost::shared_ptr<Neuron>,common_ns::WEIGHT>>,false>
1> ]
1> FILE_PATH_REMOVED\neuralnet.h(21) : see reference to class template instantiation 'stdext::hash_map<_Kty,_Ty>' being compiled
1> with
1> [
1> _Kty=boost::shared_ptr<Neuron>,
1> _Ty=common_ns::WEIGHT
1> ]
1>Generating Code...
``` | You probably have `Neuron` declared in your .h file.
So the below could work:
```
struct hasher {
size_t operator()(const boost::shared_ptr<Neuron>& n) { return (size_t)n.get(); }
};
typedef stdext::hash_map<boost::shared_ptr<Neuron>,WEIGHT,hasher> NeuronWeightMap;
```
The problem probably is that `boost:shared_ptr` has no default hashing function (what one would look like?), so you just need to provide one. | You could also provide a template specialization for the hash:
```
#include <functional>
#include <boost/shared_ptr.hpp>
template<class T>
class std::tr1::hash<boost::shared_ptr<T>> {
public:
size_t operator()(const boost::shared_ptr<T>& key) const {
return (size_t)key.get();
}
};
```
Works perfectly with unordered\_set:
```
class Foo;
typedef boost::shared_ptr<Foo> FooPtr;
typedef std::tr1::unordered_set<FooPtr> FooSet;
``` | C++ boost shared_ptr as a hash_map key | [
"",
"c++",
"boost",
"neural-network",
"shared-ptr",
"hashmap",
""
] |
Is it possible to tell JPanel to set its size to fit all components that it contains? Something like `pack()` for JFrame.
edit: The trick with preferredSize didn't help. I've got JSplitPane, where in one part there is GridBagLayout with many labels (see screenshot) and labels overlap each other.
[screenshot http://foto.darth.cz/pictures/screen.png](http://foto.darth.cz/pictures/screen.png) | After looking at the source code for `pack()`, I came up with:
```
panel.setPreferredSize(panel.getPreferredSize());
```
This forces the panel to recalculate its preferred size based on the preferred sizes of its subcomponenents.
You may or may not have to call [`validate()`](http://java.sun.com/javase/6/docs/api/java/awt/Container.html#validate()) afterward; in my tiny example, it seemed to make no difference, but the Javadoc says:
> The `validate` method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
So I guess it depends on why you're having to repack your `JPanel`. | By default `Container`s have a preferred size that matches the preferred layout size given by the container. So literally all you have to do is:
```
panel.setSize(panel.getPreferredSize());
```
Presumably you are doing something odd with the parent to stop the parent's layout manager doing the equivalent of this. | JPanel size by inner components | [
"",
"java",
"user-interface",
"swing",
""
] |
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).
This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1.
Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy?
Here's my function:
```
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
correlation = numpy.corrcoef(x, y)[0,1]
# r
results['correlation'] = correlation
# r-squared
results['determination'] = correlation**2
return results
``` | From the [numpy.polyfit](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function
E(y|x) = p\_d \* x\*\*d + p\_{d-1} \* x \*\*(d-1) + ... + p\_1 \* x + p\_0
So you just need to calculate the R-squared for that fit. The wikipedia page on [linear regression](http://en.wikipedia.org/wiki/Linear_regression) gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being
```
SST = Sum(i=1..n) (y_i - y_bar)^2
SSReg = Sum(i=1..n) (y_ihat - y_bar)^2
Rsquared = SSReg/SST
```
Where I use 'y\_bar' for the mean of the y's, and 'y\_ihat' to be the fit value for each point.
I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct
```
import numpy
# Polynomial Regression
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()
# r-squared
p = numpy.poly1d(coeffs)
# fit values, and mean
yhat = p(x) # or [p(z) for z in x]
ybar = numpy.sum(y)/len(y) # or sum(y)/len(y)
ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])
results['determination'] = ssreg / sstot
return results
``` | A very late reply, but just in case someone needs a ready function for this:
[scipy.stats.linregress](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html)
i.e.
```
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)
```
as in @Adam Marples's answer. | How do I calculate r-squared using Python and Numpy? | [
"",
"python",
"math",
"statistics",
"numpy",
"curve-fitting",
""
] |
There are loads of profilers and static code analyzers out there for C# assemblies.
Just wonder if there are any methods to prevent being analyzed, because it does make me feel a bit nervous when being stripped.
I have searched all over the Internet and stackoverflow. There seems none for my wonder.
What I've got are only some even more scary titles like these (sorry, new user can't post hyper links, please google them):
"Assembly Manipulation and C#/VB.NET Code Injection"
"How To Inject a Managed .NET Assembly (DLL) Into Another Process"
Is it just me being too worried or what?
BTW, with C#, we are building a new winform client for a bank's customers to do online transactions. Should we not do this in the winform way or should we use some other language like Delphi, C++? Currently we have a winform client built with C++ Builder. | Just about any application can be "analysed and injected". Some more than others. That's why you NEVER TRUST USER INPUT. You fully validate your user's requests on the server end, making sure you're not vulnerable to buffer overruns, sql injection and other attack vectors.
Obfuscators can make .NET assemblies harder to analyze. Using a secure key to strong-name your assemblies can make it much harder to alter your code. But, like everything else in the digital world, somebody can exploit a vulnerability and get around whatever safeguards you put in place. | If by analyzed you mean someone decompiling the code and looking at it, then the Dotfucstor that ships with VS Pro and above is a simple (free) tool to help here. There is a fuller functionality (but paid for) version that can do more.
To prevent someone tampering with your deployed assmebliles, use [Strong Names](http://msdn.microsoft.com/en-us/library/xc31ft41(VS.71).aspx). | Is there way to prevent our application from being analysed or injected? (c#) | [
"",
"c#",
"code-injection",
"analyzer",
""
] |
EDIT: I also got an answer to make sector a vector of vectors:
```
vector<vector<char>>sector;
```
and that gets rid of the rest of my errors.
EDIT: I've made sector an array of pointers as someone suggested, and still get three errors:
EDIT: I have edited the program, but it has not fixed all of the errors:
I have this section of a program:
```
char* load_data(int begin_point,int num_characters);
ifstream mapdata("map_data.txt");
const int maxx=atoi(load_data(0,2));
const int maxy=atoi(load_data(2,2));
char** sector=new char[maxx][maxy];
char* load_data(int begin_point,int num_characters)
{
seekg(begin_point);
char* return_val=new char[num_characters+1];
mapdata.getline(return_val,num_characters);
return return_val;
}
```
And I get these errors:
line 5>error C2540: non-constant expression as array bound
line 5>error C2440: 'initializing' : cannot convert from 'char (\*)[1]' to 'char \*\*'
line 14>error C3861: 'seekg': identifier not found
per seekg: yes I know I have to include fstream, I included that in main.cpp, this is a separate .h file also included in main.cpp.
How do I fix the errors? Specifically, how to I fix the errors while keeping all my variables global?
Also, if it helps, this is map\_data.txt:
```
10
10
00O
99!
1
55X
19
What is a question?
18
This is an answer
1
1
2
1
``` | Well,
function load\_data(int,int) returns a char.
You are passing that char to the atoi function, that takes a char\*. In addition to that, you are probably not including stdlib.h header file!!
```
#include <cstdlib>
int atoi(const char*);
```
If you dont wan't to include stdlib.h, then you could declare atoi as extern, but be aware when you compile this module.
```
extern int atoi(const char*)
```
Take into account that the argument of atoi function must be a null-terminated string.
In order for your code to work, you should make function load data return a char\*, not a char.
```
char* load_data(int,int);
```
So, now you could do
```
//notice these aren't const, they rely on non-compile time available data.
int maxx = atoi (load_data(....));
int maxy = atoi (load_data(....));
```
If you are in C++, load\_data function could return a std::string.
```
std::string load_data(int,int)
```
and then use c\_str() method, which returns a C-String from a C++ string.
```
const char* std::string:c_str()
int maxx = atoi(load_data(....).c_str());
int maxy = atoi(load_data(....).c_str());
```
In addition to that, you shouldn't
(regarding
```
line 5>error C2540: non-constant expression as array bound
line 5>error C2440: 'initializing' : cannot convert from 'char (*)[1]' to 'char **'
```
)
```
char sector[maxx][maxy];
```
You should
```
char** sector = new char[maxx][maxy]();
```
and dont forget to free this memory
```
delete[](sector);
``` | You can't return a pointer to a stack variable. And arrays need to be returned as pointer types.
Try:
```
char* load_data(int begin_point,int num_characters)
{
seekg(begin_point);
char* return_val = new char[num_characters+1];
mapdata.getline(return_val, num_characters);
return return_val;
}
char* foo = load_data(...);
...
delete [] foo;
``` | How can I make this declaration work? | [
"",
"c++",
"arrays",
"text-files",
"constants",
""
] |
I'm working on a web app which will need to work offline. I'm looking at [Gears](http://gears.google.com/) right now, but I also found [Dojo offline](http://www.dojotoolkit.org/offline). I'm asking this question because the latest news of it are from 2007, and the hosted [demos](http://docs.google.com/View?docid=dhkhksk4_8gdp9gr#demos) don't seem to work (I've installed Gears under Firefox 3.0 on my Ubuntu laptop)
Is anyone using Dojo offline, or an alternative high level offline web application toolkit right now? | Dojo Offline will most likely support native HTML5 offline features in the upcoming browsers (like the latest Firefox release candidate for 3.5), or fall back to using Gears if the user isn't on an HTML5-capable browser. So Dojo Offline provides an abstract layer above the actual implementation which will allow for adaptation to newer offline technologies without having to change your own code. | As the web site you link to states, Dojo Offline is built on top of Gears. The only reason you'd want to use Dojo Offline is if you use the dojo toolkit for other functionality on your site. | Is Dojo offline working? Are there any alternatives? | [
"",
"javascript",
"dojo",
"offline",
""
] |
Ok, i'm a regex doofus. I only ever learn enough to get me by, but i would like to know how to do the below regex without using a php ternary operator in the middle of it. Also it may be ugly but it works...
```
'^". $date[0].(($date[0] == 0)?'?':'').$date[1]."[/.-]".$date[2].(($date[2] == 0)?'?':'').$date[3]."'";
```
uhm. as you can see im using a ternary operator to test if the date contains a 0. if it does.. then it can be ignored, if not then its a 1 or 2 and do not ignore. i'm sure there is a way to write this with just regex? If you know how then please tell me and i will be forever greatful. Also, just incase you wondering this is a regex in a mysql query. | Are you looking for this? match[1] is the month, match[2] is the day and match[3] is the year
```
$regex = '#(0?[1-9]|1[0-2])[-/]([0-2]?[1-9]|3[01])[-/](19|20)?\d\d)#';
```
You have a couple problems here.
First, never ever put a text into a database that you haven't made sure is formatted correctly. The fact that the dates are in the database with and without the 0's is a problem. Why aren't the dates in datetime fields where the database would make sure they are formatted correctly?
Second, the regex above only works in the US where 'mm/dd/yyyy' dates are used. Support for other date formats is impossible if you are tied to that regex.
Third, why are you doing this in the database? Your example is WHERE birthday regex something.... That means you have this date before you are passing it to mySQL. So fix the date in PHP first:
```
$date = strtotime($_GET['date']);
$sql = "select blah From blah WHERE birthday = '$date' blah";
``` | There really isn't any easy way to simplify this. The problem is that you are building a regular expression which forces you to test on zero no matter what. You might be better off converting $date into a true date with mktime and then use that in your query.
```
$date1 = mktime(0,0,0, substr($date, 0, 2), substr($date, 2, 2));
$sqlquery = "select * from table WHERE table_date == $date1";
``` | Fairly simple regex question in PHP | [
"",
"php",
"regex",
""
] |
I am trying to write a error reporting feature for a website in php. I cannot get the headers right so that the email will display as html.
Here is the code:
```
if( isset($_POST['submit']) )
{
$browser = $_SERVER['HTTP_USER_AGENT'];
$page = $_POST['page'];
$email = $_POST['email'];
$error = $_POST['error'];
$message = "<html><body> \n";
$message .= "Email: $email \n";
$message .= "Page: $page \n";
$message .= "OS/ Browser: $browser \n";
$message .= "Error: $error \n";
$message .= "</body></html> \n";
$headers = 'MIME-Version: 1.0' . '\r\n';
$headers .= 'Content-type: text/html; charset="iso-8859-1"' . '\r\n';
$headers .= 'From: <code@website.com>' . '\r\n';
$headers .= 'Reply-To: $email ' . '\r\n';
$headers .= 'X-Priority: 1' . '\r\n';
$subject = "[ERROR REPORT] Page: " . $page;
mail("myEmail@gmail.com", $subject, $message, $headers );
$mesg = "Thank you for your report!";
}
?>
``` | Basically repeating what I answered for [another question](https://stackoverflow.com/questions/809924/is-this-the-correct-way-to-send-email-with-php/), I'm all for rolling-your-own in most situations, but when it comes to mail I'd heartily recommend making it easier on yourself and using something like [Swift Mailer](http://swiftmailer.org/) or [PHPMailer](http://phpmailer.codeworxtech.com/) (in that order, for my money).
As a side-bonus (and assuming you specify reply-to, etc), you also have much less chance of being tagged as spam.
EDIT: Maybe it's just the example you've used, but there's no actual HTML in your message. Why not just use plain text? And yes, I'd use one of the classes I suggest for plain text too. | Personally, I'm a fan of Pear Mail (<http://pear.php.net/package/Mail>) and Pear Mail\_Mime (<http://pear.php.net/package/Mail_Mime>).
Sending an HTML e-mail (with a plain-text body, for clients that don't support HTML) is as simple as this:
```
include_once('Mail.php');
include_once('Mail/Mime.php');
$htmlBody = '<html><body><b>Hello World</b></body></html>';
$plainBody = 'Your client doesn\'t support HTML';
$em = Mail::factory('sendmail');
$headers = array('From'=>'me@domain.com', 'To'=>'joe@schmoe.com', 'Subject'=>'Cool Email');
$mime = new Mail_Mime();
$mime->setTxtBody($plainBody);
$mime->setHtmlBody($htmlBody);
$message = $mime->get();
$headers = $mime->headers($headers);
$mail = $em->send('joe@schmoe.com', $headers, $message);
``` | mail() header problem for html email | [
"",
"php",
"email",
"header",
""
] |
I just started using cdb and I love it!
I've found and [bookmarked](http://delicious.com/john.weldon/cdb) a few interesting articles I've found on using cdb, but I'd love to see other peoples resources.
What sites do you use to extract the max usefulness from cdb (windbg) | Code project has a great beginners article on WinDbg. There may be some items you have not seen yet.
<http://www.codeproject.com/KB/debug/windbg_part1.aspx>
Here is a list of some commonly used features
<http://www.windbg.info/doc/1-common-cmds.html> | Here are a series of links that I have collected on WinDbg/SOS over the years:
* [If broken it is fix it you should blog](https://web.archive.org/web/20100219233135/http://blogs.msdn.com:80/tess/default.aspx) -- Tess Ferrandez's excellent blog on WinDbg/.Net debugging with interesting [labs](https://web.archive.org/web/20100118142529/http://blogs.msdn.com:80/tess/pages/net-debugging-demos-information-and-setup-instructions.aspx)
* [WinDbg / SOS Cheat Sheet](https://web.archive.org/web/20201024041713/http://geekswithblogs.net/.NETonMyMind/archive/2006/03/14/72262.aspx) -- Commonly used SOS commands
* [John Robbin's Blog / CmdTree information](https://web.archive.org/web/20100323134731/http://www.wintellect.com:80/CS/blogs/jrobbins/archive/2008/09/17/windbg-cmdtree-file-that-eases-some-sos-pain.aspx) -- CmdTree is a hidden feature of WinDbg to create shortcuts to commonly used items
* [SOSEX](https://web.archive.org/web/20220605125636/http://www.stevestechspot.com/) -- Steve Johnson's SOS Extensions that contain a bunch of exta .Net debugging extensions | I'm looking for links to cdb/windbg + .net documentation | [
"",
"c#",
"windbg",
"sos",
""
] |
Visual C++ has a compiler setting "Enable C++ Exceptions" which can be set to "No". What exactly will happen if I set it this way? My code never explicitly throws or catches exceptions (and therefore the first thrown exception will terminate the program anyway) and doesn't rely on stack unwinding - should I expect any more undesired behaviour from the recompiled program? | The [MSDN documentation of the setting](http://msdn.microsoft.com/en-us/library/1deeycx5(VS.80).aspx) explains the different exception modes and even gives code examples to show the difference between the different modes. Furthermore, [this article](http://www.thunderguy.com/semicolon/2002/08/15/visual-c-exception-handling/) might be interesting, even though it's pretty old.
Bottom line: The option basically enables or disables the tracking of the life-spans of all your objects. Such tracking is required, because in the case of an exception, all the proper destructors need to be called, the stack has to be unwinded, and a lot of clean up is done. Such tracking requires organizational overhead (= additional code) - this can be dropped by setting the option to "No".
I haven't tried by myself, but it looks like you still can `throw` and `catch` exceptions if the option is set to "No", but the clean up and unwinding is missing, which might have very bad consequences (not recommended ;) .. | The compiler will omit the destructors and other stack-unwinding code that cleans up after C++ objects when they go out of scope as the result of an exception.
In other words, it leaves out a bunch of cleanup code. This [will significantly improve performance](http://www.gamearchitect.net/Articles/ExceptionsAndErrorCodes.html), but also cause grave evil if an exception actually does get thrown. (Time it yourself if you don't believe me.)
The performance difference isn't really a reason to disable exceptions, except in certain critical applications where you will be absolutely obliged to do so. | What exactly will happen if I disable C++ exceptions in a project? | [
"",
"c++",
"exception",
""
] |
In the following SQL query using the `PreparedStatement` class:
```
String query_descrip = "insert into timitemdescription (itemkey, languageid, longdesc, shortdesc) values (?, 1033, ?,?)";
PreparedStatement pstmt2 = con.prepareStatement(query_descrip);
pstmt2.setInt(1, rs4);
pstmt2.setString(2, itemdescription);
pstmt2.setString(3, itemdescription.substring(0,39));
pstmt2.executeUpdate();
```
I sometimes get apostrophes and single and double quotes in my item descriptions. for example, my late issue with one item is a "Planar 22" monitor". Of course, the string was misinterpreted and thought the description value was just "Planar 22".
What is the best way to handle special characters in a string?
I've read that some people are using regex, however these seemed to be specific to a case by case basis. Another way I'm working on is reading the string array character by character. I was hoping there was a more efficient and less resource-intensive way of doing this.
UPDDATE
AFter some more extensive testing, it turns out there were more problems occuring in my code. it was also a URL Encoding problem. When the html form was being populated by the jsp code,it would try to move the description field to an online form, it truncates it there on the form rather than on the query. jTDS also corrected the problem receiving the special characters. Because jTDS is a jar, it also helped avoid rebooting the machine. I will award the jTDS thread the bounty since that was what I partially used.
thanks in advance | Since you are using PreparedStatement, you don't have to do anything at all, it will be handled for you by the JDBC driver. The only thing you have to look out for is non-ASCII characters, specifically you have to make sure the DB tables use an encoding for textual columns that can handle all characters you're going to use. But that's an SQL issue, not a Java issue. | Like the others have said, you do not have to do anything to handle the special characters. You need to try a different JDBC driver.
Try using the [jTDS driver](http://jtds.sourceforge.net/) and see if it helps you with your PreparedStatement. It is an open source database driver for SQL Server. I use it at work now and it works like a champ and actually conforms to the JDBC specification unlike the MS driver. | How do I handle special characters in a Java PrepareStatement? | [
"",
"java",
"string",
"special-characters",
""
] |
At work we use a .ini file to set variables prior to calling the rest of the framework (I think it goes
```
function getConfigVars(){
//read my_config.ini file
....
//call framework
}
```
and I have always wondered if there was a benefit to doing it that way.
It seems to me that you then have to write access rules to stop people from looking at it from the web and php has to parse it and understand it.
So, why use my\_config.ini rather than my\_config.php? It is not like anyone should be touching it after it is set up and it seems more convenient to just call the variables and be able to have your IDE auto complete the text wherever you are using the ini variables / parse it for errors. | The [Zend Framework](http://framework.zend.com/) contains a config parses that parses files that are written in the ini format ([Zend\_Config\_Ini](http://framework.zend.com/manual/en/zend.config.adapters.ini.html)), it sounds like this is what you are using.
The config file should not be located in your document root, and if it is not in your document root then no re-write rules are required since no-one can access it anyway.
> The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character (.). A section may extend or inherit from another section by following the section name with a colon character (:) and the name of the section from which data are to be inherited.
From [Zend\_Config\_Ini](http://framework.zend.com/manual/en/zend.config.adapters.ini.html) page.
The Zend Framework uses it to allow you to have multiple configuration parameters, one for staging, one for development and one for production. This also allows for easy setting database settings for production, and for development and having two very different settings. Different paths set up in the ini file to where includes are located. This makes it much easier to move code from development to production knowing that immediately everything that is development will be turned off.
Sure, this would be possible with a PHP script, but it would require more parsing of the various configuration variables as well as doing if/then checks, whereas using the parse\_ini\_file() does all of this for you automatically.
The other answers also already pointed out that non-programmers may need to change variables and or something on the website that is set as a configuration variable (for example, site title that is used in the sites layout). INI files are easy to understand and read even for someone that has never programmed before.
Example from a website I am currently working on:
```
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/users.db"
resources.view[] =
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.params.dbname = APPLICATION_PATH "/../data/db/users-testing.db"
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.params.dbname = APPLICATION_PATH "/../data/db/users-dev.db
```
It makes it extremely easy to have multiple data sets for the various environments in which the code can be run. | For those who come to this question because they want to know if there are any performance differences between using an INI file which must be parsed and a PHP file which is simply included (And can be cached by PHP): Yes, there are differences but they are so small that it doesn't really matter.
My benchmark scenario is a `config.ini` file with 20 key/value pairs and a `config.php` file with the same 20 key/value pairs written as defines. PHP version is 5.4.9 on Ubuntu Linux 13.04.
```
key1 = value1
...
key20 = value20
```
vs.
```
<?php
define("key1", "value1");
...
define("key2", "value20");
```
Two test scripts including the configs:
```
<?php
$CONF = parse_ini_file("config.ini");
```
vs.
```
<?php
require_once "config.php";
```
I tested the performance with `ab -c 25 -n 10000`.
Result without a PHP cache:
```
ini: Requests per second: 2660.89 [#/sec] (mean)
php: Requests per second: 2642.28 [#/sec] (mean)
```
Result with APC PHP cache:
```
ini: Requests per second: 3294.47 [#/sec] (mean)
php: Requests per second: 3307.89 [#/sec] (mean)
```
I ran the tests multiple times, naturally the numbers will vary every time but the consensus is: `config.ini` is a little bit faster when no PHP cache is used, `config.php` is a little bit faster when a PHP cache is used. But the difference is so small that the decision should not be based on performance. | my_config.ini vs my_config.php | [
"",
"php",
"configuration-files",
"ini",
""
] |
i'm working on a project that consists of a website that connects to the NCBI(National Center for Biotechnology Information) and searches for articles there. Thing is that I have to do some text mining on all the results.
I'm using the JAVA language for textmining and AJAX with ICEFACES for the development of the website.
What do I have :
A list of articles returned from a search.
Each article has an ID and an abstract.
The idea is to get keywords from each abstract text.
And then compare all the keywords from all abstracts and find the ones that are the most repeated. So then show in the website the related words for the search.
Any ideas ?
I searched a lot in the web, and I know there is Named Entity Recognition,Part Of Speech tagging, there is teh GENIA thesaurus for NER on genes and proteins, I already tried stemming ... Stop words lists, etc...
I just need to know the best aproahc to resolve this problem.
Thanks a lot. | i would recommend you use a combination of POS tagging and then string tokenizing to extract all the nouns out of each abstract.. then use some sort of dictionary/hash to count the frequency of each of these nouns and then outputting the N most prolific nouns.. combining that with some other intelligent filtering mechanisms should do reasonably well in giving you the important keywords from the abstract
for POS tagging check out the POS tagger at <http://nlp.stanford.edu/software/index.shtml>
However, if you are expecting a lot of multi-word terms in your corpus.. instead of extracting just nouns, you could take the most prolific [n-grams](http://en.wikipedia.org/wiki/N-gram) for n=2 to 4 | This might be relevant as well:
<https://github.com/jdf/cue.language>
It has stop words, word and ngram frequencies, ...
It's part of the software behind [Wordle](http://www.wordle.net/). | Which NLP toolkit to use in JAVA? | [
"",
"java",
"nlp",
"text-mining",
""
] |
I have a table like this that stores messages coming through a system:
```
Message
-------
ID (bigint)
CreateDate (datetime)
Data (varchar(255))
```
I've been asked to calculate the messages saved per second at peak load. The only data I really have to work with is the CreateDate. The load on the system is not constant, there are times when we get a ton of traffic, and times when we get little traffic. I'm thinking there are two parts to this problem: 1. Determine ranges of time that are considered peak load, 2. Calculate the average messages per second during these times.
Is this the right approach? Are there things in SQL that can help with this? Any tips would be greatly appreciated. | I don't think you'd need to know the peak hours; you can generate them with SQL, wrapping a the full query and selecting the top 20 entries, for example:
```
select top 20 *
from (
[...load query here...]
) qry
order by LoadPerSecond desc
```
[This answer](https://stackoverflow.com/questions/876842/how-to-find-the-average-time-difference-between-rows-in-a-table/877051#877051) had a good lesson about averages. You can calculate the load per second by looking at the load per hour, and dividing by 3600.
To get a first glimpse of the load for the last week, you could try (Sql Server syntax):
```
select datepart(dy,createdate) as DayOfYear,
hour(createdate) as Hour,
count(*)/3600.0 as LoadPerSecond
from message
where CreateDate > dateadd(week,-7,getdate())
group by datepart(dy,createdate), hour(createdate)
```
To find the peak load per minute:
```
select max(MessagesPerMinute)
from (
select count(*) as MessagesPerMinute
from message
where CreateDate > dateadd(days,-7,getdate())
group by datepart(dy,createdate),hour(createdate),minute(createdate)
)
```
Grouping by datepart(dy,...) is an easy way to distinguish between days without worrying about month borders. It works until you select more that a year back, but that would be unusual for performance queries. | I agree, you have to figure out what Peak Load is first before you can start to create reports on it.
The first thing I would do is figure out how I am going to define peak load. Ex. Am I going to look at an hour by hour breakdown.
Next I would do a group by on the CreateDate formated in seconds (no milleseconds). As part of the group by I would do an avg based on number of records. | SQL: Calculating system load statistics | [
"",
"sql",
"statistics",
"load",
""
] |
If you have 2 functions like:
```
def A
def B
```
and A calls B, can you get who is calling B inside B, like:
```
def A () :
B ()
def B () :
this.caller.name
``` | You can use the [inspect](http://docs.python.org/library/inspect.html) module to get the info you want. Its [stack](https://docs.python.org/3.5/library/inspect.html#the-interpreter-stack) method returns a list of frame records.
* For **Python 2** each frame record is a list. The third element in each record is the caller name. What you want is this:
```
>>> import inspect
>>> def f():
... print inspect.stack()[1][3]
...
>>> def g():
... f()
...
>>> g()
g
```
---
* For **Python 3.5+**, each frame record is a [named tuple](https://docs.python.org/3.5/glossary.html#term-named-tuple) so you need to replace
```
print inspect.stack()[1][3]
```
with
```
print(inspect.stack()[1].function)
```
on the above code. | There are two ways, using `sys` and `inspect` modules:
* `sys._getframe(1).f_code.co_name`
* `inspect.stack()[1][3]`
The `stack()` form is less readable and is implementation dependent since it calls `sys._getframe()`, see extract from `inspect.py`:
```
def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context)
``` | Getting the caller function name inside another function in Python? | [
"",
"python",
"debugging",
""
] |
Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces,
```
[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')]
```
I want to read the lines in. Now I can read them in, and operate on the string to assign values and types but I was wondering if Python had a higher level method for this.
After building a function to do this I tried to find a higher level approach but didn't find one. | What you are looking for is [eval](http://docs.python.org/library/functions.html#eval). But please keep in mind that this function will evaluate and execute the lines. So don't run it on untrusted input ever!
```
>>> print eval("[('tupleValueA', 1), 'someString']")
[('tupleValueA', 1), 'someString']
```
If you have control over the script that generate the output file, then I would suggest you use [json](http://docs.python.org/library/json.html) encoding. JSON format is very similar to the python string representation of lists and dictionaries. And will be much more secure and robust to read from.
```
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar": ["baz", null, 1.0, 2]}]')
["foo", {"bar": ["baz", null, 1.0, 2]}]
``` | The problem you describe is conventionally referred to as [serialization](http://en.wikipedia.org/wiki/Serialization). [JavaScript Object Notation (JSON)](http://en.wikipedia.org/wiki/JSON) is one popular serialization protocol. | Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents? | [
"",
"python",
"string",
"tuples",
""
] |
I'm starting Django development, and I can either install it from the .deb using
```
$ apt-get install python-django
```
on my Ubuntu machine, or I can download the .tar.gz from [djangoproject.com](http://djangoproject.com), and start with that.
What are the benefits and drawbacks of each approach? | Using `apt-get` lets your system keep track of the install (e.g. if you want to disinstall, upgrade, or the like, late). Installing from source (`.tar.gz` or otherwise) puts you in charge of what's what and where -- you can have multiple versions installed at various locations, etc, but there's no easy "uninstall" and the like. Personally I prefer to install by my OS's supported method (`apt-get` and the like) for packages I think as secondary or auxiliary, directly from svn/hg/&c for ones I'm contributing to or otherwise want to keep the closest control on, and `.tar.gz` (or better when available `.tar.bz2`;-) "snapshots" and "source releases" that are s/where in the middle... | The best way to install is to check out the code, which ever the changeset (branch/tag) you want, and define a symbolic link to it
Checkout the version you want:
```
# For trunk
svn co http://code.djangoproject.com/svn/django/trunk/ django-trunk
# For a tag, 1.02 release
svn co http://code.djangoproject.com/svn/django/tag/1.02 django-1.02
# To update the trunk
cd django-trunk
svn up
```
Then define symbolic link
```
ln -fs /usr/lib/python2.5/site-packages/django/* ~/django-1.02/
```
If you want to test your code in the latest release, just redefine the symbolic link:
```
ln -fs /usr/lib/python2.5/site-packages/django/* ~/django-trunk/
```
The package managers aptitude and apt-get are good for auto updating those software you don't really bother about developing with every day, like media players, browsers. For stuff U code with everyday, full control of versions is needed, you get that only by source. | Benefit of installing Django from .deb versus .tar.gz? | [
"",
"python",
"django",
"ubuntu",
"apt-get",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.