Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to parse a CSV file using Python's `csv` module (specifically, the `DictReader` class). Is there a Pythonic way to detect empty or missing fields and throw an error?
Here's a sample file using the following headers: NAME, LABEL, VALUE
```
foo,bar,baz
yes,no
x,y,z
```
When parsing, I'd like the second line to throw an error since it's missing the VALUE field.
Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):
```
import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
```
Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of `if` statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible. | ```
if any(row[key] in (None, "") for key in row):
# raise error
```
**Edit**: Even better:
```
if any(val in (None, "") for val in row.itervalues()):
# raise error
``` | Since `None` and empty strings both evaluate to `False`, you should consider this:
```
for row in reader:
for header in HEADERS:
if not row[header]:
# raise error
```
Note that, unlike some other answers, you will still have the option of raising an informative, header-specific error. | How do I detect missing fields in a CSV file in a Pythonic way? | [
"",
"python",
"error-handling",
"csv",
""
] |
In my code i am using addslashes to escape certain characters while inserting them into the database and when i send some information out i use stripslashes to remove those slashes, the situation is stripslashes function removes all the slashes so if i need to send any string which has backslashes those also get removed. How can i retain those required slashes.
Any help will be greatly appreciate. | You might want to try using [mysql\_real\_escape\_string](http://us.php.net/mysql_real_escape_string). You don't have to unescape it, and it is safe for database use.
Better yet, use [prepared statements](http://us.php.net/mysqli_prepare) | You can try using PDO prepared statements when inserting to database so you don't need to worry about escaping anything. | Escaping using slashes and then using stripslashes PHP | [
"",
"php",
""
] |
I have tried very hard but cannot find a solution on how to set session timeout value for in-process session for an ASP.Net web application.
I am using VSTS 2008 + .Net 3.5 + C#. Here is what I wrote by myself to set timeout to be 1 minute, is it correct?
I wrote under system.web section in the `web.config`
```
<sessionState timeout="1" mode="InProc" />
``` | If you want to set the timeout to 20 minutes, use something like this:
```
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
``` | The value you are setting in the `timeout` attribute is the one of the correct ways to set the session timeout value.
The `timeout` attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.
By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.
To test this, create a simple aspx page, and write this code in the Page\_Load event,
```
Response.Write(Session.SessionID);
```
Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.
Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -
```
Session["UserId"] = 1;
```
Now, you will have to perform a check on every page for this variable like this -
```
if(Session["UserId"] == null)
Response.Redirect("login.aspx");
```
This is a bare-bones example of how this will work.
But, for making your production quality secure apps, use [Roles & Membership](https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx) classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use. | How to set session timeout in web.config | [
"",
"c#",
"asp.net",
".net",
"session",
"visual-studio-2008",
""
] |
Is there any way of instructing a web browser to completely **delete** one's cookie set with PHP?
I do not want to *expiry* it or wait for the browser to be *closed*.
With delete I mean to actually not have it listed inside the cookie's list anymore. | You cannot force the browser to delete the file associated with any cookie, because you can't guarantee there's actually such a file - the contract between browser and web server regarding cookies is that the data will be presented at eligible requests.
You state that you "don't want to wait for the cookie to expire", but cookie expiration is the correct method for indicating that the data is no longer needed and should not be presented on future requests, which in most cases does translate to the browser removing the file.
To delete a cookie, therefore, set its expiration time into the past. In PHP, this is done with [`setcookie()`](http://us.php.net/setcookie). | Try something like this to delete all cookies:
```
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1);
}
```
The value `1` is the *expire* value and it represents one second after the begin of the Unix time epoch. So it’s always already expired. | Delete cookie from browser? | [
"",
"php",
"http",
"browser",
"cookies",
""
] |
I'm trying to get all of my checkboxes to be checked when clicking a link
looks like this: `<a href='javascript:;' onclick="$.overall.selectAll();">select all</a>`
inputs in a loop: `<input type="checkbox" name="delete[$i]" value="1" />`
jquery code:
```
var checked_status = this.checked;
$("input[name=delete]").each(function() {
this.checked = checked_status;
});
```
Can someone help me get it to check all.. ?
When clicking at the select all link, nothing seems to happen.. (not even an error) | Try the following.
Updated. The handler is tied to an anchor therefore there will be no this.checked attribute available.
```
$("#select_all").click(function(){
$("input[name^=delete]").attr('checked', 'checked');
});
``` | jQuery Tutorial: [Select All Checkbox](http://jetlogs.org/jquery/jquery_select_all.html) | select all checkboxes command jquery, javascript | [
"",
"javascript",
"jquery",
""
] |
This question is related to a Windows install of PHP5.
Doing a file `unlink()` makes it difficult for recovery.
Instead I would like to move the file to the Recycle Bin (without doing an `exec()`).
Do you have any idea?
Thanks for your help. | This is the only solution that works and it's portable in all drives.
```
function Recycle($filename)
{
if (is_file($filename) === true)
{
$filename = realpath($filename);
$recycle = glob(current(explode('\\', $filename, 2)) . '\\RECYCLER\\*', GLOB_ONLYDIR);
if (is_array($recycle) === true)
{
return rename($filename, current($recycle) '\\' . basename($filename));
}
}
return false;
}
```
Deleted files are correctly moved to for instance:
```
O:\RECYCLER\S-1-5-21-1715567821-1390067357-1417001333-1003
```
Restore from the Recycle Bin should be possible, however I've not tested it.
**EDIT**: I just updated this function to work with files that have relative paths. | why dont you just create one folder and name it "Recycle Bin" .. then instead of doing an unlink() .. just move the files to this "Recycle Bin" folder??
If you wish to move a file, use the [rename()](http://uk.php.net/manual/en/function.rename.php) php function.
Then later you can run a cron script which checks the time of the files and then you can delete files, say, older than 10 days etc.
I hope this helps. | Moving a file to the Recycle Bin (PHP) | [
"",
"php",
"windows",
"file",
""
] |
I am using a WPF Popup, but it popups up above every single window on my desktop, even when my application is minimized. How can I make it stay only on the window it originated? The same thing happens when my window is behind other windows: the popup displays above them all.
"There must be something can be done!"
Thanks. | I've tried to solve this issue as well, and have found no good solution. This seems to be the way it is supposed to work, and you can't override that.
The only solution I've come up with is to just use a regular layout panel and raise it's Z-Index, so it is the top-level control (this sort of simulates the Popup). The only time I have found that this won't work is when you have WinForms on the screen through WindowsFormsHosts. Those Winforms are always at a higher Z-Index than any of the WPF stuff. That is when you have to use a Popup to get around it. | So I dug through the framework source code to see where it actually causes the window to be topmost and it does this in a private nested class. However, it does not provide an option to either just be a child popup of the main window or to be the topmost window. Here is a hack to make it always a child popup window. One could easily add a dependency property and do some more magic to make it the top most.
```
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace UI.Extensions.Wpf.Controls
{
public class ChildPopup : Popup
{
static ChildPopup()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ChildPopup), new FrameworkPropertyMetadata(typeof(ChildPopup)));
}
public ChildPopup()
{
Type baseType = this.GetType().BaseType;
dynamic popupSecHelper = GetHiddenField(this, baseType, "_secHelper");
SetHiddenField(popupSecHelper, "_isChildPopupInitialized", true);
SetHiddenField(popupSecHelper, "_isChildPopup", true);
}
protected dynamic GetHiddenField(object container, string fieldName)
{
return GetHiddenField(container, container.GetType(), fieldName);
}
protected dynamic GetHiddenField(object container, Type containerType, string fieldName)
{
dynamic retVal = null;
FieldInfo fieldInfo = containerType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
retVal = fieldInfo.GetValue(container);
}
return retVal;
}
protected void SetHiddenField(object container, string fieldName, object value)
{
SetHiddenField(container, container.GetType(), fieldName, value);
}
protected void SetHiddenField(object container, Type containerType, string fieldName, object value)
{
FieldInfo fieldInfo = containerType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
fieldInfo.SetValue(container, value);
}
}
}
}
``` | WPF Popup ZOrder | [
"",
"c#",
"wpf",
"xaml",
"z-order",
""
] |
I'm attempting to capture an event on a GTK window when the window is moved. I'm doing so with something that looks like this:
```
void mycallback(GtkWindow* parentWindow, GdkEvent* event, gpointer data)
{
// do something...
}
...
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_add_events(GTK_WIDGET(window), GDK_CONFIGURE);
g_signal_connect_(G_OBJECT(window), "configure-event", G_CALLBACK(mycallback), NULL);
...
```
This works- the event is properly called when the window is moved... but it's also called when the window is resized. This has the side effect of not resizing the window's sub-elements as they would if I didn't connect the event.
According to [this table](http://developer.gnome.org/doc/GGAD/sec-gdkevent.html#TAB-WIDGETEVENTS) in the GTK docs, the GDK\_CONFIGURE event does not propagate. If the event does not propagate, how can I still detect the window's movement while allowing it to resize properly?
note: I'm using GTK version 2.12.9 | Luke, as you have discovered, returning FALSE allows the event to propagate. This is explained in the gtk tutorial [here](http://www.gtk.org/tutorial1.2/gtk_tut-2.html) | Neuro- I didn't believe that would work because the function signature returned void rather than gboolean. For grins, I changed:
```
void mycallback(GtkWindow* parentWindow, GdkEvent* event, gpointer data)
```
to
```
gboolean mycallback(GtkWindow* parentWindow, GdkEvent* event, gpointer data)
```
I would have thought this would cause a type-mismatch with the callback types, but it does not. Returning TRUE like you suggested doesn't work... but strangely returning FALSE does. This being the case, it appears that the event *can* propagate.
---
**Edit:**
According to the [GTK tutorial](http://www.gtk.org/tutorial1.2/gtk%5Ftut-2.html) (thanks Matt):
> The value returned from this function
> indicates whether the event should be
> propagated further by the GTK event
> handling mechanism. Returning TRUE
> indicates that the event has been
> handled, and that it should not
> propagate further. Returning FALSE
> continues the normal event handling. | GTK Window configure events not propagating | [
"",
"c++",
"c",
"events",
"gtk",
""
] |
I would like to register to some event. The following ways works:
```
public void AddOptionAsListner(OptionElement option)
{
option.Selected += onOptionSelectedChanged;
}
public void AddOptionAsListner(OptionElement option)
{
option.Selected += new EventHandler(onOptionSelectedChanged);
}
```
Is there a difference or that this is just different syntax for the same thing? | Same - No diff. The compiler infers the type of delegate and does it auto-magically for you. Syntactic sugar to make your life a bit easier
Just checked with C#-in depth. This feature is called "**Method group conversions**" ; added in C#2.0
e.g. from the book
```
static void MyMethod() { ... }
static void MyMethod( object sender, EventArgs e) {...}
static void Main() {
ThreadStart x = MyMethod; // binds to first overload
EventHandler y = MyMethod; // binds to second overload
}
```
If I open this up in reflector, you'd see that the compiler just created the delegate instances of the right type for you, behind the scenes of course.
```
L_0000: ldnull
L_0001: ldftn void CS.Temp.Program::MyMethod()
L_0007: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int)
L_000c: pop
L_000d: ldnull
L_000e: ldftn void CS.Temp.Program::MyMethod(object, class [mscorlib]System.EventArgs)
L_0014: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int)
L_0019: pop
``` | It's the same thing, the new EventHandler() is just redundant.
You don't need to explicitly create a delegate for an event handler. | Is there a difference between the following ways to register to event | [
"",
"c#",
".net",
"c#-3.0",
""
] |
Could anyone please what the following is saying about instance and object:
> If class is the general representation
> of an object, an instance is its
> concrete representation.
I know concrete means non-abstract. So what's actually **general representation** and **concrete representation**? | Car is a general representation having attributes (wheels, doors, colour, etc) and behaviour (start, stop, brake, accelerate, change gears, etc), also called a class.
Bob's Ford Focus (red, license plate LH 12 233) is an instance of class Car, also called an object. | My best advise would be to drop the dictionary.. looking up what concrete means and than trying to apply the definition to understanding what an author meant when he or she used *concrete representation* to describe an instance of an object is just wrong.
Look for other explanations of what objects, classes and instances of objects are, and I'm sure you'll find many with great examples.
Basically you could think of the class as a "*recipe*" or as a "*template*" (although I'm reluctant to say template for fear of causing confusion) and an instance as an "*embodiment*" of said recipe or template.. hence the concrete representation.
So you have the following, which is a class (the recipe):
```
class Human
{
private string Name;
private int Age;
public void SayHello()
{
// run some code to say hello
}
public Human(string name, int age)
{
Name = name;
Age = age;
}
}
```
And these are instances (objects)..
```
Human mike = new Human("Mike", 28);
Human jane = new Human("Jane", 20);
Human adam = new Human("Adam", 18);
```
They are embodiments, or concrete representations of our Human class. | Confusion in line about the difference between instance and object in context of Java | [
"",
"java",
"oop",
""
] |
When using `subprocess.Popen(args, shell=True)` to run "`gcc --version`" (just as an example), on Windows we get this:
```
>>> from subprocess import Popen
>>> Popen(['gcc', '--version'], shell=True)
gcc (GCC) 3.4.5 (mingw-vista special r3) ...
```
So it's nicely printing out the version as I expect. But on Linux we get this:
```
>>> from subprocess import Popen
>>> Popen(['gcc', '--version'], shell=True)
gcc: no input files
```
Because gcc hasn't received the `--version` option.
The docs don't specify exactly what should happen to the args under Windows, but it does say, on Unix, *"If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments."* IMHO the Windows way is better, because it allows you to treat `Popen(arglist)` calls the same as `Popen(arglist, shell=True)` ones.
**Why the difference between Windows and Linux here?** | Actually on Windows, it does use `cmd.exe` when `shell=True` - it prepends `cmd.exe /c` (it actually looks up the `COMSPEC` environment variable but defaults to `cmd.exe` if not present) to the shell arguments. (On Windows 95/98 it uses the intermediate `w9xpopen` program to actually launch the command).
So the strange implementation is actually the `UNIX` one, which does the following (where each space separates a different argument):
```
/bin/sh -c gcc --version
```
It looks like the correct implementation (at least on Linux) would be:
```
/bin/sh -c "gcc --version" gcc --version
```
Since this would set the command string from the quoted parameters, and pass the other parameters successfully.
From the `sh` man page section for `-c`:
> `Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands.`
This patch seems to fairly simply do the trick:
```
--- subprocess.py.orig 2009-04-19 04:43:42.000000000 +0200
+++ subprocess.py 2009-08-10 13:08:48.000000000 +0200
@@ -990,7 +990,7 @@
args = list(args)
if shell:
- args = ["/bin/sh", "-c"] + args
+ args = ["/bin/sh", "-c"] + [" ".join(args)] + args
if executable is None:
executable = args[0]
``` | From the subprocess.py source:
> On UNIX, with shell=True: If args is a string, it specifies the
> command string to execute through the shell. If args is a sequence,
> the first item specifies the command string, and any additional items
> will be treated as additional shell arguments.
>
> On Windows: the Popen class uses CreateProcess() to execute the child
> program, which operates on strings. If args is a sequence, it will be
> converted to a string using the list2cmdline method. Please note that
> not all MS Windows applications interpret the command line the same
> way: The list2cmdline is designed for applications using the same
> rules as the MS C runtime.
That doesn't answer why, just clarifies that you are seeing the expected behavior.
The "why" is probably that on UNIX-like systems, command arguments are actually passed through to applications (using the `exec*` family of calls) as an array of strings. In other words, the calling process decides what goes into EACH command line argument. Whereas when you tell it to use a shell, the calling process actually only gets the chance to pass a single command line argument to the shell to execute: The entire command line that you want executed, executable name and arguments, as a single string.
But on Windows, the entire command line (according to the above documentation) is passed as a single string to the child process. If you look at the [CreateProcess](http://msdn.microsoft.com/en-us/library/ms682425%28VS.85%29.aspx) API documentation, you will notice that it expects all of the command line arguments to be concatenated together into a big string (hence the call to `list2cmdline`).
Plus there is the fact that on UNIX-like systems there actually *is* a shell that can do useful things, so I suspect that the other reason for the difference is that on Windows, `shell=True` does nothing, which is why it is working the way you are seeing. The only way to make the two systems act identically would be for it to simply drop all of the command line arguments when `shell=True` on Windows. | Why does subprocess.Popen() with shell=True work differently on Linux vs Windows? | [
"",
"python",
"shell",
"subprocess",
"popen",
""
] |
```
public class StatisticsViewPresenter
{
private IStatisticsView view;
private Statistics statsModel;
public StatisticsViewPresenter(IStatisticsView view, Statistics statsModel)
{
this.view = view;
this.statsModel = statsModel;
}
}
```
I don't use events (but am willing to if it can solve my problem), so my View classes look like this:
```
public class StatisticsForm : Form, IStatisticsView
{
public StatisticsForm()
{
InitializeComponent();
}
[Inject]
public StatisticsViewPresenter Presenter
{
private get;
set;
}
}
```
With
```
kernel.Bind<StatisticsPresenter>().ToSelf().InSingletonScope();
kernel.Bind<IStatisticsView>().To<StatisticsForm>();
kernel.Get<IStatisticsView>();
```
it builds up the Form, builds up the presenter, then injects the presenter into the Presenter property. Everything's peachy. (Except for that singleton-scoped presenter--any thoughts on a better way to do that? Perhaps just manually inject the presenter into the view's Presenter property inside the presenter's constructor: this.view.Presenter = this).
But if I turn StatisticsForm into StatisticsUserControl and drag-drop it onto my MainForm, it's not being injected into MainForm by Ninject, it's simply being new'd by the Designer. I see three solutions here:
1) Don't use UserControls and just use one giant form that implements these multiple views (eww);
2) Inject UserControls into my form and lose Designer support;
3) Your solution! :) | This is certainly an interesting area of, should I say, research. We've made ourselves a solution where we host user controls in a generic form.
Our generic form is not intended for use with the Designer. Through code we add the chosen user control to the Form dynamically.
For other frameworks you should look at [Prism/Composite](http://msdn.microsoft.com/en-us/library/cc707819.aspx) from the Microsoft Patterns & Practices group. [Here's an article](http://www.softinsight.com/bnoyes/2008/10/13/CompositeExtensionsForWindowsForms.aspx) discussing extensions for WinForms. | My approach to use Ninject with forms, usercontrols and the designer is:
* Use factories to create the forms (also for the usercontrols if you create some controls dinamically)
* for the usercontrols and the forms keep the constructors without parameters and use property injection
* add an [Activation strategy](https://github.com/ninject/Ninject/wiki/Component-Extension-Points#iactivationstrategy) to the kernel that check if ninject has just created a form or a usercontrol. If that is the case, the activation strategy iterates over the controls in the Controls property of the UserControl (or the Form) and calls Kernel.Inject(UserControl) for each usercontrol. (An Activation strategy is some code ninject executes after it has injected an object)
You can use the designer and have forms and usercontrols with dependencies injected via Ninject.
The only drawback is that you have to use property injection instead of constructor injection for the usercontrols (and the forms)
```
namespace Majiic.Ninject
{
public class WindowsFormsStrategy : ActivationStrategy
{
// Activate is called after Kernel.Inject
//even for objects not created by Ninject
//To avoid multiple "injections" in the same nested controls
//we put this flag to false.
private bool _activatingControls = false;
public override void Activate(IContext context, InstanceReference reference)
{
reference.IfInstanceIs<UserControl>(uc =>
{
if (!_activatingControls)
{
Trace.TraceInformation("Activate. Injecting dependencies in User control of type {0}", uc.GetType());
_activatingControls = true;
context.Kernel.InjectDescendantOf(uc);
_activatingControls = false;
}
});
reference.IfInstanceIs<Form>(form =>
{
if (!_activatingControls)
{
Trace.TraceInformation("Activate. Injecting dependencies in Form of type {0}", form.GetType());
_activatingControls = true;
context.Kernel.InjectDescendantOf(form);
_activatingControls = false;
}
});
}
}
}
```
Create the kernel and add the Activation Strategy
```
var kernel=new StandardKernel(new CommonMajiicNinjectModule());
kernel.Components.Add<IActivationStrategy, WindowsFormsStrategy>();
```
kernel extensions to iterate over descendents controls
```
namespace Majiic.Ninject
{
static public class WinFormsInstanceProviderAux
{
static public void InjectDescendantOf(this IKernel kernel, ContainerControl containerControl)
{
var childrenControls = containerControl.Controls.Cast<Control>();
foreach (var control in childrenControls )
{
InjectUserControlsOf(kernel, control);
}
}
static private void InjectUserControlsOf(this IKernel kernel, Control control)
{
//only user controls can have properties defined as n-inject-able
if (control is UserControl)
{
Trace.TraceInformation("Injecting dependencies in User Control of type {0}", control.GetType());
kernel.Inject(control);
}
//A non user control can have children that are user controls and should be n-injected
var childrenControls = control.Controls.Cast<Control>();
foreach (var childControl in childrenControls )
{
InjectUserControlsOf(kernel, childControl );
}
}
}
}
``` | How to apply dependency injection to UserControl views while keeping Designer happy? | [
"",
"c#",
"dependency-injection",
"user-controls",
"ninject",
"windows-forms-designer",
""
] |
I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing [Kaprekar's constant](http://en.wikipedia.org/wiki/6174).
It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google that could help me. A site I found tried to explain a way using lists, but it didn't work out very well. | Sort the digits in ascending and descending orders:
```
ascending = "".join(sorted(str(number)))
descending = "".join(sorted(str(number), reverse=True))
```
Like this:
```
>>> number = 5896
>>> ascending = "".join(sorted(str(number)))
>>>
>>> descending = "".join(sorted(str(number), reverse=True))
>>> ascending
'5689'
>>> descending
'9865'
```
And if you need them to be numbers again (not just strings), call `int()` on them:
```
>>> int(ascending)
5689
>>> int(descending)
9865
```
---
2020-01-30
```
>>> def kaprekar(number):
... diff = None
... while diff != 0:
... ascending = "".join(sorted(str(number)))
... descending = "".join(sorted(str(number), reverse=True))
... print(ascending, descending)
... next_number = int(descending) - int(ascending)
... diff = number - next_number
... number = next_number
...
>>> kaprekar(2777)
2777 7772
4599 9954
3555 5553
1899 9981
0288 8820
2358 8532
1467 7641
``` | ```
>>> x = [4,5,81,5,28958,28] # first list
>>> print sorted(x)
[4, 5, 5, 28, 81, 28958]
>>> x
[4, 5, 81, 5, 28958, 28]
>>> x.sort() # sort the list in place
>>> x
[4, 5, 5, 28, 81, 28958]
>>> x.append(1) # add to the list
>>> x
[4, 5, 5, 28, 81, 28958, 1]
>>> sorted(x)
[1, 4, 5, 5, 28, 81, 28958]
```
As many others have pointed out, you can sort a number forwards like:
```
>>> int(''.join(sorted(str(2314))))
1234
```
That's pretty much the most standard way.
Reverse a number? Doesn't work well in a number with trailing zeros.
```
>>> y = int(''.join(sorted(str(2314))))
>>> y
1234
>>> int(str(y)[::-1])
4321
```
The `[::-1]` notation indicates that the iterable is to be traversed in reverse order. | How to sort digits in a number? | [
"",
"python",
"numbers",
""
] |
Is there a FREE (or relatively cheaper) Java GUI designer/builder? | I highly recommend [NetBeans](http://www.netbeans.org/)'s Matisse GUI editor. | Unfortunately, it looks like the Eclipse Visual Editor has not been maintained or developed a lot the past three years. On the [Visual Editor homepage](http://www.eclipse.org/vep/WebContent/main.php) you'll see that the last release is from June 30, 2006 - more than three years ago.
The best free GUI builder for Java at the moment is probably Matisse which is included in NetBeans, as others have already mentioned.
If you're an Eclipse user, then there's also [Matisse4MyEclipse](http://www.myeclipseide.com/index.php?module=htmlpages&func=display&pid=5), but it is not free - it's an add-on to the popular MyEclipse. Another non-free option for Eclipse is [WindowBuilder Pro](http://www.instantiations.com/windowbuilder/), which is not only for Swing, but also for SWT and even GWT GUIs. | Is there a FREE Java GUI designer? | [
"",
"java",
"swing",
"open-source",
"gui-designer",
""
] |
This should be very simple (when you know the answer). From [this question](https://stackoverflow.com/questions/412467/how-to-embed-youtube-videos-in-php)
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
```
http://www.youtube.com/watch?v=Ahg6qcgoay4
```
I need:
```
Ahg6qcgoay4
```
I tried:
```
http://www.youtube.com/watch\\?v=(w{11})
```
But: I suck... | You almost had it, just need to escape special regex chars:
```
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
```
**Edit:** Fix for regex by [soupagain](https://stackoverflow.com/questions/1280557/extract-parameter-value-from-url-using-regular-expressions#comment2200253_1280572). | Why dont you take the string and split it
Example on the url
```
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
```
you can do a split as
```
var params = url.split("?")[1].split("&");
```
You will get array of strings with params as name value pairs with "=" as the delimiter. | Extract parameter value from url using regular expressions | [
"",
"javascript",
"regex",
"url",
""
] |
I know this is subjective, but I'd like to know peoples opinions and hopefully some best practices that I can apply when designing sql server table structures.
I personally feel that keying a table on a fixed (max) length varchar is a no-no, because it means having to also propogate the same fixed length across any other tables that use this as a foreign key. Using an `int`, would avoid having to apply the same length across the board, which is bound to lead to human error, i.e. 1 table has `varchar (10)`, and the other `varchar (20)`.
This sounds like a nightmare to initially setup, plus means future maintaining of the tables is cumbersome too. For example, say the keyed varchar column suddenly becomes 12 chars instead of 10. You now have to go and update all the other tables, which could be a huge task years down the line.
Am I wrong? Have I missed something here? I'd like to know what others think of this and if sticking with int for primary keys is the best way to avoid maintainace nightmares. | I would definitely recommend using an `INT NOT NULL IDENTITY(1,1)` field in each table as the
primary key.
With an IDENTITY field, you can let the database handle all the details of making sure it's really unique and all, and the INT datatype is just 4 bytes, and fixed, so it's easier and more suited to be used for the primary (and clustering) key in your table.
And you're right - INT is an INT is an INT - it will not change its size of anything, so you won't have to ever go recreate and/or update your foreign key relations.
Using a VARCHAR(10) or (20) just uses up too much space - 10 or 20 bytes instead of 4, and what a lot of folks don't know - the clustering key value will be repeated on every single index entry on every single non-clustered index on the table, so potentially, you're wasting a lot of space (not just on disk - that's cheap - but also in SQL Server's main memory). Also, since it's variable (might be 4, might be 20 chars) it's harder to SQL server to properly maintain a good index structure.
Marc | When choosing the primary key usualy you also choose the clustered key. Them two are often confused, but you have to understand the difference.
**Primary keys** are logical *business* elements. The primary key is used by your application to identify an entity, and the discussion about primary keys is largely wether to use [natural keys](http://en.wikipedia.org/wiki/Natural_key) or [surrogate key](http://en.wikipedia.org/wiki/Surrogate_key). The links go into much more detail, but the basic idea is that natural keys are derived from an existing entity property like `ssn` or `phone number`, while surrogate keys have no meaning whatsoever with regard to the business entity, like `id` or `rowid` and they are usually of type `IDENTITY` or some sort of uuid. My personal opinion is that surrogate keys are superior to natural keys, and the choice should be always identity values for local only applicaitons, guids for any sort of distributed data. A primary key never changes during the lifetime of the entity.
**Clustered keys** are the key that defines the physical storage of rows in the table. Most times they overlap with the primary key (the logical entity identifier), but that is not actually enforced nor required. When the two are different it means there is a non-clustered unique index on the table that implements the primary key. Clustered key values can actualy change during the lifetime of the row, resulting in the row being physically moved in the table to a new location. If you have to separate the primary key from the clustered key (and sometimes you do), choosing a good clustered key is significantly harder than choosing a primary key. There are two primary factors that drive your clustered key design:
1. The prevalent **data access pattern**.
2. The **storage considerations**.
**Data Access Pattern**. By this I understand the way the table is queried and updated. Remember that clustered keys determine the actual order of the rows in the table. For certain access patterns, some layouts make all the difference in the world in regard to query speed or to update concurency:
* current vs. archive data. In many applications the data belonging to the current month is frequently accessed, while the one in the past is seldom accessed. In such cases the table design uses [table partitioning](http://msdn.microsoft.com/en-us/library/ms188706.aspx) by transaction date, often times using a [sliding window](http://msdn.microsoft.com/en-us/library/aa964122(SQL.90).aspx) algorithm. The current month partition is kept on filegroup located a hot fast disk, the archived old data is moved to filegroups hosted on cheaper but slower storage. Obviously in this case the clustered key (date) is not the primary key (transaction id). The separation of the two is driven by the scale requirements, as the query optimizer will be able to detect that the queries are only interested in the current partition and not even look at the historic ones.
* FIFO queue style processing. In this case the table has two hot spots: the tail where inserts occur (enqueue), and the head where deletes occur (dequeue). The clustered key has to take this into account and organize the table as to physically separate the tail and head location on disk, in order to allow for concurency between enqueue and dequeue, eg. by using an enqueue order key. In *pure* queues this clustered key is the only key, since there is no primary key on the table (it contains *messages*, not *entities*). But most times the queue is not pure, it also acts as the storage for the entities, and the line between the *queue* and the *table* is blured. In this case there is also a primary key, which cannot be the clustered key: entities may be re-enqueued, thus changing the enqueue order clustered key value, but they cannot change the primary key value. Failure to see the separation is the primary reason why user table backed queues are so notoriously hard to get right and riddled with deadlocks: because the enqueue and dequeue occur interleaved trought the table, instead of localized at the tail and the head of the queue.
* Correlated processing. When the application is well designed it will partition processing of correlated items between its worker threads. For instance a processor is designed to have 8 worker thread (say to match the 8 CPUs on the server) so the processors partition the data amongst themselves, eg. worker 1 picks up only accounts named A to E, worker 2 F to J etc. In such cases the table should be actually clustered by the account name (or by a composite key that has the leftmost position the first letter of account name), so that workers localize their queries and updates in the table. Such a table would have 8 distinct hot spots, around the area each worker concentrates at the moment, but the important thing is that they don't overlap (no blocking). This kind of design is prevalent on high throughput OLTP designs and in TPCC benchmark loads, where this kind of partitioning also reflects in the memory location of the pages loaded in the buffer pool (NUMA locality), but I digress.
**Storage Considerations**. The clustered key *width* has huge repercursions in the storage of the table. For one the key occupies space in every non-leaf page of the b-tree, so a large key will occupy more space. Second, and often more important, is that the clustered key is used as the lookup key by every non-clustred key, so *every* non-clustered key will have to store the full width of the clustered key for each row. This is what makes large clustered keys like varchar(256) and guids poor choices for clustered index keys.
Also the choice of the key has impact on the clustered index fragmentation, sometimes drastically affecting performance.
These two forces can sometimes be antagonistic, the data access pattern requiring a certain large clustered key which will cause storage problems. In such cases of course a balance is needed, but there is no magic formula. You measure and you test to get to the sweet spot.
So what do we make from all this? **Always start with considering clustered key that is also the primary key of the form `entity_id IDENTITY(1,1) NOT NULL`**. Separate the two and organize the table accordingly (eg. partition by date) when appropiate. | Should I design a table with a primary key of varchar or int? | [
"",
"sql",
"sql-server",
"database-design",
""
] |
I am having trouble with my javascript. It seems to be acting oddly. This is what's going on. I have a form, after the user submits it, it calls a function(onsubmit event) to verify the submitted data, if something bad OR if the username/email is already in database(using ajax for this part) it'll return false and display errors using DOM. Here's the code below. What's weird about it, is that it only works when I use an empty alert('') message, without it, it just doesn't work. Thanks for the help.
```
//////////////////////////////////////
function httpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function validateRegForm(reg) {
var isValidForm = true;
var warningIcon = "";//for later in case we want to use an icon next to warning msg
with(reg) {
var regFormDiv = document.getElementById("registration_form");
//Check if dynamic div exist, if so, remove it
if(document.getElementById('disp_errors') != null) {
var dispErrorsDiv = document.getElementById('disp_errors');
document.getElementById('reg_form').removeChild(dispErrorsDiv);
}
//Dynamically create new 'div'
var errorDiv = document.createElement('div');
errorDiv.setAttribute('id','disp_errors');
errorDiv.setAttribute('style','background-color:pink;border:1px solid red;color:red;padding:10px;');
document.getElementById('reg_form').insertBefore(errorDiv,regFormDiv);
var xmlhttp = httpRequest();
var available = new Array();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4)
{
var response = xmlhttp.responseText;
if(response != "") {
//Return values
var newValue = response.split("|");
available[0] = newValue[0];
available[1] = newValue[1];
}
}
}
xmlhttp.open("GET","profile_fetch_reg_info.php?do=available&un="+u_username.value+"&email="+u_email.value+"",true);
xmlhttp.send(null);
alert(' '); ////////////WITHOUT THIS, IT DOESN'T WORK. Why?
if(available[1] == "taken") {
errorDiv.innerHTML += warningIcon+'Username is already taken!<br />';
isValidForm = false;
} else if(u_username.value.length < 4){
errorDiv.innerHTML += warningIcon+'Username must be more than 4 characters long!<br />';
isValidForm = false;
} else if(u_username.value.length > 35) {
errorDiv.innerHTML += warningIcon+'Username must be less than 34 characters long!<br />';
isValidForm = false;
}
if(available[0] == "taken") {
errorDiv.innerHTML += warningIcon+'Email address entered is already in use!<br />';
isValidForm = false;
} else if(u_email.value == ""){
errorDiv.innerHTML += warningIcon+'Email address is required!<br />';
isValidForm = false;
} else {
//Determine if email entered is valid
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(u_email.value)) {
errorDiv.innerHTML += warningIcon+'Email entered is invalid!<br />';
u_email.value = "";
isValidForm = false;
}
}
if(u_fname.value == ""){
errorDiv.innerHTML = warningIcon+'Your first name is required!<br />';
isValidForm = false;
}
if(u_lname.value == ""){
errorDiv.innerHTML += warningIcon+'Your last name is required!<br />';
isValidForm = false;
}
if(u_password.value.length < 4){
errorDiv.innerHTML += warningIcon+'Password must be more than 4 characters long!<br />';
isValidForm = false;
} else if(u_password.value.length > 35) {
errorDiv.innerHTML += warningIcon+'Password must be less than 34 characters long!<br />';
isValidForm = false;
} else if (u_password.value != u_password2.value) {
errorDiv.innerHTML += warningIcon+'Password and re-typed password don\'t match!<br />';
isValidForm = false;
}
if(u_squestion.value == ""){
errorDiv.innerHTML += warningIcon+'A security question is required!<br />';
isValidForm = false;
}
if(u_sanswer.value == ""){
errorDiv.innerHTML += warningIcon+'A security answer is required!<br />';
isValidForm = false;
}
if(u_address.value == ""){
errorDiv.innerHTML += warningIcon+'Address is required!<br />';
isValidForm = false;
}
if(u_city.value == ""){
errorDiv.innerHTML += warningIcon+'City is required!<br />';
isValidForm = false;
}
if(u_state.value == ""){
errorDiv.innerHTML += warningIcon+'State is required!<br />';
isValidForm = false;
}
if(u_zip.value == ""){
errorDiv.innerHTML += warningIcon+'Zip code is required!<br />';
isValidForm = false;
}
if(u_phone.value == ""){
errorDiv.innerHTML += warningIcon+'Phone number is required!<br />';
isValidForm = false;
}
if(isValidForm == false)
window.scroll(0,0);
return isValidForm;
}
}
``` | The `alert()` helps because that delays the processing of the remaining javascript in that function (everything from the `alert()` down to the bottom), leaving enough time for the AJAX request to complete. The first letter in AJAX stands for "asynchronous" which means that (by default) the response will come in at "some point in the future" but not immediately.
One fix (which you should *not* implement) is to make the processing synchronous (by changing the third argument of `open()` to be `false`) which will stop further processing of your script (and the entire webpage) until the request returns. This is bad because it will effectively freeze the web browser until the request completes.
The proper fix is to restructure your code so that any processing that depends on the result of the AJAX request goes in to the `onreadystatechange` function, and can't be in the main function that initiates the AJAX request.
The way this is usually handled is to modify your DOM (before the AJAX request is sent) to make the form readonly and display some sort of "processing" message, then in the AJAX response handler, if everything is okay (the server responded properly *and* validation was successful) call `submit()` on the form, otherwise make the form wriable again and display any validation errors. | The problem is that XMLHTTPRequest is asynchronous - it sends the request in the background and doesn't wait for it to finish.
The `alert` statement causes the code to wait until the user clicks OK, during which the request finishes.
You need to use the `onreadystatechange` event, like this:
```
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
// Do things
}
};
```
The method you assign to this property will be called after the response is received. (and at other times, which is why you need to check that `readyState` is 4) | Javascript and AJAX, only works when using alert() | [
"",
"javascript",
"ajax",
"alert",
""
] |
I have an image with letters in it, the letters are in two colors black and blue, I want to read the blue colored letters from the image.
Can anyone suggest me a method to do this in C#. Iam studying GDI+,but still didn't get any logic to develop this program..
I tried OCRing it, but the issue with common OCRs is that they dont recognize the color difference.
I only want to read the Blue characters....
Any guidance is highly appreciated. | Try this one ;) But that's unsafe code.
```
void RedAndBlue()
{
OpenFileDialog ofd;
int imageHeight, imageWidth;
if (ofd.ShowDialog() == DialogResult.OK)
{
Image tmp = Image.FromFile(ofd.FileName);
imageHeight = tmp.Height;
imageWidth = tmp.Width;
}
else
{
// error
}
int[,] bluePixelArray = new int[imageWidth, imageHeight];
int[,] redPixelArray = new int[imageWidth, imageHeight];
Rectangle rect = new Rectangle(0, 0, tmp.Width, tmp.Height);
Bitmap temp = new Bitmap(tmp);
BitmapData bmpData = temp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int remain = bmpData.Stride - bmpData.Width * 3;
unsafe
{
byte* ptr = (byte*)bmpData.Scan0;
for (int j = 0; j < bmpData.Height; j++)
{
for (int i = 0; i < bmpData.Width; i++)
{
bluePixelArray[i, j] = ptr[0];
redPixelArray[i, j] = ptr[2];
ptr += 3;
}
ptr += remain;
}
}
temp.UnlockBits(bmpData);
temp.Dispose();
}
``` | Modify the color of the image to gray scaled then use OCR
```
public Bitmap MakeGrayscale(Bitmap original)
{
//make an empty bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
for (int i = 0; i < original.Width; i++)
{
for (int j = 0; j < original.Height; j++)
{
//get the pixel from the original image
Color originalColor = original.GetPixel(i, j);
//create the grayscale version of the pixel
int grayScale = (int)((originalColor.R * .3) + (originalColor.G * .59)
+ (originalColor.B * .11));
//create the color object
Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
//set the new image's pixel to the grayscale version
newBitmap.SetPixel(i, j, newColor);
}
}
return newBitmap;
}
``` | Image Processing in C# - A smart solution? | [
"",
"c#",
"image-processing",
"image-manipulation",
""
] |
I'm building a .NET DLL Class Library which depends on other libraries such as log4net.dll - where should I put these DLLs when packaging up my DLL? Is there a way to automatically include them inside one super-DLL? Should I just ship all the DLLs in a single bin folder? | Just ship them all in a directory with your dll (assuming you're talking about a binary distribution - in a source distribution I'd have a "lib" directory containing your dependencies).
Don't forget to check whether or not you need to also supply licences, directions to get the source etc.
I wouldn't be tempted to try to merge your class library with the dependencies, personally. | You need to check the EULA and other licenses attached to those other DLL's first. Some may restrict how their DLL libraries are redestributed. Assuming no issues with that, you can either compile them all together as one big DLL, or create an installer (or a simple zip file) that will install all the associated DLL's in their intended destination. | How/where do I ship third-party libraries with a .NET DLL? | [
"",
"c#",
".net",
"dll",
"packaging",
""
] |
pretty straightforward question actually..
> **is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?**
I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?
```
function Combine($array1, $array2) {
if(count($array1) == count($array2)) {
$assArray = array();
for($i=0;$i<count($array1);$i++) {
$assArray[$array1[$i]] = $array2[$i];
}
return $assArray;
}
}
``` | [`array_combine($keys, $values)`](https://www.php.net/manual/en/function.array-combine.php)
PS: Click on my answer! Its also a link! | you need [array\_combine](http://www.php.net/manual/en/function.array-combine.php).
```
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
``` | PHP - Merge two arrays (same-length) into one associative? | [
"",
"php",
"arrays",
"merge",
"associative-array",
""
] |
i have made a serialized class,like this
`
```
class Example implements Serializable
{
transient byte i=2;
transient byte j=3;
Example(){System.out.println("value of i:"+i+",j:"+j);}
}
```
`
when i am serilizing n deserializing the class,i.e.
```
class SerialClass
{
public static void main(String []r)//throws IOException
{
try{
System.out.println("Serialization");
Example e=new Example();
FileOutputStream out=new FileOutputStream("hyxa_code.txt");
/*File f=new File("copt.txt");
f.createNewFile();*/
ObjectOutputStream oo=new ObjectOutputStream(out);
oo.writeObject(e);
oo.close();}catch(IOException e){}
try{
System.out.println("Deserialization");
Example ee=new Example();
FileInputStream in=new FileInputStream("hyxa_code.txt");
ObjectInputStream o=new ObjectInputStream(in);
ee=(Example)o.readObject();
System.out.println("The vlaue of i,j:"+ee.i+" "+ee.j);
}catch(IOException e)
{}
catch(ClassNotFoundException e){}
}
}
```
the output is coming like this:
```
Serialization
value of i:2,j:3
Deserialization
value of i:2,j:3
The vlaue of i,j:0 0
```
but as i have heard, Deserialization doesn't initialize constructor,
here is happening,why???
also,why the value of both variables is coming as it was initialized | You're explicitly calling the constructor twice - once to serialize and then once when deserializing:
```
Example ee=new Example();
FileInputStream in=new FileInputStream("hyxa_code.txt");
ObjectInputStream o=new ObjectInputStream(in);
ee=(Example)o.readObject();
System.out.println("The vlaue of i,j:"+ee.i+" "+ee.j);
```
You're ignoring the value you've created though, so the code is effectively like this:
```
FileInputStream in=new FileInputStream("hyxa_code.txt");
ObjectInputStream o=new ObjectInputStream(in);
Example ee=(Example)o.readObject();
System.out.println("The vlaue of i,j:"+ee.i+" "+ee.j);
```
The difference is just that this time you won't be calling the constructor unnecessarily.
That explains why you're seeing the "value of i:2,j:3" line twice. The reason that the deserialized objects have values of 0 is because you've declared the variables as `transient`, as described in the other answers. | Having the variables marked as transient keeps them from being serialized. Remove the transient part of the variable declaration and it will work.
And you are correct about the constructor not being invoked as part of deserialization. The state of the object is loaded directly from the stream and no constructor is invoked.
See <http://www.rockstarprogrammer.org/post/2006/jul/29/more_you_want_know_about_java_serialization/> for more information. The readObject method can be used to initialize transient variables when deserialization happens. | Java Serializable | [
"",
"java",
"serialization",
""
] |
I'm making [Braid](http://www.braid-game.com) in Java. If you rewind the time, the sound plays backward.
How can I play a WAV file backward? Maybe with a stream with something like `previous()`?
On the site of Braid can you see what I mean. | I solved it by myself
```
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
/**
*
* @author Martijn
*/
public class FrameBuffer {
private byte[][] frames;
private int frameSize;
public FrameBuffer(AudioInputStream stream) throws IOException {
readFrames(stream);
}
public byte[] getFrame(int i) {
return frames[i];
}
public int numberFrames()
{
return frames.length;
}
public int frameSize()
{
return frameSize;
}
private void readFrames(AudioInputStream stream) throws IOException {
frameSize = stream.getFormat().getFrameSize();
frames = new byte[stream.available() / frameSize][frameSize];
int i = 0;
for (; i < frames.length; i++)
{
byte[] frame = new byte[frameSize];
int numBytes = stream.read(frame, 0, frameSize);
if (numBytes == -1)
{
break;
}
frames[i] = frame;
}
System.out.println("FrameSize = " + frameSize);
System.out.println("Number frames = " + frames.length);
System.out.println("Number frames read = " + i);
}
}
```
And then:
```
FrameBuffer frameStream = new FrameBuffer(austream); //austream is the audiostream
int frame = frameStream.numberFrames() - 1;
while (frame >= 0) {
auline.write(frameStream.getFrame(frame), 0, frameStream.frameSize());
frame--;
}
``` | If the WAV contains PCM, reverse the order of the PCM samples. If it contains some other format it can be a lot more complex; probably easiest to just convert it to PCM first.
For more information on the WAV format, see [this site](http://ccrma.stanford.edu/courses/422/projects/WaveFormat/). | Play WAV file backward | [
"",
"java",
"stream",
"audio",
""
] |
If you have a common eclipse/osgi code platform on which you build various products can you/should you inherit activators from the common code
E.g.
org.test.common.PluginActivator
org.test.common.ui.UIPluginActivator
org.test.product1.Product1PluginActivator
org.test.product1.ui.Product1UIPluginActivator
org.test.product2.Product2PluginActivator
org.test.product2.ui.Product2PluginActivator
I want to have all the UI activators inheriting from the common one, and the same for the non-ui activators. The start methods would all be calling super...
However I am wondering if this is bad osgi/bundle practice or could cause problems.
Does anyone have any ideas/opinions on this? | If the child can't run without the parent's bundle anyway (i.e. it has a functional dependency on it), you're not adding any additional coupling by making the Activator inherit from it.
I'd be wary of inheriting from a common parent unless the plugin already had reason to do so as you're forcing the bundle to be loaded even if you're only inheriting some constant. | I'm assuming you're doing Eclipse RCP because otherwise I'd recommend Spring DM (or iPOJO, Google Guice with Peaberry, or Declarative Services, ...). That way you'd never need to write another bundle activator again.
On the other hand, my team went with the common abstract `BundleActivator` for our RCP-related bundles. To me, having the actual bundle activators in a central bundle(s) increases coupling. | Is having Eclipse OSGI Activators inheriting from each other a good idea? | [
"",
"java",
"eclipse",
"eclipse-plugin",
"osgi",
"bundle",
""
] |
I want to capture stdout from a long-ish running process started via `subprocess.Popen(...)` so I'm using `stdout=PIPE` as an arg.
However, because it's a long running process I also want to send the output to the console (as if I hadn't piped it) to give the user of the script an idea that it's still working.
Is this at all possible?
Cheers. | Can you simply `print` it as you read it from the pipe? | The buffering your long-running sub-process is probably performing will make your console output jerky and very bad UX. I suggest you consider instead using [pexpect](http://pexpect.sourceforge.net/pexpect.html) (or, on Windows, [wexpect](http://code.google.com/p/wexpect/)) to defeat such buffering and get smooth, regular output from the sub-process. For example (on just about any unix-y system, after installing pexpect):
```
>>> import pexpect
>>> child = pexpect.spawn('/bin/bash -c "echo ba; sleep 1; echo bu"', logfile=sys.stdout); x=child.expect(pexpect.EOF); child.close()
ba
bu
>>> child.before
'ba\r\nbu\r\n'
```
The ba and bu will come with the proper timing (about a second between them). Note the output is not subject to normal terminal processing, so the carriage returns are left in there -- you'll need to post-process the string yourself (just a simple `.replace`!-) if you need `\n` as end-of-line markers (the lack of processing is important just in case the sub-process is writing binary data to its stdout -- this ensures all the data's left intact!-). | Python - capture Popen stdout AND display on console? | [
"",
"python",
"pipe",
"popen",
""
] |
I have a page which has DIVs which contain short phrases (one-two words) of varying font sizes, which need to be positioned left-to-right according to a numerical parameter, and vertically so as not to overlap.
It's like a tag cloud, but there's information contained in the y-axis as well ("coolness" in this case - <http://cool-wall.appspot.com>)
How should I lay these out? I'm currently using a very messy series of DIVs like this:
```
<div style="position:absolute; top:150px;left:10px;right:10px;bottom:10px">
<!-- then, repeated, with different top, left and font-size values -->
<div style="align:center; margin:0; border:none; padding:0; float:left; visibility:visible; position:absolute; top:21%; left:56%; font-size:11px">
<div style="margin-top:0%; margin-right:50%; margin-bottom:0%; margin-left:-50%;">
<a href="foo"><span style="display:inline"> ← </span></a>
<a href="bar"><span style="display:inline"> Buzz </span></a>
<span style="display:inline"> → </span>
</div>
</div>
<!-- of course, followed by a close div -->
</div>
```
I use a stylesheet to extract some of those styles, and I realise that it's pretty poor CSS (and HTML)... but this was all I could hack together to do (almost) what I wanted to do. The main problem with the above (apart from it being confusing) is that I can't set the positioning so it doesn't overlap, because I don't know what size the font will be, nor how it will display onscreen.
Happy to use JavaScript to get it right. But I don't know where to start. Any tips? | The x-value is set on each one, you want to be as high on the page as possible (lowest y) as it can go without overlapping. Not too bad:
1) Render the container - position:relative; Render each item inside the container with "position:absolute; top:0; left:-1000; " - draw them all off screen.
2) One by one, move the element to it's needed x-coorinate and y=0; Check it with all previous render items to see if it collides, if it does, move it down one pixel until it doesn't collide:
```
var regions = [];
for(var i = 0; i < items.length; i++){
var item = items[i];
item.style.x = getX(item); // however you get this...
var region = YAHOO.util.Dom.getRegion(item);
var startingTop = region.top;
for(var iReg = 0; iReg < regions.length; iReg++){
var existingRegion = regions[iRegion];
while(region.intersect(existingRegion)){
region.top++;
region.bottom++;
}
item.style.y = (region.top - startingTop) + 'px';
}
}
```
It's important to just update the region and not actually move the dom node 1px at a time for performance reasons.
Put most important items first and they will render with more priority than items below them. | There is a javascript property on the dom object that will tell you the height of the tag if you have the width set. I believe its called clientHeight
alert(document.getElementById('myElement').offsetHeight);
Try that (also see <http://www.webdeveloper.com/forum/archive/index.php/t-121578.html>)
OR
Try this
```
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
..
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
```
Have all your element just display inline, output them in random order, and then set random margin's on them. This could all be done with server side code (or javascript if you want it client side). | Positioning Divs semi-randomly, without overlaps | [
"",
"javascript",
"html",
"css",
"overlap",
""
] |
I have problems getting two different struts2 webapps to start together in tomcat. But each of the webapps start correctly when placed independently inside webapps folder of tomcat.
I get the following in catalina.out logs-
SEVERE: Error filterStart
Aug 13, 2009 3:17:45 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/admin] startup failed due to previous errors
Environment- Java1.6, Tomcat6, Struts2.1.6, FC10
The webapps are "admin" and "user". Both of these webapps contain struts2 jars inside their WEB-INF/lib directory respectively.
web.xml contains the following in both the webapps-
```
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
A point to note that always the "admin" webapp fails to load with the above error. If I remove the "user" webapp from webapps folder, "admin" webapp comes up just fine.
I have also observed one more thing w.r.t struts2 filter in web.xml- If I remove the struts2 filter from web.xml in one of the webapps, BOTH the webapps start without any errors in the logs (but of course I won't be able to use struts in the webapp where the filter is removed).
I have also tried moving the struts2 jar to tomcat lib and removing them from individual webapps, but same problem exists..
Any ideas what is causing this problem?
**Updates:** This strangely works fine on Ubuntu OS. But the problem persists on FC10 and OpenSolaris. | Thanks alzoid, extraneon and Peter.
I had overlooked an exception coming up on localhost..log file. I thought I had redirected all the struts log to a different log file but had overlooked mentioning the opensymphony package in the log4j properties file.
Coming to original problem- there was a class loader issue with xerces-impl jar and some other jar file belonging to struts2. So when I removed the xerces-impl jar from the WEB-INF/lib directories in both apps, it started worked fine! | I had a similar problem using Spring and using this listener class in web.xml:
org.springframework.web.util.Log4jConfigListener
See the documentation of the Spring [Log4jWebConfigurer](http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/util/Log4jWebConfigurer.html), which says you need unique "web app root" properties defined per web-app, so I had to have a section like this in each web.xml:
```
<!-- used by Log4jConfigListener -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myappname.root</param-value>
</context-param>
```
Are you using Spring ? If not hope this gives you some clues, I don't know much about Struts2 maybe it does something similar. Do let me know how it goes ! | Two struts2 webapps fail to start together | [
"",
"java",
"deployment",
"tomcat",
"struts2",
"web-applications",
""
] |
Good morning all. I have an issue with a query. I want to select something in a query only if another field is somethingelse. The below query will better explain
```
select
Case isnull(rl.reason,'Not Found')
When 'D' then 'Discontinued'
When 'N' then 'Not Found'
When 'I' then 'Inactive'
When 'C' then 'No Cost'
When '' then 'Not Found'
End as Reason, ***If statement to select pv.descriptor only if reason is in ('D','I','C')***pv.descriptor
from table1 as rl
left join table2 as v on v.field= rl.field
***Here i want an if statment to run if reason is in ('D','I','C')***
left join table3 as pv on
Case rl.scantype
when 'S' then cast(ltrim(rtrim(pv.field#1)) as varchar)
when 'U' then cast(ltrim(rtrim(pv.field#2)) as varchar)
when 'V' then cast(ltrim(rtrim(pv.vfield#3)) as varchar)
end
= rl.scan and pv.vend_no = rl.vendnum
***'**If statement ends*****
left join storemain..prmastp as p on p.emuserid = rl.userid
where rl.scandate between GetDate() -7 and GetDate() order by rl.scandate desc
```
I want the if statement to select the descriptor only if the reason selected is a 'D','I',or'C'. If not I want a null value there because i will not do the join to get that variable unless the reason is a 'D','I','C'
BY the way, I can used a case statement where i used it in the middle of the left join. It works perfectly fine. That's not my issue. | I *think* that you want to only join to `pv` if `v.reason` is `(D, I, C)` - is that right? If that's your problem, just change your `JOIN` clause to:
```
LEFT JOIN table3 as pv ON
LTRIM(RTRIM(
CASE rl.scantype
WHEN 'S' THEN pv.field#1
WHEN 'U' THEN pv.field#2
WHEN 'V' THEN pv.field#3
END
)) = rl.scan
AND rl.vendnum = pv.vend_no
AND rl.reason IN ('D', 'I', 'C')
```
Of course, you also have "If statement to select pv.descriptor only if reason is in ('D','I','C') [as] pv.descriptor" in the SELECT clause. So, assuming you want *that* instead, try this:
```
SELECT
/* your other columns */
CASE
WHEN rl.reason IN ('D', 'I', 'C') THEN pv.descriptor
ELSE NULL --optional, since it'll default to NULL
END as descriptor
``` | If you want it in one query, you HAVE to do the join. Using left joins and case statement as you have, you can ensure pv.descriptor is shown as null if that is what you want in certain cases.
If you want control flow, you will need to use T-SQL
If performance is your concern, you shouldn't be joining on computed values. Rethink the database design. You likey want to create new columns for your join, and may want to create intermediary tables if you have many-to-many relationships. | if statements in sql query | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sms",
""
] |
I'm using two 3rd party libraries, which both implement their own 2D vector class. Unfortunately, I have to work with both of them, so is there anyway I can write some "friend" functions so that one can automatically be converted to the other when I try to use them in functions from the other library? | Conversion operators have to be member functions.
In situations like this, I have used a `convert<X,Y>` function template, with full specialisations or overloads for each pair of types that I want to "cast". In this case, you wouldn't need the template, just two overloads, one in each direction, because for a given X there's only ever one thing you convert it to.
Then it's rarely any trouble to switch between one and the other (the notable exception being when you're using template code which requires that one parameter type be convertible to another). You can easily see in the code the boundary between the two APIs, without introducing much noise.
The reason I've had this situation a lot is writing OS abstraction layers - the underlying OS has one set of objects or opaque handles for various OS concepts, and the API you're implementing has another. It's much nicer to just "convert" from one set of concepts to the other, without having ConvertHostMutexToGuestMutex, ConvertGuestMutexToHostMutex, ConvertHostSocketOptsToGuestSocketOpts etc. The disadvantage is the usual one with widespread overloading, that it's not necessarily obvious where the functions are actually defined. | *Auto*-cast seems not to be possible. You could define global conversion function and call it explicitly. Could you post definition of that classes? May be some trick with inheritance will be possible.
Something like this, but it is not auto-cast:
```
class T1 {};
class T2 {};
class UnionType : public T1, public T2
{
public:
UnionType( const T1& val ) {} // real storing should be here
UnionType( const T2& val ) {} // real storing should be here
operator T1() { T1 t; return t; } // real conversion should be here
operator T2() { T2 t; return t; } // real conversion should be here
};
int main()
{
T1 t;
T2 t2 = UnionType(t);
return 0;
}
``` | Auto-cast two 3rd party classes? | [
"",
"c++",
"casting",
""
] |
When you use `Html.RenderPartial` is takes the name of the view you want to render, and renders it's content in that place.
I would like to implement something similar. I would like it to take the name of the view you want to render, along with some other variables, and render the content within a container..
For example:
```
public static class WindowHelper
{
public static string Window(this HtmlHelper helper, string name, string viewName)
{
var sb = new StringBuilder();
sb.Append("<div id='" + name + "_Window' class='window'>");
//Add the contents of the partial view to the string builder.
sb.Append("</div>");
return sb.ToString();
}
}
```
Anyone know how to do this? | The RenderPartial extensions are programmed to render directly to the Response object... you can see this in the source code for them:
```
....).Render(viewContext, this.ViewContext.HttpContext.Response.Output);
```
This means that if you change your approach a little bit, you can probably accomplish what you want. Rather than appending everything to a StringBuilder, you could do something like this:
```
using System.Web.Mvc.Html;
public static class WindowHelper
{
public static void Window(this HtmlHelper helper, string name, string viewName)
{
var response = helper.ViewContext.HttpContext.Response;
response.Write("<div id='" + name + "_Window' class='window'>");
//Add the contents of the partial view to the string builder.
helper.RenderPartial(viewName);
response.Write("</div>");
}
}
```
Note that including System.Web.Mvc.Html allows you access to the RenderPartial() methods. | We are fixing this in MVC 2. You will be able to call Html.Partial() and get the actual contents of the view as a string. | How does the Html Helper, RenderPartial, work? How can I implement a helper that can bring in content from a partial view? | [
"",
"c#",
"asp.net-mvc",
"html-helper",
"partial-views",
"renderpartial",
""
] |
I made a function that overwrite the the `:hover` of some elements on a page. It fades between the normal and the `:hover` effect. That for i had to create a `.hover` class in my CSS file. I think this is a little unclean. How could i read the the `:hover` pseudo class contents? | **UPDATE**: I somehow got this wrong. The below example doesn't work. See [@bfavaretto's comment](https://stackoverflow.com/questions/1285033/read-hover-pseudo-class-with-javascript/1285212#comment17028965_1285212) for an explanation.
~~In Firefox, Opera and Chrome or any other browser that correctly implements [`window.getComputedStyle`](https://developer.mozilla.org/en/DOM/window.getComputedStyle) is very simple. You just have to pass "hover" as the second argument:~~
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
display: block;
width: 200px;
height: 200px;
background: red;
}
div:hover {
background: green;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementsByTagName("div")[0];
var style = window.getComputedStyle(div, "hover");
alert(style.backgroundColor);
};
</script>
</body>
</html>
```
~~But I don't believe there's yet a solution for Internet Explorer, except for using `document.styleSheets` as Gumbo suggested. But there will be differences.~~ So, having a `.hover` class is the best solution so far. Not unclean at all. | Using [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle) as on the accepted answer won't work, because:
1. The computed style for the hover state is only available when the element is actually on that state.
2. The second parameter to `getComputedStyle` should be empty or a pseudo-element. It doesn't work with `:hover` because it's a pseudo-class.
Here is an alternative solution:
```
function getCssPropertyForRule(rule, prop) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if(rules[j].selectorText == rule) {
return rules[j].style[prop];
}
}
}
}
// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));
```
[**Demo**](http://jsfiddle.net/EtLT5/) | Read :hover pseudo class with javascript | [
"",
"javascript",
"jquery",
"css",
""
] |
Is there a way to find the width of the console in which my Java program is running?
I would like this to be cross platform if possible...
I have no desire to change the width of the buffer or the window, I just want to know its width so I can properly format text that is being printed to screen. | There are no **reliable** cross-platform solutions to this problem. Indeed, there are situations where it is not possible to know what the real console width is.
(See other answers for approaches that work *some* of the time and/or on some platforms. But beware of the limitations ...)
For example, on a Linux system you can typically find out the notional terminal dimensions from the LINES and COLUMNS environment variables. While these variables are automatically updated when you resize some "terminal emulator" windows, this is not always the case. Indeed, in the case of a remote console connected via telnet protocol, there is no way to get the actual terminal dimensions to the user's shell.
**EDIT**: Just to add that if the user changes the dimensions of his/her xterm on Linux after launching a Java app, the Java app won't be notified, and it won't see the new dimensions reflected in its copy of the `LINES` and `COLUMNS` environment variables!
**EDIT 2**: My mistake: `LINES` and `COLUMNS` are `bash` shell variables, and they are not exported to the environment by default. You can "fix" this by running `export COLUMNS LINES` before you run your Java application. | Actually, a Java library already exists to do this in Java: [JLine 2](https://github.com/jline/jline2). (There's an old version on SourceForce, but that link to GitHub seems to be the latest.)
This worked for me under Linux (Mint 14) and Windows (I don't know what version), using JLine 2.11:
```
terminalWidth = jline.TerminalFactory.get().getWidth();
```
JLine promises to work on Mac, too.
I've found that it returns bad widths (like `1`!) under the Eclipse console (but even Java's native Console doesn't work under Eclipse!), and, unfortunately, under Cygwin. But I've worked around this with code that checks for unreasonable values (`< 10`) and just uses 80 in those cases.
**Update for JLine 3** (per [Mark](https://stackoverflow.com/users/108034/mark)—thanks, mate!):
```
terminalWidth = org.jline.terminal.TerminalBuilder.terminal().getWidth()
``` | Can I find the console width with Java? | [
"",
"java",
"console",
""
] |
An answer from [another question](https://stackoverflow.com/questions/1286113/another-php-regex-question/1286117#1286117) piqued my curiosity.
Consider:
```
$string = "asfasdfasdfasdfasdf[[sometextomatch]]asfkjasdfjaskldfj";
$regex = "/\[\[(.+?)\]\]/";
preg_match($regex, $string, $matches);
$regex = "/\[\[(.*)\]\]/";
preg_match($regex, $string, $matches);
```
I asked what the difference between the two regexes is. The aswer I got was that ".\*" matches any character 0 or more times as many times as possible,
and ".+?" matches any character 1 or more times as few times as possible.
I read those regexes differently so I did some experimenting on my own but didn't come to any conclusions. Php.net says "?" is equivalent to {0,1} so you could rewrite
```
"/\[\[(.+?)\]\]/"
```
as
```
"/\[\[((.+){0,1})\]\]/"
```
or as
```
"/\[\[(.{0,})\]\]/"
```
or as
```
"/\[\[(.*)\]\]/"
```
Will they capture different text? Is the difference that one is less expensive? Am I being anal? | Just take an example where you get different results:
```
foo [[bar]] baz [[quux]]
```
Your first regular expression will match `[[bar]]` and `[[quux]]` while the second will match only `[[bar]] baz [[quux]]`.
The reason for that is that a lazy [quantifier](http://docs.php.net/manual/en/regexp.reference.repetition.php) (suffixed with `?`) will match the minimum of possible repetitions the normal greedy mode will match the maximum of possible repetitions:
> However, if a quantifier is followed by a question mark, then it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern `/\*.*?\*/` does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in `\d??\d` which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches. | Stand-alone, `?` does mean `{0,1}`, however, when it follows something like `*`, `+`, `?`, or `{3,6}` (for example), `?` means something else entirely, which is that it does minimal matching. So, no, you can't rewrite `/\[\[(.+?)\]\]/` as `/\[\[((.+){0,1})\]\]/`. :-) | What's the difference between these perl compatible regular expressions? | [
"",
"php",
"regex",
""
] |
I'm not sure if it's possible. I wrote a code like this:
```
listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's");
listBox1.Font = new Font("Arial", 12, FontStyle.Bold);
listBox1.ForeColor = Color.Violet;
listBox1.Items.Add("There are " + j.ToString().Trim() + " vowels");
listBox1.ForeColor = Color.Blue;
```
When I executed this code, the color of the texts were blue. I would like to have it first "violet" and then the next line of code blue. Is it possible?
Cheers | You could create an owner-drawn listbox as described in MSDN here:
> [**How to: Create an Owner-Drawn List Box**](http://msdn.microsoft.com/en-us/library/ms229679.aspx) | [ObjectListView](http://objectlistview.sourceforge.net/), though it's not exactly a `ListBox`, allows to do that. If you want `ListBox` only, see [this](http://www.c-sharpcorner.com/UploadFile/sahuja/OwnerDrawListBox11212005014826AM/OwnerDrawListBox.aspx). | is it possible to have different colors of text in a textbox or listbox? | [
"",
"c#",
"winforms",
"text",
"colors",
""
] |
How can I find out how much time my C# code takes to run? | Check out the [`Stopwatch`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class:
```
Stopwatch sw = new Stopwatch();
sw.Start();
// your code here
sw.Stop();
TimeSpan elapsedTime = sw.Elapsed;
``` | The [`Stopwatch`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class offers high-precision timing in .NET. It is capable of measuring time with sensitivity of around 100s of nanoseconds (fractions of milliseconds). To get the exact resolution, read the value of [`Stopwatch.Frequency`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.frequency.aspx).
```
var timer = System.Diagnostics.Stopwatch.StartNew();
// Run code here.
var elapsed = timer.ElapsedMilliseconds.
```
Also, be sure to *run your code repeatedly* (as many times as is feasible) to get a better average time, as well as to reduce the effects of fluctuations in CPU load. | How long does my code take to run? | [
"",
"c#",
"benchmarking",
"performance",
""
] |
This is just a matter of taste but I'd like to hear some of your opinions (that's also why this question is marked as subjective).
If I have a property, say
```
private string _Text;
public string Text;
get
{
object tmp = ViewState["Text"];
if (tmp != null)
_Text = Convert.ToString(tmp);
return _Text;
}
set
{
ViewState.Add("Text", value);
}
```
Now this is the property which may be specified by the programmer, by setting some custom text. This is then mapped - say - to some control on the UI. In the default case however, the Text of the control comes from a predefined resource file. So internally to handle that internally in a better way, I'd have some central point where I check whether the user has specified the "Text" property (above) and if so, use that data, otherwise rely on the default one from the resource file.
So what approach would you take? I have two options in mind:
```
private string ResolvedText
{
get
{
if(!string.IsNullOrEmpty(Text))
return Text;
else
//return the one from the resource file
}
}
```
Or put everything in a method
```
public string GetResolvedText()
{
if(!string.IsNullOrEmpty(Text))
return Text;
else
//return the one from the resource file
}
```
The question may sound stupid to you since it's really a minor difference. But I'd like to know whether there are some conventions about this.
Thx | I find that the best general rule here is: if calling the action twice results in multiple resource calls or different behaviour - use a method.
So, in your example use of a property is fine if it caches:
```
public string ResolvedText
{
get { return Text ?? (Text = GetResolvedText()); }
}
```
However the method doesn't need to - users expect it to be a more intensive operation:
```
public string GetResolvedText()
{
//return the one from the resource file
}
```
The design question is how do you want this class to be used?
A property will get called as if it is a 'cheap' operation:
```
if( myInstance.ResolvedText != null &&
myInstance.ResolvedText.Length > 5 )
Response.Write( myInstance.ResolvedText );
```
A method hints to the developer that they should call it as few times as possible:
```
string resolvedText = myInstance.GetResolvedText();
if( resolvedText != null &&
resolvedText.Length > 5 )
Response.Write( resolvedText );
```
Personally I prefer to keep interim classes simple, so in the vast majority of cases I would use the method model.
As this is a fairly standard convention you should avoid properties that don't cache and methods that do. | Personally, I'd take the body of your GetResolvedText method, and use it in the property, thus:
```
private string _Text;
public string Text
{
get
{
if(string.IsNullOrEmpty(_Text))
//return the one from the resource file
else
return _Text;
}
set
{
_Text = value;
}
}
```
This puts all the responsibility for managing the string into the one place. The class itself can access `_Text` internally, if it needs the raw value. | Get-methods or private property? | [
"",
"c#",
".net",
""
] |
Is it possible to set session variables from javascript? | The short answer is no.
You can set cookies, but they're not quite the same.
You could also use AJAX to post back to a script on your server that will set the variables.
Session variables exist only on the server. | session variables belongs to server-side scripting, thus javascript, being a client-side script is not able to set session variables. however, you are able to make use of ajax to set the session variable asynchronously, meaning without refreshing the page =) | Is it possible to set session variables from javascript? | [
"",
"javascript",
""
] |
I did my programming before integrating into a design and I have to admit I am quite stuck on the whole situation. Here is my structure:
* System Files
+ Admin (Admin files)
- Functions (Admin Function folder)
+ User (User Files)
- Functions (User Function folder)
Normal Visitor Account Files ( In system files folder).
This whole directory is under public\_html which holds my site files. I have tried includes, which seems like a nice clean way of doing it. But the issue I encounter is when I need to modify the header on login. I was just wondering if anyone had any ideas. I tried iframes but i feel it is very unclean.
Thanks!! | I simply took all of my PHP code and wrapped my header and footer files around it.
To fix the header problem i used:
```
ob_start();
```
and
```
ob_flush();
```
Thank you all for your input. | In fact you need to check whatever you want to check before you start any output.
So:
```
<?php
//do your stuff, includes and more
if(isset($_GET['login']))
{
//do login stuff
if($login === false)
{
header("Location: index.php");
}
}
//start output
?>
<html>
etc.
```
So in your situation you have to reorganize a little bit.
The following is not recommended:
If it costs to many efforts... you can use ob\_start(); at the beginning of your script and buffer any output.
But again, the last solution is really ugly because it hides the real problem. | Integrating my PHP code into my site | [
"",
"php",
"mysql",
""
] |
Array.Sort(test);
Comes out to be
```
_A
_B
_C
A
B
C
```
I reverse it
```
C
B
A
_C
.. You know
```
I want it to be
```
_C
_B
_A
C
B
A
```
So how could I do that? | You could implement your own Comparer like this:
```
public class MyOwnComparer: IComparer<string>
{
public int Compare(string x, string y)
{
if (x.StarsWith("_") && !y.StartsWith("_"))
return 1;
else if (!x.StartsWith("_") && y.StartsWith("_"))
return -1;
else
return x.CompareTo(y);
}
}
```
and then use it like this:
```
Array.Sort(test, new MyOwnComparer()); //sort ascending
var result = test.Reverse(); //now its descending
``` | If the built-in Array.Sort() does not sort the way you intend, you can override the IComparable.CompareTo method.
See this MSDN Article: How to: [Sort Arrays Using Custom Criteria](http://msdn.microsoft.com/en-us/library/s9xfdtye.aspx) | How do I do a non-standard sort on an Array in C#? | [
"",
"c#",
""
] |
I'm trying to compute 100! and there doesn't seem to be a built-in factorial function. So, I've written:
```
Protected Sub ComputeFactorial(ByVal n As ULong)
Dim factorial As ULong = 1
Dim i As Integer
For i = 1 To n
factorial = factorial * i
Next
lblAnswer.Text = factorial
End Sub
```
Unfortunately, running this with the value of 100 for n rseults in
> Value was either too large or too
> small for a UInt64.
So, is there a larger data type for holding numbers? Am i mistaken in my methods? Am I helpless? | Sounds like Project Euler.
.NET 4.0 has System.Numerics.BigInteger, or you can pick up a pretty sweet implementation here:
[C# BigInteger Class](http://www.codeproject.com/KB/cs/biginteger.aspx)
Edit: treed :(
I'll add - the version at CodeProject has additional features like integer square root, a primality test, Lucas sequence generation. Also, you don't have direct access to the buffer in the .NET implementation which was annoying for a couple things I was trying. | Until you can use [`System.Numerics.BigInteger`](http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(VS.100).aspx) you are going to be stuck using a non-Microsoft implementation like [`BigInteger` on Code Project](http://www.codeproject.com/KB/cs/biginteger.aspx). | A value larger than ULong? Computing 100! | [
"",
"c#",
"asp.net",
"vb.net",
"math",
""
] |
I am working on the application (C# 2.0). I have implemented single instance in it. Everything is fine.
If i run the application again, it shows messagebox saying "instance is already running".
Actually i don't want to show the message through messagebox.
I want to show this message using Balloon tip of already running instance (it has notify icon in system tray).
How can i achieve this?
Thanks in advance. | You need a form of [interprocess communication](http://www.google.co.uk/search?rlz=1C1GGLS_en-GBGB300GB305&sourceid=chrome&ie=UTF-8&q=c%23+interprocess+communication), to signal to the other instance that it should display the messagebox.
In this instance, you could go one better than telling the existing instance to display the message, and instead tell it to restore it's main window (i.e. "unminimise"). | You could use a WCF service inside you app.
Your second app connects to it via NetPipe, invode a method and closes.
Your first app receive the call and pops-up the baloon notification | single instance and notify in system tray | [
"",
"c#",
".net",
"single-instance",
"notify",
"balloon",
""
] |
I'm thinking about attempting a port of an existing emulator code base to Silverlight 3. There appears to be enough functionality with WritableBitmap and the new sound classes to make a port feasible. Is anyone familiar with an emulator that's open source and might not be too hard to port? I'd really like to focus on moving the media aspects of the source to SL more than the complexities of porting some awkward ASM code to C#. I guess if I could find some source that's already in C# it might be ideal. | Start with a good 'ol NES emulator...
[SharpNES](http://forge.novell.com/modules/xfmod/project/?sharpnes) is C#/Mono so while it might not be directly port-able, it should be a good start.
[vNES](http://www.virtualnes.com/) is a Java NES emulator intended to be run in an applet. It's source is freely available under GPL. Not C#, but might be worth looking at for ideas. | I'm looking for interested folks to bring <http://silverlightc64.codeplex.com> up to full functionality. It's a C64 emulator. I just want to make sure that whoever contributes can make a real contribution :)
I use MediaStreamSource to output 50fps of video instead of using the writablebitmap. The advantage is if the client machine can't keep up, MSS will handle dropping frames.
Pete | What's a good emulator to port to Silverlight 3? | [
"",
"c#",
"silverlight",
"emulation",
""
] |
Suppose I load a webpage which contains the following anchor:
```
<a class="someClass" href="#" onClick="gotoPage('http://somepage.org')">Link</a>
```
What I want is: as soon as the page is loaded, I want to generate onClick for this anchor which has text as "Link".
Note that the anchor does not contains any id or name associated with it. Thus document.getelementbyid or document.getelementbyname will not work. | As you're using Greasemonkey you should be able to use XPath to select the link in question using one of it's HTML attributes:
<http://diveintogreasemonkey.org/patterns/match-attribute.html> | Here is what [people seem](http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/751003265631) [to do](http://svn.openqa.org/fisheye/browse/selenium/trunk/javascript/selenium-browserbot.js?r=2) to be able to generically trigger a `click` event in Firefox. They extend the `HTMLAnchorElement` prototype with a `click()` function, like so:
```
HTMLAnchorElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
```
See [MDC for `initMouseEvent()`](https://developer.mozilla.org/en/DOM/event.initMouseEvent).
If you have jQuery, you might also check out [`trigger()`](http://docs.jquery.com/Events/trigger#eventdata). | How to simulate click on anchor with specific text using javascript in GreaseMonkey? | [
"",
"javascript",
"anchor",
"greasemonkey",
""
] |
I'm familiar with this sort of syntax in SQL Server, to concatenate strings in my result set:
```
SELECT 'foo' + bar AS SomeCol
FROM SomeTable
```
I would like to do something similar inside a ColdFusion Query of Queries:
```
<cfquery name="qOptimize" dbtype="query">
select
image_id AS imageId,
'#variables.img_root#' + image_id + '.' + image_ext AS fullImage,
'#variables.img_root#' + image_id + 't.' + image_ext AS thumbnailImage,
from qLookup
order by imageId asc
</cfquery>
```
This is part of a service consumed by a Flex application, so I'm optimizing the result of a stored procedure used elsewhere in the application before returning to the client -- stripping out unused columns, and compiling image URLs from some dynamic path information.
I could write a new stored procedure that takes the image root as a parameter and does all of this, **and I probably *will* for performance reasons**, but the question is still nagging me. I haven't found a syntax that works yet, so I wonder if it's possible.
When I try the above, I get the following error:
> **Query Of Queries syntax error.**
> Encountered "from. Incorrect Select List, Incorrect select column,
Has anyone done this? Is it possible, perhaps with another syntax? | Yes this is possible. I think the problem is that image\_id is most likely a numeric value. If you cast it as an varchar then it should be fine.
```
<cfquery name="qOptimize" dbtype="query">
select
image_id AS imageId,
'#variables.img_root#' + cast(image_id as varchar) + '.' + image_ext AS fullImage,
'#variables.img_root#' + cast(image_id as varchar) + 't.' + image_ext AS thumbnailImage
from qLookup
order by imageId asc
</cfquery>
``` | I think the error you mention is due to the comma at the last concatenation, at the end of thumbnailImage.
Just my $0.002 | Is it possible to do string concatenation in a ColdFusion Query of Queries? | [
"",
"sql",
"coldfusion",
""
] |
With Javascript how would I search the first three letters in a string and see if they match "ABC"? Thanks | Using a regular expression:
```
str.match(/^ABC/);
```
or using the `substring` method:
```
str.substring(0, 3) == 'ABC';
``` | ```
if (/^ABC/.test(aString)) {
}
``` | With Javascript how would I search the first three letters in a string and see if they match "ABC"? | [
"",
"javascript",
""
] |
I have this line of code in an assembly:
```
HttpContext.Current.Server.MapPath
```
This works great if the assembly is being used in a web service.
but if I take it out of the web service its obivously not going to work, because HTTPContext does not exist.
Is it at all possible to fool httpContext into thinking it exists, really just to get the relative path structure of a directory?
I mean somehow manually creating the HTTPContext object, and assigning it a base directory?
**Update**
Is there a more generic approach to : HttpContext.Current.Server.MapPath
Something that can work in executables, and something that can work in web? | [HttpContext.Current](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.current.aspx) "gets or **sets** the HttpContext object". And HttpContext has a public constructor which takes a HttpWorkerRequest (abstract, use SimpleWorkerRequest) and you would be able to fake the HttpContext completely.
I agree with others that you could refactor your code to remove this dependency, but there are scenarios when you must fake the HttpContext.Current stuff, in which case this question will show up if you search... | It sounds to me like you need to wrap up the call to HttpContext inside another object which you can then switch out using IOC for the correct object in the correct environment. E.g. something like IMapPath as your interface and then your implementation could be HttpMapPath or ConsoleAppMapPath etc. | Possible to fool HTTPContext.Current? | [
"",
"c#",
""
] |
I asked this question previously and thought I had it figured out but it still doesn't work.
[Form.Show() moves form position slightly](https://stackoverflow.com/questions/1214014/form-show-moves-form-position-slightly)
So I have a parent form that opens a bunch of children with show() and then when one is needed I use bringToFront() to display it. The problem is when show() is called the child form is aligned perfectly but when I use bringToFront it moves left and down 1 px which screws with my borders. I have set all the child forms startPosition properties to Manual before show()-ing them. I have set frm.location = new Point(x,y) when bringing to front. I've also tried explicity setting frm.location when show()-ing also. It still moves it left and down 1 px when I bringToFront(). Is there something with bringToFront() that doesn't let me change the location property of the form? Here is my code:
```
if (myNewForm != null)
{
myNewForm.MdiParent = this;
bool isFormOpen = false;
foreach (Form frm in Application.OpenForms)
{
if (frm.GetType() == myNewForm.GetType())
{
frm.WindowState = FormWindowState.Maximized;
frm.BringToFront();
frm.Location = new Point(-4, -30);
isFormOpen = true;
break;
}
}
if (!isFormOpen)
{
myNewForm.StartPosition = FormStartPosition.Manual;
myNewForm.Show();
}
}
```
EDIT: Ok so apparently Microsoft has a bug that lets StartPosition only work for ShowDialog() and not Show() but refuses to fix it: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=107589>
But my application needs to keep all the different forms open and just bring them to the front when needed...so ShowDialog() could not be appropriately used in this instance correct? So what options do I have? Any? | What about using a [p/Invoke to MoveWindow](http://www.pinvoke.net/default.aspx/user32/MoveWindow.html)? The link provided includes a C# example. | If you wish to set the form location, you have to set the form's `WindowState` to `Normal` (on any other setting, the location is set for you according to the rules of that setting, so your value is ignored), and its `StartPosition` to `Manual`.
```
frm.WindowState = FormWindowState.Normal;
frm.StartPosition = FormStartPosition.Manual;
frm.BringToFront();
frm.Location = new Point(-4, -30);
``` | Form.Location doesn't work | [
"",
"c#",
"winforms",
""
] |
Our code is C++ and is managed in svn. The development is with Visual Studio. As you know Visual Studio C++ is case insensitive to file names and our code unfortunately "exploited" this heavily.
No we are porting our application to Linux + gcc, which **is** case sensitive. This will involve a lot of file names and file changes. We planned to do the development in separate branch.
It appears that svn rename has a well known problem ([here](https://stackoverflow.com/questions/187454/subversion-not-merging-changes-into-renamed-files) and [here](http://markphip.blogspot.com/2006/12/subversion-moverename-feature.html)).
Is there a way to workaround it? Is git-svn or svnmerge can aid here?
Thanks
Dima | The case sensitivity issue is not about Visual Studio vs. GCC, but rather about the filesystem; the standard filesystems on Windows and Mac OS X (FAT32 and NTFS for Windows, HFS+ for Mac OS X), are case insenstive but case preserving, while Linux filesystems (ext2, ext3, and ext4) are case sensitive. I would suggest that you rename your files, using all lower case for all your source files, and then branch, and -- of course -- for the future, have a strict policy of using lower case and a ".cpp" extension for all C++ source files and ".h" for all header files. Is there any reason you cannot perform this renaming prior to the branch? | Git itself deals (very well) with the problem of renamed files in merges (and not only there) by doing heuristic file-contents and filename similarity based *rename detection*. It doesn't require to have information about renames entered like rename tracking solution. | svn rename problem | [
"",
"c++",
"svn",
"git",
"cross-platform",
"rename",
""
] |
I'm using ODBC, OLE is available if needed to dump approx 3 different types of data to different excel sheets. But to use insert statements in excel, the table has to be created first I believe, especially if the sheet doesn't exist yet.
I used to use sql server 2000's import/export wizard that automatically generated the create table statement.
So does anyone know the data types, and syntax for a create statement or the location of a good resource for excel sql create statements? | The create table syntax given to me on that sheet failed with the message
Could not modify the design of table 'Data' it is a read-only database.
Using OleDb This worked:
```
CREATE TABLE `sheetname` (
`DartNumber` VarChar (16)
, `ClientId` VarChar (10)
, `Population` VarChar (30))
```
but for some reason failed saying read-only using odbc. | Try here: [Using SQL in VBA](http://www.bygsoftware.com/Excel/SQL/UsingSql.html) | What's the syntax for the create table statement in Excel? | [
"",
"sql",
"excel",
"odbc",
""
] |
I have a GUI application written in C/C++ using gcc. I need some recommendations for writing an automated test system for it. What tools/scripting should be used? The application runs on Windows. | My recommendation is PyWinAuto, open source tool, python based tests (fast and easy to develop) and work on win32 level.
<http://pywinauto.openqa.org/> | We have used [TestComplete](http://en.wikipedia.org/wiki/TestComplete) here, with some success. | Automated Testing for C/C++ GUI Applications | [
"",
"c++",
"c",
"user-interface",
"automated-tests",
""
] |
Here's a snippet of my code:
```
$(".item").click(function () {
alert("clicked!");
});
```
And I have (hypothetically; in actuality it's far more complicated) the following on my page:
```
<a href="#" class="item"><img src="1.jpg" /></a>
```
However, when I click the image, I do not get an alert.
What is my mistake? | First question - are you adding the element to be clicked dynamically? If it is,
you should use the live event since that will take care dynamically created elements.
<http://docs.jquery.com/Events/live#typefn> | Is your selector actually matching anything? Try using the jQuery debug plugin (<http://jquery.glyphix.com/>) and doing this:
```
$(".item").debug().click(function() {
alert("clicked!");
});
```
.debug() will log whatever is matched to the Firebug console (you are using firebug, right? :-) ) without "breaking the chain" so you can use it inline like this.
If that turns out correctly, there may be some issue with the browser navigating to "#" before it can show your alert. Try using the .preventDefault() method on the event object to prevent this behavior:
```
$(".item").click(function(evt) {
evt.preventDefault();
alert("clicked!");
});
``` | JQuery .click() event troubles | [
"",
"javascript",
"jquery",
""
] |
This is the scenario:
We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:
```
os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
```
In the batch.bat we start a Windows GUI programm like this:
```
start c:\the_programm.exe
```
Thats all in the batch fíle.
Now the os.remove() fails with "Permission denied" because the temp.txt is still locked by the system. It seems this is caused by the still runing the\_programm.exe (whos output also seems to be redirected to the temp.txt).
Any idea how to start the\_programm.exe without having the temp.txt locked while it is still running? The Python part is hardly changeable as this is a tool ([BusyB](http://busyb.sourceforge.net/)).
In fact I do not need the output of the\_programm.exe, so the essence of the question is: **How do I decouple the\_programm.exe from locking temp.txt for its output?**
Or: **How do I use START or another Windows command to start a program without inheriting the batch output redirection?** | Finally I could find a proper solution:
I am not using a batch file anymore for starting the\_programm.exe, but a Python script:
```
from subprocess import Popen
if __name__ == '__main__':
Popen('C:/the_programm.exe', close_fds=True)
```
The close\_fds parameter decouples the file handles from the .exe process! That's it! | This is a bit hacky, but you could try it. It uses the `AT` command to run `the_programm.exe` up to a minute in the future (which it computes using the `%TIME%` environment variable and `SET` arithmetic).
batch.bat:
```
@echo off
setlocal
:: store the current time so it does not change while parsing
set t=%time%
:: parse hour, minute, second
set h=%t:~0,2%
set m=%t:~3,2%
set s=%t:~6,2%
:: reduce strings to simple integers
if "%h:~0,1%"==" " set h=%h:~1%
if "%m:~0,1%"=="0" set m=%m:~1%
if "%s:~0,1%"=="0" set s=%s:~1%
:: choose number of seconds in the future; granularity for AT is one
:: minute, plus we need a few extra seconds for this script to run
set x=70
:: calculate hour and minute to run the program
set /a x=s + x
set /a s="x %% 60"
set /a x=m + x / 60
set /a m="x %% 60"
set /a h=h + x / 60
set /a h="h %% 24"
:: schedule the program to run
at %h%:%m% c:\the_programm.exe
```
You can look at the `AT /?` and `SET /?` to see what each of these is doing. I left off the `/interactive` parameter of `AT` since you commented that "no user interaction is allowed".
Caveats:
* It appears that `%TIME%` is always 24-hour time, regardless of locale settings in the control panel, but I don't have any proof of this.
* If your system is loaded down and batch.bat takes more than 10 seconds to run, the `AT` command will be scheduled to run 1 day later. You can recover this manually, using `AT {job} /delete`, and increase the `x=70` to something more acceptable.
The `START` command, unfortunately, even when given `/i` to ignore the current environment, seems to pass along the open file descriptors of the parent `cmd.exe` process. These file descriptors appear to be handed off to subprocesses, even if the subprocesses are redirected to NUL, and are kept open even if intermediate shell processes terminate. You can see this in [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) if you have a batch file which `START`s another batch file which `START`s another batch file (etc.) which `START`s a GUI Windows app. Once the intermediate batch files have terminated, the GUI app will own the file handles, even if it (and the intermediate batch files) were all redirected to `NUL`. | Batch output redirection when using start command for GUI app | [
"",
"python",
"windows",
"batch-file",
"output-redirect",
""
] |
I am trying to create a stored procedure that takes a bit parameter which if true orders by one column and if false orders by another column. How would I implement this?
Here is what I have so far
```
CREATE PROCEDURE [dbo].[CLICK10_GetCP]
@switch AS BIT
AS
BEGIN
SELECT
acct_nbr,
acct_name
FROM
acct
ORDER BY
END
GO
``` | ```
ORDER BY
CASE WHEN @switch = 0 THEN Field1 END,
CASE WHEN @Switch = 1 THEN Field2 END
``` | A crude way:
```
IF @switch = 1
BEGIN
SELECT
acct_nbr,
acct_name
FROM
acct
ORDER BY acct_nbr
END
ELSE
BEGIN
SELECT
acct_nbr,
acct_name
FROM
acct
ORDER BY acct_name
END
```
You should also be able to use CASE..WHEN I think:
```
SELECT
acct_nbr,
acct_name
FROM
acct
ORDER BY
CASE @switch
WHEN 1 THEN acct_nbr
WHEN 0 THEN acct_name
END
``` | IF statement in ORDER BY Clause of a SELECT Statement in a SQL Server Stored Procedure | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Can I pass a method with an out parameter as a Func?
```
public IList<Foo> FindForBar(string bar, out int count) { }
// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }
```
Func needs a type so out won't compile there, and calling listFunction requires an int and won't allow an out in.
Is there a way to do this? | `ref` and `out` are not part of the type parameter definition so you can't use the built-in `Func` delegate to pass `ref` and `out` arguments. Of course, you can declare your own delegate if you want:
```
delegate V MyDelegate<T,U,V>(T input, out U output);
``` | Why not create a class to encapsulate the results?
```
public class Result
{
public IList<Foo> List { get; set; }
public Int32 Count { get; set; }
}
``` | Func<T> with out parameter | [
"",
"c#",
".net",
"linq",
"generics",
"func",
""
] |
I have csv files with the following format:
```
CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
```
The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format I receive them in. Is there a way to read a CSV file backwards, from the end of line to the beginning?
I don't mind writing a little python script to do so, if I’m guided in the right direction. | The `rsplit` string method splits a string starting from the right instead of the left, and so it's probably what you're looking for (it takes an argument specifying the max number of times to split):
```
line = "hello, world , 1 , 2 , 3"
parts = line.rsplit(",", 3)
print parts # prints ['hello, world ', ' 1 ', ' 2 ', ' 3']
```
If you want to strip the whitespace from the beginning and end of each item in your splitted list, then you can just use the `strip` method with a list comprehension
```
parts = [s.strip() for s in parts]
print parts # prints ['hello, world', '1', '2', '3']
``` | I don't fully understand why you want to read each line in reverse, but you could do this:
```
import csv
file = open("mycsvfile.csv")
reversedLines = [line[::-1] for line in file]
file.close()
reader = csv.reader(reversedLines)
for backwardRow in reader:
lastField = backwardRow[0][::-1]
secondField = backwardRow[1][::-1]
``` | parsing CSV files backwards | [
"",
"python",
"parsing",
"csv",
"readline",
""
] |
If I have a beacon:
```
<img src="http://example.com/beacon" />
```
I want a method to be called once the beacon request finishes. Something like:
```
<script>
$("img.beacon").load(function() {
// do stuff knowing the beacon is done
});
</script>
```
Is it possible? Is it in jQuery? | Sure. Remember the load needs to be added before the src attribute.
```
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
```
If you have defined the image tag in the markup then your stuck with when the window load event fires to be sure the image has come down the wire. | ```
$('img.beacon').load()
```
Will not always work correctly, ussually I do this:
```
$.fn.imageLoad = function(fn){
this.on('load', fn);
this.each( function() {
if ( this.complete && this.naturalWidth !== 0 ) {
$(this).trigger('load');
}
});
}
```
The above code also covers cases where the image has finished loading before the script is executed. This can happen when you define the image in the markup.
Use like this:
```
<img src='http://example.com/image.png' class='beacon' />
<script type='text/javascript'>
$(document).ready(function(){ //document.ready not really necessary in this case
$('img.beacon').imageLoad(function(){
//do stuff
});
});
</script>
``` | JavaScript: Know when an image is fully loaded | [
"",
"javascript",
"jquery",
"image",
""
] |
We have a Java application that stores RSA public keys and allows a user to encrypt a short stream of information with any of the keys. The application also allows the user to import a new key certificate into the keystore. When we load the certificate from a file, we want to use the common name (CN) as the alias. Here is the problem:
```
CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
X509Certificate cert = x509CertFact.generateCertificate(certificateInputStream);
String alias = cert.getSubjectX500Principal().getName();
assert alias.equals("CN=CommonName, OU=TestCo..."); // FAILS
assert alais.equals("cn=commonname, ou=testco..."); // PASSES
```
We know for a fact that the subject name in the file has mixed casing and we need to preserve that casing. Does anyone know how to get more flexible X.509 support from the JCE in Java6?
We've thought of using the BouncyCastle lightweight API, but documentation is almost non-existent.
EDIT:
Using JDK 6u11 Here is the list of security providers from java.security:
```
security.provider.1=sun.security.provider.Sun
security.provider.2=sun.security.rsa.SunRsaSign
security.provider.3=com.sun.net.ssl.internal.ssl.Provider
security.provider.4=com.sun.crypto.provider.SunJCE
security.provider.5=sun.security.jgss.SunProvider
security.provider.6=com.sun.security.sasl.Provider
security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.8=sun.security.smartcardio.SunPCSC
security.provider.9=sun.security.mscapi.SunMSCAPI
security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider
```
The certificate:
```
-----BEGIN CERTIFICATE-----
MIIDHjCCAtugAwIBAgIESnr4OzALBgcqhkjOOAQDBQAwcjELMAkGA1UEBhMCVVMxFTATBgNVBAoT
DEdlbWFsdG8gSW5jLjEnMCUGA1UECxMeU29sdXRpb25zIGFuZCBTcGVjaWFsIFByb2plY3RzMSMw
IQYDVQQDExpGUkJCTHVuYUNyeXB0b1NlcnZlci0xLjAuMDAeFw0wOTA4MDYxNTM1MjNaFw0wOTEx
MDQxNTM1MjNaMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxHZW1hbHRvIEluYy4xJzAlBgNVBAsT
HlNvbHV0aW9ucyBhbmQgU3BlY2lhbCBQcm9qZWN0czEjMCEGA1UEAxMaRlJCQkx1bmFDcnlwdG9T
ZXJ2ZXItMS4wLjAwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I8
70QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJP
u6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCXYFCP
FSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV466
1FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoB
JDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhAACgYBHBBVNzuoXgpPFPkSN71rI
MKkSIUAVE7iLagFCklCEvHlh1UxyRhCWNh/UazaJzHRZofWlVPRGmgtl+J6BJRJIDorPqt8FfifY
fpbAbCQctMToFF5QqggumOlJozXyfV9eyYyNn+Y4yZDr8JKq70WX/S2M+Oo1+SBJsXMTeDdfkDAL
BgcqhkjOOAQDBQADMAAwLQIUA+VcqEYMHwXdKY4XC+oO/zF/pRkCFQCDKAS5HpSMazbZgToEEYft
QFJSvw==
-----END CERTIFICATE-----
``` | If you mean that you are literally using the identity operator (`==`) to test, then the assertion should always fail. Use alias.equals("CN=CommonName, OU=...") instead.
However, assuming that's not the problem, can add:
```
System.out.println(x509CertFact.getProvider());
System.out.println(alias);
```
at the appropriate points in the code and post the results? It might turn up more leads. Posting the certificate you are loading (in text-friendly PEM format) would be helpful too, if it isn't disclosing any personally-identifying information. | Try using [X500Principal#getName(String)](http://java.sun.com/javase/6/docs/api/javax/security/auth/x500/X500Principal.html#getName(java.lang.String)) to get the DN in the format of your choice. Then you can parse the common name out of that.
Alternatively, if you're mapping an alias to an actual certificate you could store the "alias" in all caps (and query it in all caps) but you would still have the original casing from the mapped certificate | Get REAL X.509 data from RFC1421 formatted certificate | [
"",
"java",
"x509certificate",
"bouncycastle",
"jce",
""
] |
What is the easiest way to send and receive mails in java. | Don't forget [Jakarta Commons Email](http://commons.apache.org/email/) for sending mail. It has a very easy to use API. | [JavaMail](http://java.sun.com/products/javamail/) is the traditional answer for sending email (as everyone's pointing out).
As you also want to *receive* mail, however, you should check out [Apache James](http://james.apache.org/). It's a modular mail server and heavily configurable. It'll talk POP and IMAP, supports custom plugins and can be embedded in your application (if you so wish). | Sending mail from java | [
"",
"java",
"email",
"email-client",
""
] |
I want to create a fixed arbitrary size ThreadPool in .NET - I understand the default size is 25 - but I wish to have a different size e.g. 5 or 10. Anyone? | You should be careful about changing the size of the thread pool. There is just *one* fixed system thread pool, used by all kinds of things. Making it too small could cause problems in areas you didn't even think you were using.
If you want to have a relatively small thread pool for one specific task, you should use a separate pool. There are various third party pools available - I have a rather old one as part of [MiscUtil](http://pobox.com/~skeet/csharp/miscutil), but it should be good enough for simple use cases. I'm sure you can find more advanced ones if you look.
It's unfortunate that there isn't an instantiable `ThreadPool` in the framework yet. I can't remember offhand whether Parallel Extensions will effectively provide one, but I don't *think* it will. | You can use [ThreadPool.SetMinThreads](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads.aspx) and [ThreadPool.SetMaxThreads](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads.aspx) to have some control over the number of threads in the thread pool.
That being said, I recommend being cautious in using this. It's easy to get yourself into trouble, as many operations in the BCL rely on threadpool threads being available. | How do I create a fixed-size ThreadPool in .NET? | [
"",
"c#",
".net",
"multithreading",
"threadpool",
""
] |
What is the most common performance bottleneck that is not caused by the database structure? | Let's see (in no particular order)
1. Cursors
2. non-sargable where clauses
3. failure to index foreign key fields
4. failure to index fields commonly used in the where clause
5. correlated subqueries
6. accidental cross joins causing the need to distinct the result set
7. Badly performing code coming from ORMs
8. Code that causes too many reads or is called more than once when it didn't need to be (I've seen applications that send the same code many times when they didn't need to or every time a page is opened)
9. network pipe overloaded
10. User defined functions causing row-by-row processing
11. Parameter sniffing
12. out of date statistics
13. Union instead of union all | table scan because:
* index does not exist
* stats out of date
* functions in where clause prevent usage | Top 10 SQL Server performance bottlenecks | [
"",
"sql",
"sql-server",
"performance",
""
] |
I feel a little silly asking this but I wanted everyones opinion on it.
I want to submit a page, target itself, on the press of a button but carrying one piece of data with it.
Example:
Edit | Delete
On the click on edit, I want the page to reload with `$_POST['example'] === "edit"` or something. I don't want to use `$_GET` and I don't want to use the ugly submit button.
Any ideas? | You should probably go ahead and use submit buttons, but use CSS to change how they look.
For example:
```
<input class="aslink" type="submit" />
.aslink {
background: transparent;
border: none;
cursor: pointer;
text-decoration: underline;
}
``` | You could use Ajax to submit a POST request or style a submit button to look like a link (or whatever else you'd like). | Forms, Post and submit buttons | [
"",
"php",
"html",
"css",
"forms",
""
] |
i need something like iMacros for Python. It would be great to have something like that:
```
browse_to('www.google.com')
type_in_input('search', 'query')
click_button('search')
list = get_all('<p>')
```
Do you know something like that?
Thanks in advance,
Etam. | Almost a direct fulfillment of the wishes in the question - [twill](http://twill.idyll.org/).
> twill is a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features.
>
> twill supports automated Web testing and has a simple Python interface.
(`pyparsing`, `mechanize`, and `BeautifulSoup` are included with twill for convenience.)
A `Python API` example:
```
from twill.commands import go, showforms, formclear, fv, submit
go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()
formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()
submit('0')
``` | Use [mechanize](http://wwwsearch.sourceforge.net/mechanize/). Other than executing JavaScript in a page, it's pretty good. | Python WWW macro | [
"",
"python",
"screen-scraping",
""
] |
In C#(.NET), what are the regular "formatting" standards?
For instance, for parameter names, so far I noticed camelCase with no prefix, is that right?
For object names, camelCase and no prefix either, right?
For namespaces, classes, functions and properties, first letter of the word is capitalized and there is no prefix, is this right (again)?
How are "temporary" objects formatted?
Example:
```
namespace TestNamespace
{
class MyOwnCoolClass
{
MyOwnCoolClass(int length, BinaryWriter writer)
{
BinaryWriter tempbw = new BinaryWriter(length);
return tempbw;
}
}
}
```
(Note: This code is not valid, I know, it's just to demonstrate formatting).
Thanks! | If you use [StyleCop](http://code.msdn.microsoft.com/sourceanalysis), you'll get good consistency with the [Microsoft .NET Design Guidelines for Developing Class Libraries](http://msdn.microsoft.com/en-us/library/ms229042.aspx). StyleCop also enforces several additional things like spacing, ordering of items in a file, and naming of non-public code elements. | Full guidelines from Microsoft can be found in the [Class Design Guidelines](http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx). It's old, but I haven't yet found anything updated on MSDN, and I believe it is still the standard set reccomendations | What are the C# "formatting" standards? | [
"",
"c#",
".net",
"formatting",
"standards",
""
] |
Recently, I have worked in a project were TDD (Test Driven Development) was used. The project was a web application developed in Java and, although unit-testing web applications [may not be trivial](http://codebetter.com/blogs/ian_cooper/archive/2008/07/07/tdd-and-hard-to-test-areas-part1.aspx), it was possible using mocking (we have used the Mockito framework).
Now I will start a project where I will use C++ to work with image processing (mostly image segmentation) and I'm not sure whether using TDD is a good idea. The problem is that is very hard to tell whether the result of a segmentation is right or not, and the same problem applies to many other image processing algorithms.
So, what I would like to know is if someone here have successfully used TDD with image segmentation algorithms (not necessarily segmentation algorithms). | The image processing tests that you describe in your question take place at a much higher level than most of the tests that you will write using TDD.
In a true [Test Driven Development](http://en.wikipedia.org/wiki/Test_driven_development) process you will first write a failing test before adding any new functionality to your software, then write the code that causes the test to pass, rinse and repeat.
This process yields a large library of [Unit Tests](http://en.wikipedia.org/wiki/Unit_testing), sometimes with more [LOC](http://en.wikipedia.org/wiki/Source_lines_of_code) of tests than functional code!
Because your analytic algorithms have structured behavior, they would be an excellent match for a TDD approach.
But I think the question you are really asking is "how do I go about executing a suite of [Integration Tests](http://en.wikipedia.org/wiki/Integration_testing) against fuzzy image processing software?" You might think I am splitting hairs, but this distinction between Unit Tests and Integration Tests really gets to the heart of what Test Driven Development means. The benefits of the TDD process come from the rich supporting fabric of Unit Tests more than anything else.
In your case I would compare the Integration Test suite to automated performance metrics against a web application. We want to accumulate a historical record of execution times, but we probably don't want to explicitly fail the build for a single poorly performing execution (which might have been affected by network congestion, disk I/O, whatever). You might set some loose tolerances around performance of your test suite and have the [Continuous Integration](http://en.wikipedia.org/wiki/Continuous_integration) server kick out daily reports that give you a high level overview of the performance of your algorithm. | at a minimum you can use the tests for regression testing. For example, suppose you have 5 test images for a particular segmentation algorithm. You run the 5 images through the code and manually verify the results. The results, when correct, are stored on disk somewhere, and future executions of these tests compare the generated results to the stored results.
that way, if you ever make a breaking change, you'll catch it, but more importantly you only have to go through a (correct) manual test cycle once. | Is it possible to use TDD with image processing algorithms? | [
"",
"c++",
"unit-testing",
"testing",
"image-processing",
""
] |
In python you can do something like this:
```
arr = list(set(randint(-50, 50) for _ in range(10)))
```
I do know how to program a extension method that fills a array, list or whatever you need with random values.
I find this cumbersome though, and I really admire how you can do it in python.
Although, I only know of `Enumerable.Range,` which only can be used for generating fixed sequences, to my knowledge.
Is it possible in C# as well? | You could do like this:
```
Random rnd = new Random();
List<int> = Enumerable.Range(0,10).Select(n => rnd.Next(-50, 51)).ToList();
``` | ```
var r = new Random();
var l = Enumerable.Range(0, 10).Select(x => r.Next(100) - 50).ToList();
``` | Fill List<int> using LINQ | [
"",
"c#",
"linq",
"random",
""
] |
we have a number of c# projects that all depend on a common DLL (also c#). this DLL changes somewhat frequency as we're in an environment where we need to be able to build and deploy updated code frequently. the problem with this is, if one of these updates requires a change to the common DLL, we end up with several client apps that all have slightly different versions of the DLL.
we're trying to figure out how to improve this setup, so we can guarantee that anyone can check out a project (we use SVN) and be able to build it without issue. it seems like tagging each and every DLL change to a new version is excessive, but I'm not sure what the "right" solution is (or at least something elegant).
it would be ideal if any solution allowed a developer to be able to step into the DLL code from visual studio, which only seems to be possible if you have the project itself on your machine (might be wrong there). | Frankly, I think versioning your DLL in source control is the RIGHT solution.
It's very possible that a quickly changing core DLL could cause binary and source compatibility in a client project. By versioning, you can prevent each project from using the new DLL until you're ready to migrate.
This provides a level of safety - you know you won't break a client's project because somebody else changed something underneath you, but it's very easy to upgrade at any time to the new version.
Versioning in SVN is trivial - so I wouldn't let this be an issue. It's also safer from a business perspective, since you have a very clear "paper trail" of what version was used with a given deliverable of a client project, which has many benefits in terms of billing, tracking, testability, etc. | There's no easy solution - and the previous two answers are possibly the more accepted method of achieving what you want. If you had a CI environment, and were able to roll out all of your apps on-demand from a store that was built via CI, then you could avoid this problem. That can be lofty ambition, though, if there are old apps in there not governed by tests etc.
If your application is .Net 3.5 (might even need the SP1 too) then did you know that assemblies that are loaded from the network now no longer have any trust restrictions? This means that you could configure an assembly path on the machines in question to point to a shared, highly available, network location - and have all of your apps locate the assembly from there.
An alternative to this, but which would achieve the same goal, would be to build a component that hooks into the AppDomain.CurrentDomain.AssemblyResolve event - which is fired whenever the runtime can't auto-discover an assembly - and do a manual search in that network location for the dll in question (if you were to take the AssemblyName portion of the Full Name, append .dll to it, then you'd be reproducing the same search that the .Net Fusion binder performs anyway).
Just a thought ;) | handling dependencies to a frequently-changing DLL | [
"",
"c#",
"svn",
"dependencies",
""
] |
Assume the following strings:
* `A01B100`
* `A01.B100`
* `A01`
* `A01............................B100` ( whatever between A and B )
The thing is, the numbers should be `\d+`, and in all of the strings A will always be present, while B may not. A will always be followed by one or more digits, and so will B, if present. What regex could I use to capture A and B's digit?
I have the following regex:
```
(A(\d+)).*?(B?(\d+)?)
```
but this only works for the first and the third case. | * Must `A` precede `B`? Assuming yes.
* Can `B` appear more than once? Assuming no.
* Can `B` appear except as part of a `B`-number group? Assuming no.
Then,
```
A\d+.*?(B\d+)?
```
using the lazy .\*? or
```
A\d+[^B]*(B\d+)?
```
which is more efficient but requires that `B` be a single character.
EDIT: Upon further reflection, I have parenthesized the patterns in a less-than-perfect way. The following patterns should require fewer assumptions:
```
A\d+(.*?B\d+)?
a\d+([^B]*B\d+)?
``` | ```
(?ms)^A(\d+)(?:[^\n\r]*B(\d+))?$
```
Assuming one string per line:
* the [^\n\r]\* is a non-greedy match for any characters (except newlines) after Axx, meaing it could gobble an intermediate Byy before the last B:
A01...B01...B23
would be matched, with 01 and 23 detected. | What regex can I use to capture groups from this string? | [
"",
"python",
"regex",
""
] |
I want to use 56K modem for getting telephone number of who calls the home phone. Is there a way to achieve this with C# ? | Not all modems support caller ID. And for those that do, the implementation varies between manufacturers.
There caller ID is passed through the serial data so you will have to use the [TAPI library](http://msdn.microsoft.com/en-us/library/ms737220%28VS.85%29.aspx) (or Windows' HyperTerminal to test it). The caller ID number typically appears between the first and the second ring.
You will need to issue a command to the modem to activate caller ID. Typically:
> `AT#CID=1` (or `AT+VCID=1`)
>
> > OK
Check the documentation for your modem.
When a call comes in, the modem will receive the a call string. Typically:
> `RING`
Then the caller ID text will come in. If I am remembering correctly, it will be in the form:
> `NMBR=XXXXXXXXXX`
*[I am looking for a reference. I will post a link when I can find it]*
**UPDATE**: Ah, found one. Check out this page for the commands and connection strings for for various modems:
[How to Test a Modem for Caller ID Support](http://www.mtnsys.com/Pages/howto/htmdmtst.htm) | It is possible, but there are some things about it you should note:
* You still have to have caller ID supported by your carrier/provider. A basic POTS line won't include this information unless the carrier has done some extra work to add it. So you can't do this to avoid paying an extra caller ID fee.
* It's not built into .Net. You'll have to call into the basic [TAPI](https://learn.microsoft.com/en-us/windows/win32/tapi/tapi-2-2-start-page) library. I've never worked with this library myself, so that's as much as I can tell you. | How to get Caller ID in C#? | [
"",
"c#",
"serial-port",
"modem",
"hardware-interface",
"caller-id",
""
] |
While searching SO for approaches to error handling related to business rule validation, all I encounter are examples of structured exception handling.
MSDN and many other reputable development resources are very clear that exceptions are *not to be used to handle routine error cases.* They are only to be used for exceptional circumstances and unexpected errors that may occur from improper use by the programmer (but not the user.) In many cases, user errors such as fields that are left blank are common, and things which our program *should* expect, and therefore are not exceptional and not candidates for use of exceptions.
QUOTE:
> Remember that the use of the term
> exception in programming has to do
> with the thinking that an exception
> should represent an exceptional
> condition. Exceptional conditions, by
> their very nature, do not normally
> occur; so **your code should not throw
> exceptions as part of its everyday
> operations.**
>
> **Do not throw exceptions to signal
> commonly occurring events.** Consider
> using alternate methods to communicate
> to a caller the occurrence of those
> events and **leave the exception
> throwing for when something truly out
> of the ordinary happens.**
For example, proper use:
```
private void DoSomething(string requiredParameter)
{
if (requiredParameter == null) throw new ArgumentExpcetion("requiredParameter cannot be null");
// Remainder of method body...
}
```
Improper use:
```
// Renames item to a name supplied by the user. Name must begin with an "F".
public void RenameItem(string newName)
{
// Items must have names that begin with "F"
if (!newName.StartsWith("F")) throw new RenameException("New name must begin with /"F/"");
// Remainder of method body...
}
```
In the above case, according to best practices, it would have been better to pass the error up to the UI without involving/requiring .NET's exception handling mechanisms.
Using the same example above, suppose one were to need to enforce a set of naming rules against items. What approach would be best?
1. Having the method return a
enumerated result?
RenameResult.Success,
RenameResult.TooShort,
RenameResult.TooLong,
RenameResult.InvalidCharacters, etc.
2. Using an event in a controller class
to report to the UI class? The UI calls the
controller's RenameItem method, and then handles an
AfterRename event that the controller raises and
that has rename status as part of the event args?
3. The controlling class directly references
and calls a method from the UI class that
handles the error, e.g. ReportError(string text).
4. Something else... ?
Essentially, I want to know how to perform complex validation in classes that may not be the Form class itself, and pass the errors back to the Form class for display -- but I do not want to involve exception handling where it should not be used (even though it seems much easier!)
---
Based on responses to the question, I feel that I'll have to state the problem in terms that are more concrete:
UI = User Interface, BLL = Business Logic Layer (in this case, just a different class)
1. User enters value within UI.
2. UI reports value to BLL.
3. BLL performs routine validation of the value.
4. BLL discovers rule violation.
5. BLL returns rule violation to UI.
6. UI recieves return from BLL and reports error to user.
Since it is routine for a user to enter invalid values, exceptions should not be used. What is the right way to do this without exceptions? | The example you give is of UI validating inputs.
Therefore, a good approach is to separate the validation from the action. WinForms has a built in validation system, but in principle, it works along these lines:
```
ValidationResult v = ValidateName(string newName);
if (v == ValidationResult.NameOk)
SetName(newName);
else
ReportErrorAndAskUserToRetry(...);
```
In addition, you can apply the validation in the SetName method to ensure that the validity has been checked:
```
public void SetName(string newName)
{
if (ValidateName(newName) != ValidationResult.NameOk)
throw new InvalidOperationException("name has not been correctly validated");
name = newName;
}
```
(Note that this may not be the best approach for performance, but in the situation of applying a simple validation check to a UI input, it is unlikely that validating twice will be of any significance. Alternatively, the above check could be done purely as a debug-only assert check to catch any attempt by programmers to call the method without first validating the input. Once you know that all callers are abiding by their contract, there is often no need for a release runtime check at all)
To quote another answer:
```
Either a member fulfills its contract or it throws an exception. Period.
```
The thing that this misses out is: What is the contract? It is perfectly reasonable to state in the "contract" that a method returns a status value. e.g. File.Exists() returns a status code, not an exception, because that is its contract.
However, your example is different. In it, you actually do two separate actions: validation and storing. If SetName can either return a status code *or* set the name, it is trying to do two tasks in one, which means that the caller never knows which behaviour it will exhibit, and has to have special case handling for those cases. However, if you split SetName into separate Validate and Store steps, then the contract for StoreName can be that you pass in valid inputs (as passed by ValidateName), and it throws an exception if this contract is not met. Because each method then does one thing and one thing only, the contract is very clear, and it is obvious when an exception should be thrown. | I think you've gotten the wrong impression of the intended message. Here's a great quote I ran across yesterday from the [current edition of Visual Studio magazine](https://visualstudiomagazine.com/Articles/2009/08/01/Working-Effectively-with-Exceptions.aspx) (Vol 19, No 8).
> Either a member fulfills its contract or it throws an excetion. Period. No middle ground. No return codes, no sometimes it works, sometimes it doesn't.
Exceptions should be used with care as they are expensive to create and throw--but they are, however, the .NET framework's way of notifying a client (by that I mean any calling component) of an error. | Error Handling without Exceptions | [
"",
"c#",
".net",
"winforms",
"exception",
"error-handling",
""
] |
I am planning to create a screen saver. Thinking of trying out some WPF as well. Anyways, I am not quite sure how I would organize the screen saver on disk in the file system. I have mainly two related issues that I am very uncertain on how to solve:
1. Normally an application lives, with all its 3rd party assemblies, static resources, images, etc., in the Program Files folder and is run from there. For example *C:\Program Files\MyScreenSaver*. But (if I haven't missed something) the executable of a screen saver in windows need to have the scr extension and to live in the system folder, for example *C:\Windows\System32*. How do you program the screen saver so that it can find the "rest of itself"? Would you use the windows registry? Or creat some sort of config file next to the scr file with the path to the rest? And would you make the scr to just be sort of a launcher of an exe in the application folder? Or would this be a bad idea?
2. I also want the screen saver to download new content from certain places on the internet. But where do I put it, and how does the screen saver find it? If I have understood correctly, an application is not to create new contents in its application folder, but rather in a user folder. How do I find that folder? Do you build it up from environment variables? And in what specific directory should things like this really be in? For example on Vista I see that you have one folder called *C:\ProgramData*. You also have *C:\Users\username\AppData\Local*, *C:\Users\username\AppData\LocalLow* and *C:\Users\username\AppData\Roaming*. Have also seen a lot of programs dump stuff in the my documents folder (although I hate programs cluttering up my documents folder, so I will probably try to avoid that :p).
What are some best practices when it comes to these issues of laying out your application in the file system? I am want it to be best and "most correct" for Windows 7, which means it will probably work the same in Vista as well (?), but it would also need to work in XP, since *a lot* of people are using that still. | For a screen saver I'd try to put most of it in the .exe (.scr) file. It might make the executable quite big but I think it's worth it.
For the downloaded content use application data folder, or maybe allow user to set the location (put the path in registry). For example if you are downloading images, the user might want to put that in My Pictures folder. | I'm still using XP :)
System.Environment.SpecialFolders is what you want for these special locations.
Say,
```
System.Environment.SpecialFolder.LocalApplicationData
``` | C#: How would you organize a screen saver in the file system? | [
"",
"c#",
"installation",
"filesystems",
"screensaver",
""
] |
I'd like to display my page differently for the visitor based on if they came from a search engine or not. I guess I'm detecting search engine referrals? I'd also like to know the search terms used to arrive at my site.
My solution so far is this:
1) Filter on the HTTP request referers which contain common search engine URLs, i.e. <http://www.google.com/search>, <http://www.bing.com/search>, or <http://search.yahoo.com/search>
2) Parse the query string parameter of the referer for the search terms, e.g. "q=search+terms+for+my+website+go+here"
I feel this isn't the most robust solution, because it misses lesser known search engines and each search engine may have it's own query string parameter for the search terms. For example, Google's and Bing's search term parameter are both "q" but Yahoo's is "p" as far as I can tell. And what about special operators like +, -, etc.?
Is there a more general way to do this? Or is there a library that would help me handle more search engines? I'm working with Java running on Tomcat, but ideas from any language and server setup are welcome. | Have a look here:
<http://www.gdargaud.net/Hack/Searches.html>
and here:
<http://search.cpan.org/perldoc?URI::ParseSearchString>
2 slightly different approaches but they cover a much wider range of search engines and their referer strings. | In case of PHP, you request the $\_REQUEST["HTTP\_REFERRER"] and parse the search-string with some pregs or eregs. | Is a visitor to my website coming from a search engine? What were their search terms? | [
"",
"java",
"tomcat",
"search-engine",
"referrals",
""
] |
I am trying to read some text files, where each line needs to be processed. At the moment I am just using a StreamReader, and then reading each line individually.
I am wondering whether there is a more efficient way (in terms of LoC and readability) to do this using LINQ without compromising operational efficiency. The examples I have seen involve loading the whole file into memory, and then processing it. In this case however I don't believe that would be very efficient. In the first example the files can get up to about 50k, and in the second example, not all lines of the file need to be read (sizes are typically < 10k).
You could argue that nowadays it doesn't really matter for these small files, however I believe that sort of the approach leads to inefficient code.
First example:
```
// Open file
using(var file = System.IO.File.OpenText(_LstFilename))
{
// Read file
while (!file.EndOfStream)
{
String line = file.ReadLine();
// Ignore empty lines
if (line.Length > 0)
{
// Create addon
T addon = new T();
addon.Load(line, _BaseDir);
// Add to collection
collection.Add(addon);
}
}
}
```
Second example:
```
// Open file
using (var file = System.IO.File.OpenText(datFile))
{
// Compile regexs
Regex nameRegex = new Regex("IDENTIFY (.*)");
while (!file.EndOfStream)
{
String line = file.ReadLine();
// Check name
Match m = nameRegex.Match(line);
if (m.Success)
{
_Name = m.Groups[1].Value;
// Remove me when other values are read
break;
}
}
}
``` | You can write a LINQ-based line reader pretty easily using an iterator block:
```
static IEnumerable<SomeType> ReadFrom(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
SomeType newRecord = /* parse line */
yield return newRecord;
}
}
}
```
or to make Jon happy:
```
static IEnumerable<string> ReadFrom(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
yield return line;
}
}
}
...
var typedSequence = from line in ReadFrom(path)
let record = ParseLine(line)
where record.Active // for example
select record.Key;
```
then you have `ReadFrom(...)` as a lazily evaluated sequence without buffering, perfect for `Where` etc.
Note that if you use `OrderBy` or the standard `GroupBy`, it will have to buffer the data in memory; ifyou need grouping and aggregation, "PushLINQ" has some fancy code to allow you to perform aggregations on the data but discard it (no buffering). Jon's explanation [is here](http://codeblog.jonskeet.uk/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation/). | It's simpler to read a line and check whether or not it's null than to check for EndOfStream all the time.
However, I also have a `LineReader` class in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) which makes all of this a lot simpler - basically it exposes a file (or a `Func<TextReader>` as an `IEnumerable<string>` which lets you do LINQ stuff over it. So you can do things like:
```
var query = from file in Directory.GetFiles("*.log")
from line in new LineReader(file)
where line.Length > 0
select new AddOn(line); // or whatever
```
The heart of `LineReader` is this implementation of `IEnumerable<string>.GetEnumerator`:
```
public IEnumerator<string> GetEnumerator()
{
using (TextReader reader = dataSource())
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
```
Almost all the rest of the source is just giving flexible ways of setting up `dataSource` (which is a `Func<TextReader>`). | Reading a file line by line in C# | [
"",
"c#",
"linq",
"line",
""
] |
I'm writing an application that will have multiple threads running, and want to throttle the CPU/memory usage of those threads.
There is a [similar question for C++](https://stackoverflow.com/questions/1982/cpu-throttling-in-c), but I want to try and avoid using C++ and JNI if possible. I realize this might not be possible using a higher level language, but I'm curious to see if anyone has any ideas.
**EDIT:** Added a bounty; I'd like some really good, well thought out ideas on this.
**EDIT 2:** The situation I need this for is executing other people's code on my server. Basically it is completely arbitrary code, with the only guarantee being that there will be a main method on the class file. Currently, multiple completely disparate classes, which are loaded in at runtime, are executing concurrently as separate threads.
The way it's written, it would be a pain to refactor to create separate processes for each class that gets executed. If that's the only good way to limit memory usage via the VM arguments, then so be it. But I'd like to know if there's a way to do it with threads. Even as a separate process, I'd like to be able to somehow limit its CPU usage, since as I mentioned earlier, several of these will be executing at once. I don't want an infinite loop to hog up all the resources.
**EDIT 3:** An easy way to approximate object size is with java's [Instrumentation](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/Instrumentation.html) classes; specifically, the getObjectSize method. Note that there is some special setup needed to use this tool. | If I understand your problem, one way would be to adaptively sleep the threads, similarly as video playback is done in Java. If you know you want 50% core utilization, the your algorithm should sleep approximately 0.5 seconds - potentially distributed within a second (e.g. 0.25 sec computation, 0.25 sec sleep, e.t.c.). Here is an [example](http://code.google.com/p/open-ig/source/browse/trunk/open-ig/src/hu/openig/ani/Player.java) from my video player.
```
long starttime = 0; // variable declared
//...
// for the first time, remember the timestamp
if (frameCount == 0) {
starttime = System.currentTimeMillis();
}
// the next timestamp we want to wake up
starttime += (1000.0 / fps);
// Wait until the desired next time arrives using nanosecond
// accuracy timer (wait(time) isn't accurate enough on most platforms)
LockSupport.parkNanos((long)(Math.max(0,
starttime - System.currentTimeMillis()) * 1000000));
```
This code will sleep based on the frames/second value.
To throttle the memory usage, you could wrap your object creation into a factory method, and use some kind of semaphore with a limited permits as bytes to limit the total estimated object size (you need to estimate the size of various objects to ration the semaphore).
```
package concur;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class MemoryLimited {
private static Semaphore semaphore = new Semaphore(1024 * 1024, true);
// acquire method to get a size length array
public static byte[] createArray(int size) throws InterruptedException {
// ask the semaphore for the amount of memory
semaphore.acquire(size);
// if we get here we got the requested memory reserved
return new byte[size];
}
public static void releaseArray(byte[] array) {
// we don't need the memory of array, release
semaphore.release(array.length);
}
// allocation size, if N > 1M then there will be mutual exclusion
static final int N = 600000;
// the test program
public static void main(String[] args) {
// create 2 threaded executor for the demonstration
ExecutorService exec = Executors.newFixedThreadPool(2);
// what we want to run for allocation testion
Runnable run = new Runnable() {
@Override
public void run() {
Random rnd = new Random();
// do it 10 times to be sure we get the desired effect
for (int i = 0; i < 10; i++) {
try {
// sleep randomly to achieve thread interleaving
TimeUnit.MILLISECONDS.sleep(rnd.nextInt(100) * 10);
// ask for N bytes of memory
byte[] array = createArray(N);
// print current memory occupation log
System.out.printf("%s %d: %s (%d)%n",
Thread.currentThread().getName(),
System.currentTimeMillis(), array,
semaphore.availablePermits());
// wait some more for the next thread interleaving
TimeUnit.MILLISECONDS.sleep(rnd.nextInt(100) * 10);
// release memory, no longer needed
releaseArray(array);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
// run first task
exec.submit(run);
// run second task
exec.submit(run);
// let the executor exit when it has finished processing the runnables
exec.shutdown();
}
}
``` | Care of [Java Forums](http://www.java-forums.org/new-java/5303-how-determine-cpu-usage-using-java.html). Basically timing your execution and then waiting when your taking too much time. As is mentioned in the original thread, running this in a separate thread and interrupting the work thread will give more accurate results, as will averaging values over time.
```
import java.lang.management.*;
ThreadMXBean TMB = ManagementFactory.getThreadMXBean();
long time = new Date().getTime() * 1000000;
long cput = 0;
double cpuperc = -1;
while(true){
if( TMB.isThreadCpuTimeSupported() ){
if(new Date().getTime() * 1000000 - time > 1000000000){ //Reset once per second
time = new Date().getTime() * 1000000;
cput = TMB.getCurrentThreadCpuTime();
}
if(!TMB.isThreadCpuTimeEnabled()){
TMB.setThreadCpuTimeEnabled(true);
}
if(new Date().getTime() * 1000000 - time != 0)
cpuperc = (TMB.getCurrentThreadCpuTime() - cput) / (new Date().getTime() * 1000000.0 - time) * 100.0;
}
//If cpu usage is greater then 50%
if(cpuperc > 50.0){
//sleep for a little bit.
continue;
}
//Do cpu intensive stuff
}
``` | Throttling CPU/Memory usage of a Thread in Java? | [
"",
"java",
"memory",
"multithreading",
"cpu",
"throttling",
""
] |
Okay, this is probably very simple but, I have the below "checks" `(not at the same time)` and the *First* **ALWAYS** evaluates to TRUE while the *Second* **SEEMS** to work. This actually happens in each place that the row value is a number or bool`(Date seems fine...)`.
If I walk through the code in *Debug* it shows the value of `row["PersonID"]` as **162434**, the same as `tbxPersonID.EditValue`. Is this just a basic and beginner truth about programming that I missed in my `hodge-podge-self-education`?
It seems, if I *cast* everything in question to a `string` first, I will be fine I would just like to know if I am correct and if there is a general rule as to what `Types` I would need to do this for?
## Doesn't Work
```
if (row["PersonID"] != tbxPersonID.EditValue)
{
row["PersonID"] = tbxPersonID.EditValue;
}
if (row["CitizenFlag"] != chkCitizen.EditValue)
{
row["CitizenFlag"] = chkCitizen.EditValue;
_whatChanged.Add("CitizenFlag");
}
```
## Works
```
if (row["PersonID"].ToString() != tbxPersonID.EditValue.ToString())
{
row["PersonID"] = tbxPersonID.EditValue;
}
if (row["CitizenFlag"].ToString() != chkCitizen.EditValue.ToString())
{
row["CitizenFlag"] = chkCitizen.EditValue;
_whatChanged.Add("CitizenFlag");
}
``` | `row["PersonID"]` is of type object, which means that != and == will use *reference identity*. Basically you're comparing boxed values.
If you use:
```
if (!object.Equals(row["PersonID"], tbxPersonID.EditValue))
```
then you'll get *value equality* semantics, and I suspect you'll be okay - assuming that tbxPersonID really *is* an `int`, either boxed or not.
Just to make things concrete, here's a short but complete example to show what I'm talking about:
```
using System;
class Test
{
static void Main()
{
object first = 2;
object second = 2;
// Compares reference equality: false
Console.WriteLine(first == second);
// Compares value equality: true
Console.WriteLine(object.Equals(first, second));
}
}
``` | Whats the type of EditValue or the right hand value? The problem is probably that EditValue is not of type string (maybe its a subclass or something) therefore when you are doing != or == on it its doing a memory address compare instead of the compare for a string therefore you are getting false instead of true | Comparing expressions of type object | [
"",
"c#",
".net",
"types",
"typechecking",
""
] |
I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.
Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:
The async stuff works like a charm, but when I connect to 100 hosts, and I get 100 timeouts (timeout = 10 secs) then I wait 1000 seconds, just to find out all my connections failed.
Is there any way to also get non blocking socket connects?
My socket is already set to nonBlocking, but calls to connect() are still blocking.
Reducing the timeout is not an acceptable solution.
I am doing this in Python, but I guess the programming language doesnt really matter in this case.
Do I really need to use threads? | You need to parallelize the connects as well, since the sockets block when you set a timeout. Alternatively, you could not set a timeout, and use the select module.
You can do this with the dispatcher class in the [asyncore](http://docs.python.org/library/asyncore.html#module-asyncore) module. Take a look at the basic [http client example](http://docs.python.org/library/asyncore.html#asyncore-example-basic-http-client). Multiple instances of that class won't block each other on connect. You can do this just as easily using threads, and I think makes tracking socket timeouts easier, but since you're already using asynchronous methods you might as well stay on the same track.
As an example, the following works on all my linux systems
```
import asyncore, socket
class client(asyncore.dispatcher):
def __init__(self, host):
self.host = host
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, 22))
def handle_connect(self):
print 'Connected to', self.host
def handle_close(self):
self.close()
def handle_write(self):
self.send('')
def handle_read(self):
print ' ', self.recv(1024)
clients = []
for i in range(50, 100):
clients.append(client('cluster%d' % i))
asyncore.loop()
```
Where in cluster50 - cluster100, there are numerous machines that are unresponsive, or nonexistent. This immediately starts printing:
```
Connected to cluster50
SSH-2.0-OpenSSH_4.3
Connected to cluster51
SSH-2.0-OpenSSH_4.3
Connected to cluster52
SSH-2.0-OpenSSH_4.3
Connected to cluster60
SSH-2.0-OpenSSH_4.3
Connected to cluster61
SSH-2.0-OpenSSH_4.3
...
```
This however does not take into account getaddrinfo, which has to block. If you're having issues resolving the dns queries, everything has to wait. You probably need to gather the dns queries separately on your own, and use the ip addresses in your async loop
If you want a bigger toolkit than asyncore, take a look at [Twisted Matrix](http://twistedmatrix.com/trac/). It's a bit heavy to get into, but it is the best network programming toolkit you can get for python. | Use the [`select`](http://docs.python.org/library/select.html) module. This allows you to wait for I/O completion on multiple non-blocking sockets. Here's [some more information](http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000) on select. From the linked-to page:
> In C, coding `select` is fairly complex.
> In Python, it's a piece of cake, but
> it's close enough to the C version
> that if you understand select in
> Python, you'll have little trouble
> with it in C.
```
ready_to_read, ready_to_write, in_error = select.select(
potential_readers,
potential_writers,
potential_errs,
timeout)
```
> You pass `select` three lists: the first
> contains all sockets that you might
> want to try reading; the second all
> the sockets you might want to try
> writing to, and the last (normally
> left empty) those that you want to
> check for errors. You should note that
> a socket can go into more than one
> list. The `select` call is blocking, but
> you can give it a timeout. This is
> generally a sensible thing to do -
> give it a nice long timeout (say a
> minute) unless you have good reason to
> do otherwise.
>
> In return, you will get three lists.
> They have the sockets that are
> actually readable, writeable and in
> error. Each of these lists is a subset
> (possibly empty) of the corresponding
> list you passed in. And if you put a
> socket in more than one input list, it
> will only be (at most) in one output
> list.
>
> If a socket is in the output readable
> list, you can be
> as-close-to-certain-as-we-ever-get-in-this-business
> that a `recv` on that socket will return
> something. Same idea for the writeable
> list. You'll be able to `send`
> something. Maybe not all you want to,
> but something is better than nothing.
> (Actually, any reasonably healthy
> socket will return as writeable - it
> just means outbound network buffer
> space is available.)
>
> If you have a "server" socket, put it
> in the potential\_readers list. If it
> comes out in the readable list, your
> accept will (almost certainly) work.
> If you have created a new socket to
> connect to someone else, put it in the
> potential\_writers list. If it shows up
> in the writeable list, you have a
> decent chance that it has connected. | How can I get non-blocking socket connect()'s? | [
"",
"python",
"sockets",
"asynchronous",
"nonblocking",
""
] |
It seems to me that built-in functions `__repr__` and `__str__` have an important difference in their base definition.
```
>>> t2 = u'\u0131\u015f\u0131k'
>>> print t2
ışık
>>> t2
Out[0]: u'\u0131\u015f\u0131k'
```
`t2.decode` raises an error since `t2` is a unicode string.
```
>>> enc = 'utf-8'
>>> t2.decode(enc)
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
```
`__str__` raises an error as if `decode()` function is being called:
```
>>> t2.__str__()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
```
but `__repr__` works without problem:
```
>>> t2.__repr__()
Out[0]: "u'\\u0131\\u015f\\u0131k'"
```
Why does `__str__` produce an error whereas `__repr__` work properly?
This small difference seems to cause a bug in one django application that I am working on. | Basically, `__str__` can only output ascii strings. Since t2 contains unicode codepoints above ascii, it cannot be represented with just a string. `__repr__`, on the other hand, tries to output the python code needed to recreate the object. You'll see that the output from repr(t2) (this syntax is preferred to `t2.__repr_()`) is exactly what you set t2 equal to up on the first line. The result from repr looks roughly like ['\', 'u', '0', ...], which are all ascii values, but the output from str is trying to be [chr(0x0131), chr(0x015f), chr(0x0131), 'k'], most of which are above the range of characters acceptable in a python string. Generally, when dealing with django applications, you should use `__unicode__` for everything, and never touch `__str__`.
More info in [the django documentation on strings](http://www.djangoproject.com/documentation/models/str/). | In general, calling `str.__unicode__()` or `unicode.__str__()` is a very bad idea, because bytes can't be safely converted to Unicode character points and vice versa. The exception is ASCII values, which are generally the same in all single-byte encodings. The problem is that you're using the wrong method for conversion.
To convert `unicode` to `str`, you should use `encode()`:
```
>>> t1 = u"\u0131\u015f\u0131k"
>>> t1.encode("utf-8")
'\xc4\xb1\xc5\x9f\xc4\xb1k'
```
To convert `str` to `unicode`, use `decode()`:
```
>>> t2 = '\xc4\xb1\xc5\x9f\xc4\xb1k'
>>> t2.decode("utf-8")
u'\u0131\u015f\u0131k'
``` | Does __str__() call decode() method behind scenes? | [
"",
"python",
"django",
"string",
"unicode",
""
] |
I have a form that uses PHP to calculate a total based on the selections that the user makes. There are 13 selections total. There are two sections that I am stuck on, "Blue" and "Orange":
If the User selects "Blue", $250.00 is added to the price
If the User selects "Orange", $150.00 is added to the price
The thing I am trying to figure out: I would like to make it so that if the user selects Blue, and then goes on to select Orange - the charge for Orange would not be added to the total. On the other hand, if they did not select Blue, and went on to select Orange, I would want the $150.00 to get added to the total.
The only way that I can think of to explain it is that if you buy Blue, Orange is included.
Here is my HTML:
BLUE
Yes
No
ORANGE
Yes
No
Here is my PHP:
```
<?php
$one = $_POST ['one'];
$two = $_POST ['two'];
$three = $_POST ['three'];
$four = $_POST ['four'];
$five = $_POST ['five'];
$six = $_POST ['six'];
$seven = $_POST ['seven'];
$eight = $_POST ['eight'];
$nine = $_POST ['nine'];
$ten = $_POST ['ten'];
$eleven = $_POST ['eleven'];
$twelve = $_POST ['twelve'];
$thirteen = $_POST ['thirteen'];
$total = ($_POST['one'] + $_POST['two'] + $_POST['three'] + $_POST['four']
+ $_POST['five'] + $_POST['six'] + $_POST['seven'] + $_POST['eight']+
$_POST['nine'] + $_POST['ten']+ $_POST['eleven'] +
$_POST['twelve']+ $_POST['thirteen']);
```
Someone told me that I should make it so that:
```
$four = $_POST ['four']- $_POST ['six'];
```
and that works fine, except that even if Blue (four) is not selected, and Orange (six) is, the value for Orange will not get added to the total. Should I be using an if/else statement or something? Also, this form does not need to be secure. Thanks in advance for any ideas. | Yes, an if/else is the way to go. You can accomplish this in-line with the [ternary operator](http://php.net/ternary).
Change this:
```
$total = ($_POST['one'] + $_POST['two'] + $_POST['three'] + $_POST['four']
+ $_POST['five'] + $_POST['six'] + $_POST['seven'] + $_POST['eight']+
$_POST['nine'] + $_POST['ten']+ $_POST['eleven'] +
$_POST['twelve']+ $_POST['thirteen']);
```
To this:
```
$total = ($_POST['one'] + $_POST['two'] + $_POST['three'] + $_POST['four']
+ $_POST['five'] + (($_POST['four'] > 0) ? 0 : $_POST['six']) + $_POST['seven'] + $_POST['eight']+
$_POST['nine'] + $_POST['ten']+ $_POST['eleven'] +
$_POST['twelve']+ $_POST['thirteen']);
```
This assumes that your $\_POST values are integers. | If Orange is included when you get Blue, then it probably shouldn't be 2 different yes/no choices.
Instead, it should more likely be one question:
---
Which plan would you like?
Orange (150)
Blue (250) | How would I add a PHP statement to conditionally subtract? | [
"",
"php",
"webforms",
"calculator",
""
] |
I have a simple C++ with Boost like this:
```
#include <boost/algorithm/string.hpp>
int main()
{
std::string latlonStr = "hello,ergr()()rg(rg)";
boost::find_format_all(latlonStr,boost::token_finder(boost::is_any_of("(,)")),boost::const_formatter(" "));
```
This works fine; it replaces every occurrence of ( ) , with a " "
However, I get this warning when compiling:
I'm using MSVC 2008, Boost 1.37.0.
```
1>Compiling...
1>mainTest.cpp
1>c:\work\minescout-feat-000\extlib\boost\algorithm\string\detail\classification.hpp(102) : warning C4996: 'std::copy': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\xutility(2576) : see declaration of 'std::copy'
1> c:\work\minescout-feat-000\extlib\boost\algorithm\string\classification.hpp(206) : see reference to function template instantiation 'boost::algorithm::detail::is_any_ofF<CharT>::is_any_ofF<boost::iterator_range<IteratorT>>(const RangeT &)' being compiled
1> with
1> [
1> CharT=char,
1> IteratorT=const char *,
1> RangeT=boost::iterator_range<const char *>
1> ]
1> c:\work\minescout-feat-000\minescouttest\maintest.cpp(257) : see reference to function template instantiation 'boost::algorithm::detail::is_any_ofF<CharT> boost::algorithm::is_any_of<const char[4]>(RangeT (&))' being compiled
1> with
1> [
1> CharT=char,
1> RangeT=const char [4]
1> ]
```
I could certainly disable the warning using
```
-D_SCL_SECURE_NO_WARNINGS
```
but I'm a bit reluctant to do that before I find out what's wrong, or more importantly if my code is incorrect. | It is nothing to worry about. In the last few releases of MSVC, they've gone into full security-paranoia mode. `std::copy` issues this warning when it is used with raw pointers, because *when used incorrectly*, it can result in buffer overflows.
Their iterator implementation performs bounds checking to ensure this doesn't happen, at a significant performance cost.
So feel free to ignore the warning. It doesn't mean there's anything wrong with your code. It is just saying that *if* there is something wrong with your code, then bad things will happen.
Which is an odd thing to issue warnings about. ;) | You can also disable this warning in specific headers:
```
#if defined(_MSC_VER) && _MSC_VER >= 1400
#pragma warning(push)
#pragma warning(disable:4996)
#endif
/* your code */
#if defined(_MSC_VER) && _MSC_VER >= 1400
#pragma warning(pop)
#endif
``` | C++ Boost: what's the cause of this warning? | [
"",
"c++",
"boost",
"compiler-warnings",
""
] |
I'm working on some C++ code and I've run into a question which has been nagging me for a while... Assuming I'm compiling with GCC on a Linux host for an ELF target, where are global static constructors and destructors called?
I've heard there's a function \_init in crtbegin.o, and a function \_fini in crtend.o. Are these called by crt0.o? Or does the dynamic linker actually detect their presence in the loaded binary and call them? If so, *when* does it actually call them?
I'm mainly interested to know so I can understand what's happening behind the scenes as my code is loaded, executed, and then unloaded at runtime.
Thanks in advance!
Update: I'm basically trying to figure out the general time at which the constructors are called. I don't want to make assumptions in my code based on this information, it's more or less to get a better understanding of what's happening at the lower levels when my program loads. I understand this is quite OS-specific, but I have tried to narrow it down a little in this question. | When talking about non-local static objects there are not many guarantees. As you already know (and it's also been mentioned here), it should not write code that depends on that. The static initialization order fiasco...
Static objects goes through a two-phase initialization: static initialization and dynamic initialization. The former happens first and performs zero-initialization or initialization by constant expressions. The latter happens after all static initialization is done. This is when constructors are called, for example.
In general, this initialization happens at some time before main(). However, as opposed to what many people think even that is not guaranteed by the C++ standard. What is in fact guaranteed is that the initialization is done before the use of any function or object defined in the same translation unit as the object being initialized. Notice that this is not OS specific. This is C++ rules. Here's a quote from the Standard:
> It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of
> namespace scope is done before the first statement of main. If the initialization is deferred to some point
> in time after the first statement of main, it shall occur before the first use of any function or object defined
> in the same translation unit as the object to be initialized | This depends heavy on the compiler and runtime. It's not a good idea to make any assumptions on the time global objects are constructed.
This is especially a problem if you have a static object which depends on another one being already constructed.
This is called "[static initialization order fiasco](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12)". Even if thats not the case in your code, the C++Lite FAQ articles on that topic are worth a read. | C++: When (and how) are C++ Global Static Constructors Called? | [
"",
"c++",
"gcc",
"static",
"global",
"constructor",
""
] |
I'm having a hell of a time trying to debug some kind of memory access error, which I believe is a double free. The code is too complex to post, but I can try to describe it.
Basically, I have two threads. When the worker thread is created, it instantiates a `new boost::signal` object, and stores it in a `shared_ptr`. The parent then queries the thread for the signal, and the parent `connect()`s the `shared_ptr` signal to a handler function.
This all works, up until the point where the thread is finished and tries to clean up. Here is a snip of the call stack, in the hopes that someone might see something I missed.
```
ntdll.dll!7c90120e()
ntdll.dll!7c96e139()
ntdll.dll!7c96e576()
ntdll.dll!7c9622e8()
kernel32.dll!7c85f8d7()
Worker.dll!_CrtIsValidHeapPointer(const void * pUserData=0x01788aa8) Line 1807 C
Worker.dll!_free_dbg_lk(void * pUserData=0x01788aa8, int nBlockUse=1) Line 1132 + 0x9 C
Worker.dll!_free_dbg(void * pUserData=0x01788aa8, int nBlockUse=1) Line 1070 + 0xd C
Worker.dll!operator delete(void * pUserData=0x01788aa8) Line 54 + 0x10 C++
Worker.dll!std::allocator<std::_List_nod<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Node>::deallocate(std::_List_nod<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Node * _Ptr=0x01788aa8, unsigned int __formal=1) Line 132 + 0x9 C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::clear() Line 622 C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Tidy() Line 931 C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::~list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >() Line 366 C++
Worker.dll!std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > >::~pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > >() + 0x2e C++
Worker.dll!std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node::~_Node() + 0x12 C++
Worker.dll!std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node::`scalar deleting destructor'() + 0xf C++
Worker.dll!std::_Destroy<std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node>(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Ptr=0x013a3008) Line 50 C++
Worker.dll!std::allocator<std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node>::destroy(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Ptr=0x013a3008) Line 152 + 0x9 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Erase(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Rootnode=0x013a3008) Line 896 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Erase(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Rootnode=0x013a2f48) Line 894 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::clear() Line 782 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::erase(std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::iterator _First={...}, std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::iterator _Last={...}) Line 754 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Tidy() Line 1144 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::~_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >() Line 393 C++
Worker.dll!std::map<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > > >::~map<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > > >() + 0xf C++
Worker.dll!boost::signals::detail::named_slot_map::~named_slot_map() + 0xf C++
Worker.dll!boost::signals::detail::signal_base_impl::~signal_base_impl() Line 33 + 0x1d C++
Worker.dll!boost::signals::detail::signal_base_impl::`scalar deleting destructor'() + 0xf C++
Worker.dll!boost::checked_delete<boost::signals::detail::signal_base_impl>(boost::signals::detail::signal_base_impl * x=0x013a2d98) Line 34 + 0x1c C++
Worker.dll!boost::detail::sp_counted_impl_p<boost::signals::detail::signal_base_impl>::dispose() Line 79 + 0xc C++
Worker.dll!boost::detail::sp_counted_base::release() Line 102 + 0xd C++
Worker.dll!boost::detail::shared_count::~shared_count() Line 209 C++
Worker.dll!boost::shared_ptr<boost::signals::detail::signal_base_impl>::~shared_ptr<boost::signals::detail::signal_base_impl>() + 0x12 C++
Worker.dll!boost::signals::detail::signal_base::~signal_base() Line 184 + 0x8 C++
Worker.dll!boost::signal2<void,enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::~signal2<void,enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >() + 0x77 C++
Worker.dll!boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::~signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >() + 0x2b C++
Worker.dll!boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::`scalar deleting destructor'() + 0x2b C++
Worker.dll!boost::checked_delete<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >(boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > * x=0x013a2cf8) Line 34 + 0x2b C++
Worker.dll!boost::detail::sp_counted_impl_p<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >::dispose() Line 79 + 0xc C++
Worker.dll!boost::detail::sp_counted_base::release() Line 102 + 0xd C++
Worker.dll!boost::detail::shared_count::~shared_count() Line 209 C++
Worker.dll!boost::shared_ptr<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >::~shared_ptr<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >() + 0x2e C++
Worker.dll!CWorker::~CWorker() Line 77 + 0x24 C++
Worker.dll!CWorker::`scalar deleting destructor'() + 0x2b C++
Worker.dll!boost::checked_delete<CSubclass>(CSubclass* x=0x013a2ab0) Line 34 + 0x32 C++
Worker.dll!boost::detail::sp_counted_impl_p<CSubclass>::dispose() Line 79 + 0xc C++
Parent.exe!boost::detail::sp_counted_base::release() Line 102 + 0xd C++
Parent.exe!boost::detail::shared_count::~shared_count() Line 209 C++
Parent.exe!boost::shared_ptr<void>::~shared_ptr<void>() + 0x19 C++
Parent.exe!CWorker::~CWorker() Line 33 + 0x20 C++
```
Any advice would be appreciated. I've been going over this for a few days but can't figure out the issue. | I ran into this a year or two ago and, IIRC, it was caused by not explicitly managing the connections using [`boost::signals::connection` objects](http://www.boost.org/doc/libs/1_35_0/doc/html/signals/s05.html#id1285940). | I know this really isn't helpful, but invest in a tool like Purify. It's really worth it's weight in gold tracking down memory leaks. It probably would have paid for itself by now. | boost signal double free? | [
"",
"c++",
"boost",
"boost-signals",
""
] |
I've generated a self-signed certificate for my Java app using keytool. However, when I go to the site in a browser it always pops up with a warning - saying this site does not own the certificate - is there a way to self-sign/doctor a certificate so I won't get these warnings in a browser? Both server and browser are located on the same host and I navigate to the site using "<http://localhost/>". I do not want to add an exception to the browser because I have tests which run on a big build farm so it is excessive to add an exception to all browsers on all build machines. | You could also setup a self-signed Certificate Authority (CA) using OpenSSL or possibly your Java tool. You can then use that CA to sign a number of server certs.
You are still going to need to manually trust your self-signed CA on all clients that access your test servers, but at least you only have to trust one root CA, rather than a bunch of individual self-signed server certs.
Another option is to check out [CAcert](http://www.cacert.org/). | No, you can't. You might as well ask "How can I make a fake certificate for hsbc.com?"
There are two ways to get a browser to accept a certificate:
* Buy a certificate for a domain from a trusted authority (which means proving to that authority that you own that domain) and then use that domain as the name of your test servers
* Install your signing certificate into the browsers, so that you effectively become a trusted authority for that browser.
Without touching the browsers, there's no other way to do it - how could there be, if the internet is to remain secure? | Can I create self-signed certificate in Java which will be automatically trusted by web browsers? | [
"",
"java",
"ssl",
"ssl-certificate",
"self-signed",
""
] |
i'm developing a read-only weekly calendar view of users's events.
Columns are the days of the week (mon > sun)
Rows are timeslots (8:00>9:00, 9:00>10:00... from 8AM up to 7PM)
Question: what's the best approach to generate that user calendar:
Option 1: pure SQL
I don't even know if that is possible, but i would find it supremelly elegant: have mysql generate a table with 7 columns (the days) and 11 rows (the timeslots) and have subqueries for each timeslot, checking if there is a meeting booked for that timeslot/user.
option 2: php/mysql
have mysql just retrieve the meetings booked/user, and cross it with a php-generated calendar.
Is option 1 at all possible? If it is, is it resource-intensive?
Thank you,
Alexandre
UPDATE: QUERY SUGGESTIONS
Here is the "option 2" query i use to get the booked events (lessons in this case: the user is a teacher).
```
SELECT DISTINCT date, hour_from, hour_to, courses.description, courses.alias, teachers.name, locations.new_acronym
FROM timetables
INNER JOIN courses ON (courses.id=timetables.course_id)
INNER JOIN teachers ON (teachers.id=timetables.prof_id)
INNER JOIN locations ON (locations.id=timetables.location_id)
WHERE ((timetables.prof_id='$id')
AND (timetables.date >= '$starting_date')
AND (timetables.date < date_add('$starting_date', INTERVAL 7 day))) ;
```
I'm very interested for suggestions on a query that would make option 1 work ! | Trying to describe a calendar as a SQL table doesn't sound like a good match. It's certainly possible to perform a query that will generate a table with 7 columns and 11 rows, but then what would you do with that generated table? You'd still have to render it using PHP.
So start with the assumption that PHP is rendering a calendar, and do away with the extra work of making SQL generate one (and an extremely specific one!) beforehand. This way you can use a single SQL query to retrieve all the events that should be visible in one shot, and then place them on the calendar as you draw it. | I´m guessing but I think you could do option 1 if you create a table with the timeslots. This will simplify a lot the queries. And the PHP code to generate the Calendar page will much simplier: you´ll need just to iteract over the result set.
And, to get a good performance you should create apropriate index and key (i cant propose wihch ones beforehand).
EDIT TO ADD A SUGGESTION:
@pixeline: Since you didnt add the table layouts, this is a shoot in the dark, bu i think just changing the `INNER JOIN`s to `LEFT OUTER JOIN` you do it:
```
SELECT DISTINCT date, hour_from, hour_to, courses.description, courses.alias, teachers.name, locations.new_acronym
FROM timetables
LEFT OUTER JOIN courses ON (courses.id=timetables.course_id)
LEFT OUTER JOIN teachers ON (teachers.id=timetables.prof_id)
LEFT OUTER JOIN locations ON (locations.id=timetables.location_id)
WHERE ((timetables.prof_id='$id')
AND (timetables.date >= '$starting_date')
AND (timetables.date < date_add('$starting_date', INTERVAL 7 day))) ;
```
If `timetables` doesnt have all the hours for the day, you could create a table with them (say `timeslot`) and put it as the first table and put timetables as a `LEFT OUTER JOIN` or a `CROSS JOIN`. And the others as `LEFT OUTER JOIN` as above. | generate weekly calendar in mysql/php | [
"",
"php",
"mysql",
"calendar",
""
] |
I have a mirrored database and I need to make some changes to it. Mainly, adding a view and some stored procedures. Now I know that if you make schema changes you are supposed to remove mirroring and the mirror database, make your changes to the principal, then backup-restore the principal and restore mirroring. Is this the case for stored procedures and views as well? Can I just make my changes to the Principal, then Failover and make my changes to the mirror as well? What are the possible issues and ramifications from doing something like this? It just seems like a very tedious task to have to do every time we want to make a small change, mainly because the database is over 10 gigs so it takes a little while to back up and restore. | If you are mirroring, you should be able to apply those changes to the principal and they show up on the mirrored side. If you want there to be schema difference between the two, you can't use mirroring. Are you looking to apply schema changes on just the mirrored database or to both? If both then you don't have to do anything special. | > Now I know that if you make schema
> changes you are supposed to remove
> mirroring and the mirror database,
> make your changes to the principal,
> then backup-restore the principal and
> restore mirroring
This is actually wrong. The principal and mirror database are in fact a single database that is stored in two physical locations. *Any* and *every* change that occurs in the principal, occurs also in the mirror. They are literarly identical all the time.
So any schema changes, including tables, views, procedures, functions, schemas, database principals, assemblies and so on and so forth occur on both the principal and the mirror.
The only changes that require special attentions are changes that are *related* to the database but don't occur in the database: Agent jobs (they are in msdb), server principals (logins), replication settings (they are all over the place in database, msdb and distributor. | How do I make schema changes to a mirrored database? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-server-2008",
"mirroring",
""
] |
Suppose We have a, `IEnumerable Collection` with **20 000 Person** object items.
Then suppose we have created another Person object.
We want to list all Persons that ressemble this Person.
That means, for instance, if the Surname **affinity is more than 90 %** , add that Person to the list.
e.g. ("Andrew" vs "Andrw")
What is the most effective / quick way of doing this?
Iterating through the collection and comparing char by char with affinity determination? OR?
Any ideas?
Thank you! | You may be interested in:
[Levenshtein Distance Algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance)
[Peter Norvig - How to Write a Spelling Corrector](http://norvig.com/spell-correct.html)
(you'll be interested in the part where he compares a word against a collection of existing words) | Depending on how often you'll need to do this search, the brute force iterate and compare method might be fast enough. Twenty thousand records really isn't all that much and unless the number of requests is large your performance may be acceptable.
That said, you'll have to implement the comparison logic yourself and if you want a large degree of flexibility (or if you need find you have to work on performance) you might want to look at something like [Lucene.Net](http://incubator.apache.org/lucene.net/). Most of the text search engines I've seen and worked with have been more file-based, but I think you can index in-memory objects as well (however I'm not sure about that).
Good luck! | C# search with resemblance / affinity | [
"",
"c#",
"search",
"collections",
""
] |
I'm writing a small program to find duplicate files
I iterate through each file in a directory
then I load the file path and the md5hash of that file into a dictionary (file path being the key)
I next want to walk through each value in the dictionary to see if any values match then display the two+ keys in a display window
however I'm not sure how to not display duplicate findings
```
1a
2b
3a
4c
```
If I use a for each loop with the key value pair I would get entries for 1 matchs 3 and then that 3 match 1
If I had a search that I could read everything below the search string and not have to worry about that (plus I believe it would be more efficient)
Is there a name for this type of loop (please excuse my lack of formal knowledge)
OR would the best practice be to remove any dictionary entries as they are found? | Assuming that `dict` is a Dictionary that contains the filename as the key and the MD5 hash as the value, you could use the following code to display duplicate files :
```
var groupedByHash = from kvp in dict
group kvp by kvp.Value into grp
let count = grp.Count()
where count > 1
select grp;
foreach (IGrouping<string,KeyValuePair<string,string>> grp in groupedByHash)
{
Console.WriteLine("Hashcode : {0}", grp.Key);
foreach(KeyValuePair<string,string> kvp in grp)
{
Console.WriteLine("\tFilename = {0}", kvp.Key);
}
Console.WriteLine();
}
``` | If I understand you correctly, you are using the hash to decide if two files are identical, and you are using the hash as the dictionary key. You can't have duplicate keys in a dictionary, so you'd want to have a `Dictionary<Hash, IList<string>>` and add any files to the list for each hash value. | Find Duplicate Values in a dictionary | [
"",
"c#",
"dictionary",
"loops",
""
] |
I can't for the life of me understand why the following regex can't match 4 floats.
there is a couple of rules for the way theese floats can be written.
* the float ranges from 0 to 1
* you can skip the first digit if its 0
* there is an unlimited number of digits after the period.
Theese are valid floats
* 1
* 1.0
* 0.0
* .0
* 0.123
* .123
Now for the code I've tried amongst others
```
string input = " 0 0 0 .4";
string regex = @"[0-1]*(\.[0-9]*)*\s[0-1]*(\.[0-9]*)*\s[0-1]*(\.[0-9]*)*\s[0-1]*(\.[0-9]*)*";
Regex r = new Regex(regex, RegexOptions.Compiled);
Match m = r.Match(input);
```
m.Value Returns " 0 0 0" where i'd expect it to return "0 0 0 .4"
I've tried
```
[0-1]{0,1}(\.[0-9]*)*\s[0-1]{0,1}(\.[0-9]*)*\s[0-1]{0,1}(\.[0-9]*)*\s[0-1]{0,1}(\.[0-9]*)*
```
aswell but it looks like .net does not cope well with the {0,1} syntax (or I am just using it wrong)
I've tried looking at <http://www.regular-expressions.info/reference.html> and the {0,1} should be valid to my understanding atleast.
I managed to make a regex that matched the string in the little regex matcher tool I have at my disposal, but that regex did not work with the .net Regex class
**UPDATE**
I'm using the regex in conjunction with a Tokenizer parsing a larger document.
Combineing what Pavel Minaev and psasik wrote the following regex made an expected match
```
([0,1]|([0,1]?\.[0-9]+))\s([0,1]|([0,1]?\.[0-9]+))\s([0,1]|([0,1]?\.[0-9]+))\s([0,1]|([0,1]?\.[0-9]+))
```
The following matches the actual float
```
([0,1]|([0,1]?\.[0-9]+))
``` | For starters, your regex is wrong in general - because of overuse of `*`, it will happily match something like `10101.10101.10101`.
The reason for your peculiar match result is because your input string starts with a space `" "` character. Thus the match goes like this:
* first `[0-1]*` matches empty string at the beginning
* first `(\.[0-9]*)*` matches empty string "following" that empty string
* first `\s` matches the starting space character in the input
* second `[0-1]*` matches the *first* `0` in the input
...
* third `\s` matches the *third* space character in the input (the one preceding the third `0`)
No groups actually match anything (or rather they all match empty strings, because you use `*`). | ```
float [0-1]|([0-1]?\.[0-9]+)
ws [ \t]
{ws}*{float}{ws}+{float}{ws}+{float}{ws}+{float}{ws}*
``` | RegEx matching 4 floats | [
"",
"c#",
".net",
"regex",
""
] |
I've a project which ask me to do such a BIG search engine but which is all dynamic. I mean I can have about 0 to 9 main "group" which have inside something like an infinite possibility of "where" with "OR" or "AND". First thing we think was to use Dynamic Linq which provide a good alternative to build dynamic query. All this using EF with an homemade wrapper.
**Probleme** :
I'm not able to access to a "Collection". I mean, I can easly access to a referenced object (Like *Customer.State.StateName = "New-York" OR Custoemr.State.StateName = "Quebec"* ) but I can't find a way to acces to something like : *"Customer.Orders.OrderID = 2 OR Customer.Orders.OrderID = 3"*. I can easly figure out this its because its a collection, but how can I do this?
Please help me out!!
\*\* Sorry for my english !!
---
**Update**
I'm not clear enought I think, sorry its because im french...
My problem its because nothing is static. Its a candidat search engine for a recruting compagny that place candidats into an enterprise. In a page where manager can search candidat, he can "parse" by : Domain(s) (Jobs), City(ies) or many other that user have filled up when he register. All this in format (if it were in SQL) :
[...] WHERE (domaine.domainID = 3 OR domaine.domainID = 5 OR domaine.domainID = 23) AND (cities.cityID = 4, cities.city = 32) [...]
So i can't do this with a normal LINQ format like :
```
Candidat.Domaines.Where(domain => domain.DomainID == 3 || domain.DomainID == 5 || domain.DomainID == 23);
```
Even the operator in the paretheses are dynamic ("AND" or "OR")! That why we trying to use Dynamic Linq because its a lot more flexible.
Hope its more easy to understand my problem ...
---
**Update 2**
Here's my method
```
private string BuildDomainsWhereClause() {
StringBuilder theWhere = new StringBuilder();
if (this.Domaines.NumberOfIDs > 0) {
theWhere.Append("( ");
theWhere.Append(string.Format("Domaines.Where( "));
foreach (int i in this.Domaines.ListOfIDs) {
if (this.Domaines.ListOfIDs.IndexOf(i) > 0) {
theWhere.Append(string.Format(" {0} ", this.DispoJours.AndOr == AndOrEnum.And ? "&&" : "||"));
}
theWhere.Append(string.Format("DomaineId == {0}", i));
}
theWhere.Append(" ))");
}
return theWhere.ToString();
}
```
It works great instead that it "Not return a boolean". So how should I?
Error : "Expression of type 'Boolean' expected".
At the end, it returns something like : "( Domaines.Where( DomaineId == 2 && DomaineId == 3 && DomaineId == 4 && DomaineId == 5 ))." which is added to my LINQ Query :
```
var queryWithWhere = from c in m_context.Candidats.Where(WHERE)
select c;
```
Dont forget that there's like 7 or 8 more "possible" added things to search in ... Any ideas? | What you need to do here, is build a **LambdaExpression** (more specifically an `Expression<Func<T, bool>>`). You cannot use a string. You can build a simple expression like this:
```
ParameterExpression p = Expression.Parameter(typeof(Domaine), "domaine");
Expression<Func<Domaine, bool>> wherePredicate =
Expression.Lambda<Func<Domaine, bool>>(
Expression.Or(
Expression.Equal(
Expression.Property(p, "DomainID"),
Expression.Constant(10)),
Expression.Equal(
Expression.Property(p, "DomainID"),
Expression.Constant(11))
), p);
```
i.e.,
> domaine.DomainID = 10 || domaine.DomainID = 11
Not very readable if you need to do this by hand.
There's a sample of a fully operational expression parser that will actually do this for you based on a string in [*C# Samples for Visual Studio 2008*](http://code.msdn.microsoft.com/csharpsamples) at MSDN Code Gallery, under **DynamicQuery**. (The `LinqDataSource` control uses a slightly modified version of this sample internally.) | Finaly i've got it exactly the way I want.
```
private string BuildDomainsWhereClause() {
StringBuilder theWhere = new StringBuilder();
if (this.Domains.NumberOfIDs > 0) {
theWhere.Append("( ");
foreach (int i in this.Domains.ListOfIDs) {
if (this.Domains.ListOfIDs.IndexOf(i) > 0) {
theWhere.Append(string.Format(" {0} ", this.Domains.AndOr == AndOrEnum.And ? "&&" : "||"));
}
theWhere.Append(string.Format("Domains.Any(IdDomaine== {0})", i));
}
theWhere.Append(" )");
}
return theWhere.ToString();
}
```
Which produce something like : "( DispoJours.Any(IdDispo == 3) && DispoJours.Any(IdDispo == 5) )".
All my other "Where builder" will do the same things with a "&&" between which give the correct result.
And later :
```
var queryWithWhere = from c in m_context.Candidats.Where(WHERE)
select c;
```
WHOOOHOOO !! Thanks folks. Were very usefull! Love this website!
---
**Update**
Don't forget that i use Dynamic Linq on this query. It's not a normal LINQ query. | Dynamic LINQ on a collection? | [
"",
"c#",
"asp.net",
"entity-framework",
"dynamic-linq",
""
] |
I need to send a curl request with the user's ip address not the server one. I tried this with no luck:
```
curl_setopt( $ch, CURLOPT_INTERFACE, $ip );
```
Any ideas? | Ok, so there's no way to safely spoof the ip address of a curl request, but I found a non-safe way, it depends on the server script receiving the request, but it worked for me to trick the API I was making the request to:
```
curl_setopt( $ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
```
This won't always work, but in this case it worked for me.
Thanks everyone for the help! | It doesn't work with curl for me so i found a way around it, I just had to do this and as long as the IP is assigned to your server, then:
```
echo http_socket::download('http://something.com', '55.55.44.33');
final class http_socket
{
static public function download($url, $bind_ip = false)
{
$components = parse_url($url);
if(!isset($components['query'])) $components['query'] = false;
if(!$bind_ip)
{
$bind_ip = $_SERVER['SERVER_ADDR'];
}
$header = array();
$header[] = 'GET ' . $components['path'] . ($components['query'] ? '?' . $components['query'] : '');
$header[] = 'Host: ' . $components['host'];
$header[] = 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20100106 Ubuntu/9.10 (karmic) Firefox/3.5.7';
$header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$header[] = 'Accept-Language: en-us,en;q=0.5';
$header[] = 'Accept-Encoding: gzip,deflate';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Keep-Alive: 300';
$header[] = 'Connection: keep-alive';
$header = implode("\n", $header) . "\n\n";
$packet = $header;
//----------------------------------------------------------------------
// Connect to server
//----------------------------------------------------------------------
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, $bind_ip);
socket_connect($socket, $components['host'], 80);
//----------------------------------------------------------------------
// Send First Packet to Server
//----------------------------------------------------------------------
socket_write($socket, $packet);
//----------------------------------------------------------------------
// Receive First Packet to Server
//----------------------------------------------------------------------
$html = '';
while(1) {
socket_recv($socket, $packet, 4096, MSG_WAITALL);
if(empty($packet)) break;
$html .= $packet;
}
socket_close($socket);
return $html;
}
}
``` | cURL ip address | [
"",
"php",
"curl",
""
] |
What does it mean and how important to know about it for a C/C++ programmers?
Is it the same across the platforms, at least conceptually?
I understand it as a block of allocated memory used to store local variable by a function...
I want to know more | An activation record is another name for Stack Frame. It's the data structure that composes a call stack. It is generally composed of:
* Locals to the callee
* Return address to the caller
* Parameters of the callee
* The previous stack pointer (SP) value
The Call Stack is thus composed of any number of activation records that get added to the stack as new subroutines are added, and removed from the stack (usually) as they return.
The actual structure and order of elements is platform and even implementation defined.
For C/C++ programmers, **general knowledge** of this structure is useful to understand certain implementation features like Calling Conventions and even why do buffer overflows allow 3rd party malicious code to be ran.
A more **intimate knowledge** will further the concepts above and also allow a programmer to debug their application and read memory dumps even in the absence of a debugger or debugging symbols.
More generally though, a C/C++ programmer can go by a large portion of their hobbyist programming career without even giving the call stack a moments thought. | *activation record* isn't a concept that is used much in talking about C or C++ langauges themselves. The format of *activation records* is very much platform specific.
Conceptually, how parameters are passed, the lifetimes of local variables, where functions return to and how the call stack is unwound in response to an expection throw are all important parts of C++ and (with the exception of the latter C). The details of how these are implemented will affect what an *activation record* looks like for a particular platform but knowledge of this is not usually necessary for writing code in C++ or C. | What is activation record in the context of C and C++? | [
"",
"c++",
"c",
""
] |
How can I extract string ‘abc.com’ from a string <http://info@abc.com> using SQL server 2008? | A more generalized variation to KM's response...
```
declare @s varchar(100)
select @s = 'http://info@abc.com'
select right(@s, len(@s) - charindex('@', @s))
```
This will locate the '@' in the string and grab everything to the right. This is most likely MSSQL specific syntax. | in SQL Server, try (assumes no nulls and string is found):
```
declare @x varchar(100), @y varchar(100)
select @x='http://info@abc.com',@y='abc.com'
print SUBSTRING(@x,CHARINDEX(@y,@x),LEN(@y))
```
**EDIT**
based on Dave Carlile answer, these handles the case when @ is not present:
retunrs empty string when "@" is not present
```
declare @s varchar(100)
select @s = 'http://infoabc.com'
select right(@s, len(@s) - CASE WHEN charindex('@', @s)>0 then charindex('@', @s) ELSE len(@s) END)
```
returns null when "@" is not present
```
declare @s varchar(100)
select @s = 'http://infoabc.com'
select CASE WHEN charindex('@', @s)> 0 THEN right(@s, len(@s) - charindex('@', @s)) ELSE NULL END
``` | How can I extract string ‘abc.com’ from a string http://info@abc.com using SQL server 2008? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have 2 check boxes, I want to know how to manage these: if one is checked do that, if the other one is checked do that, if both are checked do both actions.
Also if none are checked and I click on the button to perform the action it should display "Please check one of the options or both."
Thank you for your time
-Summey | ```
if (!checkBox1.Checked && !checkBox2.Checked)
{
MessageBox.Show("Please select at least one!");
}
else if (checkBox1.Checked && !checkBox2.Checked)
{
MessageBox.Show("You selected the first one!");
}
else if (!checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("You selected the second one!");
}
else //Both are checked
{
MessageBox.Show("You selected both!");
}
``` | Also;
```
if(checkBox1.Checked || checkBox2.Checked)
{
if(checkBox1.Checked) doCheckBox1Stuff();
if(checkBox2.Checked) doCheckBox2Stuff();
}else {
MessageBox.Show("Please select at least one option.");
}
``` | Checkbox validation | [
"",
"c#",
"checkbox",
""
] |
The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).
I've thought about two unpythonic ways of doing it:
```
def pairs(lst):
n = len(lst)
for i in range(n):
yield lst[i],lst[(i+1)%n]
```
and:
```
def pairs(lst):
return zip(lst,lst[1:]+lst[:1])
```
expected output:
```
>>> for i in pairs(range(10)):
print i
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
(9, 0)
>>>
```
any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?
also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting. | ```
def pairs(lst):
i = iter(lst)
first = prev = item = i.next()
for item in i:
yield prev, item
prev = item
yield item, first
```
Works on any non-empty sequence, no indexing required. | I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?
```
def ntuples(lst, n):
return zip(*[lst[i:]+lst[:i] for i in range(n)])
```
The itertools version should be efficient enough even for large lists...
```
from itertools import *
def ntuples(lst, n):
return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)])
```
And a version for non-indexable sequences:
```
from itertools import *
def ntuples(seq, n):
iseq = iter(seq)
curr = head = tuple(islice(iseq, n))
for x in chain(iseq, head):
yield curr
curr = curr[1:] + (x,)
```
Anyway, thanks everybody for your suggestions! :-) | Iterate over pairs in a list (circular fashion) in Python | [
"",
"list",
"iteration",
"tuples",
"python",
""
] |
I am currently implementing a YUI datatable as a reusable viewer to show sales reports (and other such things) for internal use. The problem is, many of these reports are up to, and even more than 1000 rows long, and client-side performance becomes an issue on even newer, faster machines.
For a variety of reasons, server-side pagination is not an option for us (mostly because it would be problematic when it comes to exporting a report to a spreadsheet -- you do not want the same paginated results).
So my question is.. in what ways can I increase performance on a YUI's datatable without resorting to server-side pagination? | What you want is [client side pagination](http://developer.yahoo.com/yui/examples/datatable/dt_clientpagination.html). The largest impact DataTable has on the UI is in the render phase. Tables are very complicated for browsers to render even by themselves. Add all the dynamic functionality available in DT and you can see some real UI lag.
Send all your data to the client. With client side pagination, the UI is more responsive and user friendly.
If this is not an option, [configure renderLoopSize](http://developer.yahoo.com/yui/docs/YAHOO.widget.DataTable.html#config_renderLoopSize) to around 200 or 300. This will chunk the output of the rows to 200 or 300 at a time, limiting the number of reflows that your page will suffer. | Here is one hint:
[Faster YUI DataTable with 5 Lines of Code](http://www.zachleat.com/web/2007/12/27/faster-yui-datatable-with-5-lines-of-code/) | YUI Datatable & Large Data Sets w/o Pagination | [
"",
"javascript",
"performance",
"datatable",
"yui",
""
] |
I've been having trouble with comparison in my c++ program. This is the boiled down version.
```
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc>2){cout<<"3+Args"<<endl;}else//???
if(argc==2){
cout<<"2args"<<endl;
if(argv[1]=="/hide-icons"){}
if(argv[1]=="/show-icons"){}
if(argv[1]=="/reinstall"){setAsDefault();}
if(argv[1]=="/?"){showPossibleCommands();}
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
}else{showPossibleCommands();cout<<argv[0]<<endl;}
return 0;
}
```
When I run "programname.exe /1", my program writes "2args" but not "go". Am I missing something obvious? | `argv[1]` is a `char*`, so by testing with `==` you're checking if the pointer points to the same spot as the start of the various string constants you're using... which is not going to be the case. To compare *contents* instead, use [strcmp](http://en.cppreference.com/w/cpp/string/byte/strcmp). | The problem is, that your code compares the pointers to the strings, not the stings itself.
You have to replace the compares with calls to the string-compare function.
E.g.
```
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
```
becomes
```
if(strcmp(argv[1],"/1") == 0) {cout<<"go"<<endl;FirstRun();}
```
You may have to include string.h to get the strcmp prototype into your code. | C string comparison problem in c++ | [
"",
"c++",
"cstring",
""
] |
Of course, warning must be treated, but **why is VC++ [C4150](http://msdn.microsoft.com/en-us/library/ba5dy3f2.aspx)** (deletion of pointer to incomplete type) **only a warning?** | Because standard says it's legal, although dangerous: 5.3.5
> If the object being deleted has
> incomplete class type at the point of
> deletion and the complete class has a
> non-trivial destructor or a
> deallocation function, the behavior is
> undefined. | You get this warning as result of forward declaration. So compiler has recognized that it is structure/class, but not sure about invocation of destructor.
Sense of warning most possible is concerned with second pass of code analyze by msvc. When latter class is resolved compiler can make a decision if destructor exists. | Why is VC++ C4150 (deletion of pointer to incomplete type) only a warning? | [
"",
"c++",
"compiler-construction",
"visual-c++",
"compiler-warnings",
""
] |
I'm using PHP+curl to retrieve an XSL file, but first I want to do some minimum validation that the file is really a XSL file.
I make sure the file exists, has status code 200 OK, and that it has the correct file extension, but then I want to check the header for the Content-Type. I do this using `curl_getinfo()` function. All fine.
But XSL files always return "`application/xml`" or "`text/xml`" as the Content-Type, which is for XML files. I believe an XSL header should be "`application/xslt+xml`". So what's going on here and how can I make sure it's an XSL document? | You can check the XSLT namespace in the file.
If PHP version >= 5.1.2, use [`SimpleXMLElement::getNamespaces()`](https://www.php.net/manual/en/function.simplexml-element-getNamespaces.php) | Different approach, for PHP 5:
1. You could try to load the stylesheet in an [XSLTProcessor](http://fr.php.net/manual/en/xsltprocessor.importstylesheet.php). Maybe an exception is thrown if the stylesheet is incorrect
2. (Better IMHO) [Validate](http://fr.php.net/manual/en/domdocument.schemavalidate.php) the XSL stylesheet against its schema | received HTTP headers incorrect/unexpected for XSL file type | [
"",
"php",
"curl",
"http-headers",
""
] |
I have a disclosure form that requires a user to enter yes/no answers for a series of around 30 questions.
Is there a better way to create the table than having 30 columns that correspond the questions?
Below is my MS-SQL script, but the question relates more to structure than syntax.
```
CREATE TABLE Questionaire(
QuestionaireID int IDENTITY(1,1) NOT NULL,
UserID int NOT NULL,
Q1 bit NOT NULL,
Q2 bit NOT NULL,
Q3 bit NOT NULL,
... etc ...
... etc ...
Q30 bit NOT NULL
)
-- and to store the questions relating to Q1, Q2, etc...
CREATE TABLE Questions(
QuestionID int IDENTITY(1,1) NOT NULL,
Question varchar(30) NOT NULL
)
``` | well, there are 2 better ideas i can think of:
1. store a vector (i.e. a string/byte array variable containing all results), and handle everything related to the data in your program (this way you're more limited on SQL queries)
2. store the key/value pair, keyed by survey-id, e.g.
1134 age 68
1134 prefer chocolate
1134 width 6"
1135 age 31
1135 prefer vanilla
1135 width 3.2"
it depends on what you want to do with the results.
but this is more "correct" than what you've suggested, since with my last option you're less likely to run into trouble | To fully normalize, you might want to consider a structure like this:
```
Table Questionaire(
QuestionaireID...
QuestionaireName...
Table Questions(
QuestionaireID...
QuestionID...
QuestionName...
Table Response(
QuestionaireID...
ResponseID...
UserID...
Table Answers(
AnswerID...
ResponseID...
QuestionID...
Answer...
```
This provides higher information fidelity, as you can capture data in more dimensions - at the response level, the individual answer level, as well as future-proofing yourself for changes to the system. | Is there a better way to structure a SQL table handling User Questionnaires? | [
"",
"sql",
""
] |
I am storing first name and last name with up to 30 characters each. Which is better `varchar` or `nvarchar`.
I have read that `nvarchar` takes up twice as much space compared to `varchar` and that `nvarchar` is used for internationalization.
So what do you suggest should I use: `nvarchar` or `varchar` ?
Also please let me know about the performance of both. Is performance for both is same or they differ in performance. Because space is not too big issue. Issue is the performance. | Basically, nvarchar means you can handle lots of alphabets, not just regular English. Technically, it means unicode support, not just ANSI. This means double-width characters or approximately twice the space. These days disk space is so cheap you might as well use nvarchar from the beginning rather than go through the pain of having to change during the life of a product.
If you're certain you'll only ever need to support one language you could stick with varchar, otherwise I'd go with nvarchar.
This has been discussed on SO before [here](https://stackoverflow.com/questions/35366/varchar-vs-nvarchar-performance).
EDITED: changed ascii to ANSI as noted in comment. | First of all, to clarify, `nvarchar` stores unicode data while `varchar` stores ANSI (8-bit) data. They function identically but nvarchar takes up twice as much space.
Generally, I prefer storing user names using `varchar` datatypes unless those names have characters which fall out of the boundary of characters which `varchar` can store.
It also depends on database collation also. For e.g. you'll not be able to store Russian characters in a `varchar` field, if your database collation is `LATIN_CS_AS`. But, if you are working on a local application, which will be used only in Russia, you'd set the database collation to Russian. What this will do is that it will allow you to enter Russian characters in a `varchar` field, saving some space.
But, now-a-days, most of the applications being developed are international, so you'd yourself have to decide which all users will be signing up, and based on that decide the datatype. | varchar or nvarchar | [
"",
"sql",
"sql-server",
"sql-server-2005",
"variables",
""
] |
What do single and double leading underscores before an object's name represent in Python? | ## Single Underscore
In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not *enforced* in any way.
Using leading underscores for functions in a module indicates it should not be imported from somewhere else.
From the [PEP-8](http://www.python.org/dev/peps/pep-0008/) style guide:
> `_single_leading_underscore`: weak "internal use" indicator. E.g. `from M import *` does not import objects whose name starts with an underscore.
## Double Underscore (Name Mangling)
From [the Python docs](https://docs.python.org/3/tutorial/classes.html#private-variables):
> Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where `classname` is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
And a warning from the same page:
> Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; *it still is possible for a determined soul to access or modify a variable that is considered private.*
## Example
```
>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
``` | * `_foo`: Only a convention. A way for the programmer to indicate that the variable is private (whatever that means in Python).
* `__foo`: This has real meaning. The interpreter replaces this name with `_classname__foo` as a way to ensure that the name will not overlap with a similar name in another class.
* `__foo__`: Only a convention. A way for the Python system to use names that won't conflict with user names.
No other form of underscores have meaning in the Python world. Also, there's no difference between class, variable, global, etc in these conventions. | What is the meaning of single and double underscore before an object name? | [
"",
"python",
"oop",
"naming-conventions",
"identifier",
""
] |
This may sound strange, but I need a better way to build python scripts than opening a file with nano/vi, change something, quit the editor, and type in `python script.py`, over and over again.
I need to build the script on a webserver without any gui. Any ideas how can I improve my workflow? | put this line in your .vimrc file:
```
:map <F2> :w\|!python %<CR>
```
now hitting `<F2>` will save and run your python script | You should give the [screen](http://www.gnu.org/software/screen/screen.html) utility a look. While it's not an IDE it is some kind of window manager on the terminal -- i.e. you can have multiple windows and switch between them, which makes especially tasks like this much easier. | Python IDE on Linux Console | [
"",
"python",
"shell",
"vi",
""
] |
Could you please explain what `$arg` means in this piece of code? (it's from a Drupal module)
```
function node_add_review_load($arg) {
global $user;
$add_review = FALSE;
$current_node = node_load($arg);
$type =$current_node->type;
$axes_count = db_result(db_query("SELECT COUNT(*) FROM {nodereview_axes} WHERE node_type='%s'", $type));
if (variable_get('nodereview_use_' . $type, 0) && $axes_count) {
$add_review = db_result(db_query("SELECT n.nid FROM {node} n INNER JOIN {nodereview} nr ON n.nid=nr.nid WHERE uid=%d AND reviewed_nid=%d", $user->uid, $arg));
}
return $add_review ? FALSE : $arg;
}
``` | In general, `arg` is short for "argument," as in "an argument to a function." It's a generic, and thus unhelpful, name. If you'd just given the method signature (`function node_add_review_load($arg)`) we'd have no idea.
Fortunately, with the complete function body, we can deduce its purpose: it is the node\_id. This function loads the node identified by `$arg` and then tries to find a corresponding row that's loaded, and that the code then tries to find a corresponding review for the current user. If successful, the function will return that same `node_id` (i.e., `$arg`); otherwise it will return FALSE. | <http://nl.php.net/manual/en/functions.arguments.php>
When a programmer uses node\_add\_review\_load() he can pass the argument which can be used in the function.
The function returns another value if the argument $arg is different.
So the programmer can do this:
```
node_add_review_load("my argument");
//and the php automatically does:
$arg = "my argument";
//before executing the rest of the function.
``` | What does it mean to have a variable between parentheses after a function declaration? | [
"",
"php",
"function",
"parameters",
"arguments",
"function-signature",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.