Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
Given the email address: "Jim" <jim@example.com>
If I try to pass this to MailAddress I get the exception:
> The specified string is not in the form required for an e-mail address.
How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?
EDIT: I'm looking for C# code to parse it.
EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.
|
If you are looking to parse the email address manually, you want to read RFC2822 (<https://www.rfc-editor.org/rfc/rfc822.html#section-3.4>). Section 3.4 talks about the address format.
But parsing email addresses correctly is not easy and `MailAddress` should be able to handle most scenarios.
According to the MSDN documentation for `MailAddress`:
<http://msdn.microsoft.com/en-us/library/591bk9e8.aspx>
It should be able to parse an address with a display name. They give `"Tom Smith <tsmith@contoso.com>"` as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest.
```
string emailAddress = "\"Jim\" <jim@example.com>";
MailAddress address = new MailAddress(emailAddress.Replace("\"", ""));
```
Manually parsing RFC2822 isn't worth the trouble if you can avoid it.
|
Works for me:
```
string s = "\"Jim\" <jim@example.com>";
System.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);
Debug.WriteLine("DisplayName: " + a.DisplayName);
Debug.WriteLine("Address: " + a.Address);
```
The MailAddress class has a private method that parses an email address. Don't know how good it is, but I'd tend to use it rather than writing my own.
|
How to parse formatted email address into display name and email address?
|
[
"",
"c#",
"parsing",
"mailaddress",
""
] |
A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor.
```
class foo {
public event EventHandler myEvent;
...
}
...
myFoo.myEvent += myBar1.EventHandler;
myFoo.myEvent += myBar2.EventHandler;
```
Whenever the event fires, both myBar1 and myBar2 handlers will be called.
As I recall, the default implementation of this loop uses a linked list and simply iterates over the list and calls the EventHandler delegates in order.
My question is two fold:
1. Does someone know which book I was reading?
2. Why would you want to override the default implementation (which might be answered in the book)?
Edit: The book I was referring to was indeed Jeffrey Richter's CLR via C#
|
It could have been one of many books or web articles.
There are various reasons why you might want to change how events are subscribed/unsubscribed:
* If you have many events, many of which may well not be subscribed to, you may want to use [EventHandlerList](http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx) to lower your memory usage
* You may wish to log subscription/unsubscription
* You may wish to use a weak reference to avoid the subscriber's lifetime from being tied to yours
* You may wish to change the locking associated with subscription/unsubscription
I'm sure there are more - those are off the top of my head :)
EDIT: Also note that there's a difference between having a custom way of handling subscription/unsubscription and having a custom way of raising the event (which may call GetInvocationList and guarantee that all handlers are called, regardless of exceptions, for example).
|
I seem to remember something similar in Jeffrey Richter's CLR via C#. **Edit:** I definitely do remember that he goes into detail about it.
There are a few different reasons for taking control of event registration. One of them is to reduce code bloat when you've got TONS of events. I think Jeffrey went into this in detail within the book...
|
Doing your own custom .NET event processing loop
|
[
"",
"c#",
".net",
"dispatchertimer",
""
] |
I have a ASP.NET application running on a remote web server and I just started getting this error:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:
```
Set<int> set = new Set<int>();
```
Is compiled into this line:
```
Set<int> set = (Set<int>) new ICollection<CalendarModule>();
```
The CalendarModule class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?
**Update #1:** This problem seems to be introduced by Microsoft's [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) tool. We are currently investigating how to overcome it.
**Update #2:** We found two ways to solve this problem so far. We don't quite understand what the underlying problem is, but both of these fix it:
1. Turn off optimization.
2. Merge the assemblie with ILMerge on a different machine.
So we are left wondering if the build machine is misconfigured somehow (which is strange considering that we have been using the machine to build releases for over a year now) or if it is some other problem.
|
Ahh, ILMerge - that extra info in your question really helps with your problem. While I wouldn't ever expect the .net compiler to fail in this way I would expect to occasionally see this sort of thing with ILMerge (given what it's doing).
My guess is that two of your assemblies are using the same optimisation 'trick', and once merged you get the conflict.
Have you raised the bug with Microsoft?
A workaround in the meantime is to recompile the assemblies from source as a single assembly, saving the need for ILMerge. As the csproj files are just XML lists they're basically easy to merge, and you could automate that as an extra MSBuild step.
|
Are you sure that the assembly you're looking at was actually generated from the source code in question? Are you able to reproduce this problem with a small test case?
**Edit:** if you're using Reflector, it's possible that the MSIL to C# conversion isn't correct -- Reflector isn't always 100% accurate at decompiling. What does the MSIL look like?
**Edit 2:** Hmm... I just realized that it can't be Reflector at fault or you wouldn't have gotten that error message at runtime.
|
C# Compiler Incorrectly Optimizes Code
|
[
"",
"c#",
"asp.net",
"optimization",
"compiler-construction",
"ilmerge",
""
] |
Boost is a very large library with many inter-dependencies -- which also takes a long time to compile (which for me slows down our [**CruiseControl**](http://cruisecontrol.sourceforge.net/) response time).
The only parts of boost I use are boost::regex and boost::format.
Is there an easy way to extract only the parts of boost necessary for a particular boost sub-library to make compilations faster?
EDIT: To answer the question about why we're re-building boost...
1. Parsing the boost header files still takes a long time. I suspect if we could extract only what we need, parsing would happen faster too.
2. Our CruiseControl setup builds everything from scratch. This also makes it easier if we update the version of boost we're using. But I will investigate to see if we can change our build process to see if our build machine can build boost when changes occur and commit those changes to SVN. (My company has a policy that everything that goes out the door must be built on the "build machine".)
|
First, you can use the bcp tool (can be found in the tools subfolder) to extract the headers and files you are using. This won't help with compile times, though. Second, you don't have to rebuild Boost every time. Just pre-build the lib files once and at every version change, and copy the "stage" folder at build time.
|
Unless you are patching the boost libraries themselves, there is no reason to recompile it every time you do a build.
|
How do you deal with large dependencies in Boost?
|
[
"",
"c++",
"boost",
"dependencies",
""
] |
What is the best way to parse a float in CSharp?
I know about TryParse, but what I'm particularly wondering about is dots, commas etc.
I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round.
How can I best capture this?
|
Depends where the input is coming from.
If your input comes from the user, you should use the CultureInfo the user/page is using ([Thread.CurrentThread.CurrentUICulture](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx)).
You can get and indication of the culture of the user, by looking at the [HttpRequest.UserLanguages](http://msdn.microsoft.com/en-us/library/system.web.httprequest.userlanguages.aspx) property. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the [Thread.CurrentThread.CurrentUICulture](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx) at the start of the page.
If your input comes from an internal source, you can use the [InvariantCulture](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx) to parse the string.
The Parse method is somewhat easier to use, if your input is from a controlled source. That is, you have already validated the string. Parse throws a (slow) exception if its fails.
If the input is uncontrolled, (from the user, or other Internet source) the [TryParse](http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx) looks better to me.
|
I agree with leppie's reply; to put that in terms of code:
```
string s = "123,456.789";
float f = float.Parse(s, CultureInfo.InvariantCulture);
```
|
Best way to parse float?
|
[
"",
"c#",
"parsing",
"floating-point",
"currentculture",
""
] |
I made a Java Applet with some Standard GUI Components on it. I used the [MigLayout](http://www.miglayout.com/) Manager.
If I move the mouse slowly over the various GUI Components everything appears to be fine, but if I move the mouse fast, it flickers.
What could make that nasty ugly redraw?
(Core 2 Duo 6300, 2GB Ram, Windows XP)
|
One thought would be to check your code (and/or the MigLayout code) for unnecessary `repaint()` operations.
Custom UIs and layouts can cause weird problems sometimes...
|
you could use double buffering in java applet to improve screen refreshing speed. ask more if details needed..
|
Why does Swing in my Java Applet flicker on fast mouse over?
|
[
"",
"java",
"swing",
"applet",
""
] |
I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).
The first one registers ok, then multiple ones fail, saying class already registered - as expected.
My question is - is this bad? I was thinking of using a hash table to store the ATOM results in, to look up before calling RegisterWindow, but it seems Windows does this already?
|
You can test if the window class was previously registered calling **GetClassInfoEx**.
> If the function finds a matching class
> and successfully copies the data, the
> return value is nonzero.
<http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx>
This way you can conditionally register the window class based on the return of **GetClassInfoEx**.
|
## If your window class is defined in a DLL
Perhaps you should call your `RegisterClass()` in the PROCESS\_ATTACH part of the DllMain, and call your `UnregisterClass()` in the PROCESS\_DETACH part of the DllMain
## If your window class is defined in the executable
Perhaps you should call your `RegisterClass()` in the main, before the message loop, and call your `UnregisterClass()` in the main, after the message loop.
## Registering in an object constructor would be a mistake
Because you would, by reflex, clean it in the destructor. Should one of your window be destroyed, the destructor will be called and... If you have other windows floating around...
And using global data to count the number of active registration will need proper synchronisation to be sure your code is thread-friendly, if not thread-safe.
## Why in the main/DllMain?
Because you're registering some kind of global object (at least, for your process). So it makes sense to have it initialized in a "global way", that is either in the main or in the DllMain.
## Why it is not so evil?
Because Windows will not fail just because you did register it more than once.
A clean code would have used `GetClassInfo()` to ask if the class was already registered.
But again, Windows won't crash (for this reason, at least).
You can even avoid unregistering the window class, as Windows will clean them away when the process will end. I saw conflicting info on MSDN blogs on the subject (two years ago... don't ask me to find the info again).
## Why it is evil anyway?
My personal viewpoint is that you should cleanly handle your resources, that is allocate them once, and deallocate them once. Just because Win32 will clean leaking memory should not stop you from freeing your dynamically allocated memory. The same goes for window classes.
|
Side effects of calling RegisterWindow multiple times with same window class?
|
[
"",
"c++",
"windows",
"winapi",
""
] |
What is the best way to track down a memory leak that is only found on one customer's test/release box, and no where else?
|
[dotTrace3.1](http://www.jetbrains.com/profiler/index.html)
(This question is kinda funny, cause I am tracking a mem leak that isn't present on my machine ...)
|
Try a memory profiler like [ANTS Profiler](http://www.red-gate.com/products/ants_memory_profiler/index.htm).
|
Best way to track down a memory leak (C#) only visible on one customer's box
|
[
"",
"c#",
".net",
"memory",
"memory-leaks",
"garbage-collection",
""
] |
Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
```
Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:
```
>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
```
Fortunately, there is a workaround:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
```
This time, the function name and documentation are correct:
```
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
```
But there is still a problem: the function signature is wrong. The information "\*args, \*\*kwargs" is next to useless.
What to do? I can think of two simple but flawed workarounds:
1 -- Include the correct signature in the docstring:
```
def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
```
This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [*And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny\_function is just a random example.*]
2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:
```
def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
```
This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.
I'm looking for a solution that is fully general, and automatic.
So the question is: is there a way to edit the decorated function signature after it has been created?
Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "\*kwargs, \*\*kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?
Any other approaches?
|
1. Install [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution) module:
```
$ pip install decorator
```
2. Adapt definition of `args_as_ints()`:
```
import decorator
@decorator.decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print funny_function("3", 4.0, z="5")
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
```
---
### Python 3.4+
[`functools.wraps()` from stdlib](https://docs.python.org/3/library/functools.html#functools.wraps) preserves signatures since Python 3.4:
```
import functools
def args_as_ints(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return func(*args, **kwargs)
return wrapper
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print(funny_function("3", 4.0, z="5"))
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
```
`functools.wraps()` is available [at least since Python 2.5](https://docs.python.org/2.5/lib/module-functools.html) but it does not preserve the signature there:
```
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(*args, **kwargs)
# Computes x*y + 2*z
```
Notice: `*args, **kwargs` instead of `x, y, z=3`.
|
This is solved with Python's standard library `functools` and specifically [`functools.wraps`](https://docs.python.org/3.5/library/functools.html#functools.wraps) function, which is designed to "*update a wrapper function to look like the wrapped function*". It's behaviour depends on Python version, however, as shown below. Applied to the example from the question, the code would look like:
```
from functools import wraps
def args_as_ints(f):
@wraps(f)
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
```
When executed in Python 3, this would produce the following:
```
>>> funny_function("3", 4.0, z="5")
22
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
```
Its only drawback is that in Python 2 however, it doesn't update function's argument list. When executed in Python 2, it will produce:
```
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
```
|
Preserving signatures of decorated functions
|
[
"",
"python",
"decorator",
""
] |
This is somewhat of a follow-up to an answer [here](https://stackoverflow.com/questions/26536/active-x-control-javascript).
I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use the following IE-only syntax to accomplish this on different projects:
```
function MyControl::ReceiveMessage(msg)
{
alert(msg);
}
```
However, when inside a layout in which the control is buried, the Javascript cannot find the control. Specifically, if we put this into a plain HTML page it works fine, but if we put it into an ASPX page wrapped by the `<Form>` tag, we get a "MyControl is undefined" error. We've tried variations on the following:
```
var GetControl = document.getElementById("MyControl");
function GetControl::ReceiveMessage(msg)
{
alert(msg);
}
```
... but it results in the Javascript error "GetControl is undefined."
What is the proper way to handle an event being sent from an ActiveX control? Right now we're only interested in getting this working in IE. This has to be a custom ActiveX control for what we're doing.
Thanks.
|
I was able to get this working using the following script block format, but I'm still curious if this is the best way:
```
<script for="MyControl" event="ReceiveMessage(msg)">
alert(msg);
</script>
```
|
I have used activex in my applications before. i place the object tags in the ASP.NET form and the following JavaScript works for me.
```
function onEventHandler(arg1, arg2){
// do something
}
window.onload = function(){
var yourActiveXObject = document.getElementById('YourObjectTagID');
if(typeof(yourActiveXObject) === 'undefined' || yourActiveXObject === null){
alert('Unable to load ActiveX');
return;
}
// attach events
var status = yourActiveXObject.attachEvent('EventName', onEventHandler);
}
```
|
How to handle an ActiveX event in Javascript
|
[
"",
"javascript",
"events",
"activex",
""
] |
I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?
|
Oh ye of little faith:
```
SELECT *, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
```
<http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx>
|
You commented: not working if oldtable has an identity column.
I think that's your answer. The #newtable gets an identity column from the oldtable automatically. Run the next statements:
```
create table oldtable (id int not null identity(1,1), v varchar(10) )
select * into #newtable from oldtable
use tempdb
GO
sp_help #newtable
```
It shows you that #newtable does have the identity column.
If you don't want the identity column, try this at creation of #newtable:
```
select id + 1 - 1 as nid, v, IDENTITY( int ) as id into #newtable
from oldtable
```
|
INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?
|
[
"",
"sql",
"sql-server",
""
] |
I have a scenario. (Windows Forms, C#, .NET)
1. There is a main form which hosts some user control.
2. The user control does some heavy data operation, such that if I directly call the `UserControl_Load` method the UI become nonresponsive for the duration for load method execution.
3. To overcome this I load data on different thread (trying to change existing code as little as I can)
4. I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.
5. Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.
The pseudocode would look like this:
**CODE 1**
```
UserContrl1_LoadDataMethod()
{
if (textbox1.text == "MyName") // This gives exception
{
//Load data corresponding to "MyName".
//Populate a globale variable List<string> which will be binded to grid at some later stage.
}
}
```
The Exception it gave was
> Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
To know more about this I did some googling and a suggestion came up like using the following code
**CODE 2**
```
UserContrl1_LoadDataMethod()
{
if (InvokeRequired) // Line #1
{
this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
return;
}
if (textbox1.text == "MyName") // Now it won't give an exception
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be binded to grid at some later stage
}
}
```
But it still seems that I've come back to square one. The Application again
becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.
I don't know whether I perceived this right or wrong.
How do I resolve this and also what is the effect of execution of Line#1 if block?
**The situation is this**: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
So only accessing the value so that the corresponding data can be fetched from the database.
|
As per [Prerak K's update comment](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108) (since deleted):
> I guess I have not presented the question properly.
>
> Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
>
> So only accessing the value so that corresponding data can be fetched from the database.
The solution you want then should look like:
```
UserContrl1_LOadDataMethod()
{
string name = "";
if(textbox1.InvokeRequired)
{
textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
}
if(name == "MyName")
{
// do whatever
}
}
```
Do your serious processing in the separate thread *before* you attempt to switch back to the control's thread. For example:
```
UserContrl1_LOadDataMethod()
{
if(textbox1.text=="MyName") //<<======Now it wont give exception**
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be
//bound to grid at some later stage
if(InvokeRequired)
{
// after we've done all the processing,
this.Invoke(new MethodInvoker(delegate {
// load the control with the appropriate data
}));
return;
}
}
}
```
|
# Threading Model in UI
Please read the *[Threading Model](https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/threading-model)* in UI applications ([old VB link is here](https://msdn.microsoft.com/library/ms741870(v=vs.100).aspx)) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.
## The UI Thread
* There is only one thread (UI thread), that is allowed to access [System.Windows.Forms.Control](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.aspx) and its subclasses members.
* Attempt to access member of [System.Windows.Forms.Control](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.aspx) from different thread than UI thread will cause cross-thread exception.
* Since there is only one thread, all UI operations are queued as work items into that thread:

* If there is no work for UI thread, then there are idle gaps that can be used by a not-UI related computing.
* In order to use mentioned gaps use [System.Windows.Forms.Control.Invoke](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx) or [System.Windows.Forms.Control.BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) methods:

## BeginInvoke and Invoke methods
* The computing overhead of method being invoked should be small as well as computing overhead of event handler methods because the UI thread is used there - the same that is responsible for handling user input. Regardless if this is [System.Windows.Forms.Control.Invoke](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx) or [System.Windows.Forms.Control.BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx).
* To perform computing expensive operation always use separate thread. Since .NET 2.0 [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) is dedicated to performing computing expensive operations in Windows Forms. However in new solutions you should use the async-await pattern as described [here](https://stackoverflow.com/a/18033198/2042090).
* Use [System.Windows.Forms.Control.Invoke](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx) or [System.Windows.Forms.Control.BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) methods only to update a user interface. If you use them for heavy computations, your application will block:

### Invoke
* [System.Windows.Forms.Control.Invoke](http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx) causes separate thread to wait till invoked method is completed:

### BeginInvoke
* [System.Windows.Forms.Control.BeginInvoke](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx) doesn't cause the separate thread to wait till invoked method is completed:

## Code solution
Read answers on question [How to update the GUI from another thread in C#?](https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c).
For C# 5.0 and .NET 4.5 the recommended solution is [here](https://stackoverflow.com/a/18033198/2042090).
|
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
|
[
"",
"c#",
"multithreading",
"winforms",
"invoke",
""
] |
does any one know how to get the current motherboard, processor or HD temperature statistics?
In GNU/Linux, I know I could use something like hddtemp or sensord to get the info, and then parse it... but in Windows: How can I do this? And, Can it be done with with C# or Java or any other hight level programming language?
Thanks!
|
The problem with temperature and other monitoring sensors is that there is no common protocol on the hardware level, nor drivers allowing to retrieve that information with common API.
Software like already mentioned SpeedFan and [HWMonitor](http://www.cpuid.com/hwmonitor.php) (from the makers of CPU-Z utility) work by painstakingly cataloging the various sensors and bus controllers, and implementing corresponding protocols, usually using kernel-mode driver to access SMBus devices.
To embed this functionality in you own software, you can either develop this functionality yourself (possibly reducing the amount of work by tailoring it to your specific hardware, and using linux code from www.lm-sensors.org as reference) or purchasing commercial library that implements it. One, used by HWMonitor, is available [here](http://www.cpuid-pro.com/products-system-monitoring-kit.php).
good luck
|
I would argue that when the right configurations are in place, it can be superior to windows's one.
<http://www.lm-sensors.org/> is what does all the work. I had that plugged into RRDgraph & Munin and I was monitoring the temperature of my room over a period of almost a year and had nice pretty graphs. Also showed me my CPU fan was slowly wearing down, and I could see the line sloping down over a long period and know it was on the way out.
<http://www.lm-sensors.org/browser/lm-sensors/trunk/doc/developers/applications> is what you want.
(Oh wait, I fail. You're on \*nix wanting to do it on Windows, my bad :( ..um.. well. Good luck. Maybe I'll leave this here in case somebody finds your post while searching for the contrary)
Back when I did use windows, all I recall is Ye' Old [Motherboard Monitor ( Discontinued )](http://en.wikipedia.org/wiki/Motherboard_Monitor).
Wiki article says there is [speedfan](http://en.wikipedia.org/wiki/SpeedFan) and that looks like your best option. Programmatically, I guess you'll have to find the hardware specs and dig through Windows API and stackloads of arbitrary bus address offsets.
|
How to get the temperature of motherboard of a PC (and other hardware statistics)?
|
[
"",
"java",
"statistics",
"hardware",
"temperature",
""
] |
I have an Enum called Status defined as such:
```
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
```
I would like to access the value of `VALID` from a JSTL tag. Specifically the `test` attribute of the `<c:when>` tag. E.g.
```
<c:when test="${dp.status eq Status.VALID">
```
I'm not sure if this is possible.
|
A simple comparison against string works:
```
<c:when test="${someModel.status == 'OLD'}">
```
|
If using Spring MVC, the Spring Expression Language (SpEL) can be helpful:
```
<spring:eval expression="dp.status == T(com.example.Status).VALID" var="isValid" />
<c:if test="${isValid}">
isValid
</c:if>
```
|
Access Enum value using EL with JSTL
|
[
"",
"java",
"jsp",
"jakarta-ee",
"jstl",
""
] |
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.
Anyone has a clue?
|
JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode.
But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position:
```
function isDoubleByte(str) {
for (var i = 0, n = str.length; i < n; i++) {
if (str.charCodeAt( i ) > 255) { return true; }
}
return false;
}
```
This might not be as fast as you would like.
|
I used mikesamuel answer on this one. However I noticed perhaps because of this form that there should only be one escape slash before the `u`, e.g. `\u` and not `\\u` to make this work correctly.
```
function containsNonLatinCodepoints(s) {
return /[^\u0000-\u00ff]/.test(s);
}
```
Works for me :)
|
How to find whether a particular string has unicode characters (esp. Double Byte characters)
|
[
"",
"javascript",
"unicode",
"double-byte",
""
] |
I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 ([adLDAP](http://adldap.sourceforge.net/) does it on Apache). Anyone had done anything similar, with success?
* Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.
|
Importing a whole library seems inefficient when all you need is essentially two lines of code...
```
$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
// log them in!
} else {
// error message
}
```
|
You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
* You must validate input. An empty username/password would pass otherwise.
* You should ensure the username/password is properly encoded when binding.
* You should be encrypting the connection using TLS.
* Using separate LDAP servers for redundancy in case one is down.
* Getting an informative error message if authentication fails.
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: [LdapTools](https://github.com/ldaptools/ldaptools) (Well, not just for authentication, it can do much more). It can be used like the following:
```
use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;
$domain = (new DomainConfiguration('example.com'))
->setUsername('username') # A separate AD service account used by your app
->setPassword('password')
->setServers(['dc1', 'dc2', 'dc3'])
->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);
if (!$ldap->authenticate($username, $password, $message)) {
echo "Error: $message";
} else {
// Do something...
}
```
The authenticate call above will:
* Validate that neither the username or password is empty.
* Ensure the username/password is properly encoded (UTF-8 by default)
* Try an alternate LDAP server in case one is down.
* Encrypt the authentication request using TLS.
* Provide additional information if it failed (ie. locked/disabled account, etc)
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
|
Authenticating in PHP using LDAP through Active Directory
|
[
"",
"php",
"authentication",
"active-directory",
"ldap",
""
] |
I want my Python script to copy files on Vista. When I run it from a normal `cmd.exe` window, no errors are generated, yet the files are NOT copied. If I run `cmd.exe` "as administator" and then run my script, it works fine.
This makes sense since User Account Control (UAC) normally prevents many file system actions.
Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")
If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?
|
As of 2017, an easy method to achieve this is the following:
```
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
```
If you are using Python 2.x, then you should replace the last line for:
```
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
```
Also note that if you converted you python script into an executable file (using tools like `py2exe`, `cx_freeze`, `pyinstaller`) then you should use `sys.argv[1:]` instead of `sys.argv` in the fourth parameter.
Some of the advantages here are:
* No external libraries required. It only uses `ctypes` and `sys` from standard library.
* Works on both Python 2 and Python 3.
* There is no need to modify the file resources nor creating a manifest file.
* If you don't add code below if/else statement, the code won't ever be executed twice.
* You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values [here](https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea?redirectedfrom=MSDN#return-value).
* You can change the display method of the spawned process modifying the sixth parameter.
Documentation for the underlying ShellExecute call is [here](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396).
|
It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:
```
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
```
|
Request UAC elevation from within a Python script?
|
[
"",
"python",
"windows",
"windows-vista",
"uac",
""
] |
Depends on your experience could you recommend something?
I've use [izpack](http://izpack.org/), and it's very nice tool, is there any other, better tool?
|
In MS Windows [NSIS](http://nsis.sourceforge.net/Main_Page) is great and it's free & OSS
Ref: [Java Launcher with automatic JRE installation](http://nsis.sourceforge.net/Java_Launcher_with_automatic_JRE_installation)
|
for Windows there's [AdvancedInstaller](http://www.advancedinstaller.com/java.html), it was very easy to use and created standard .msi files. It has some extra features for Java installs.
|
What is the best installation tool for java?
|
[
"",
"java",
"installation",
""
] |
PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array *"is a list"* (contains only numeric keys starting from 0)?
Basically, I want to be able to differentiate between this:
```
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
```
and this:
```
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
```
|
Since 8.1 PHP has a simple answer, [array\_is\_list()](https://www.php.net/manual/en/function.array-is-list.php).
For the legacy code you can use the following function (wrapping it in `function_exists()` to make it portable):
```
if (!function_exists('array_is_list')) {
function array_is_list(array $arr)
{
if ($arr === []) {
return true;
}
return array_keys($arr) === range(0, count($arr) - 1);
}
}
```
And then you can use the this function with any PHP version.
```
var_dump(array_is_list([])); // true
var_dump(array_is_list(['a', 'b', 'c'])); // true
var_dump(array_is_list(["0" => 'a', "1" => 'b', "2" => 'c'])); // true
var_dump(array_is_list(["1" => 'a', "0" => 'b', "2" => 'c'])); // false
var_dump(array_is_list(["a" => 'a', "b" => 'b', "c" => 'c'])); // false
```
|
To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):
```
function has_string_keys(array $array) {
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
```
If there is at least one string key, `$array` will be regarded as an associative array.
|
How to check if PHP array is associative or sequential?
|
[
"",
"php",
"arrays",
""
] |
For example, if I have an echo statement, there's no guarantee that the browser might display it right away, might display a few dozen echo statements at once, and might wait until the entire page is done before displaying anything.
Is there a way to have each echo appear in a browser as it is executed?
|
You can use [`flush()`](http://php.net/flush) to force sending the buffer contents to the browser.
You can enable implicit flushing with "[`ob_implicit_flush(true)`](http://php.net/ob_implicit_flush)".
|
```
function printnow($str, $bbreak=true){
print "$str";
if($bbreak){
print "<br />";
}
ob_flush(); flush();
}
```
Obviously this isn't going to behave if you pass it complicated objects (or at least those that don't implement \_\_toString) but, you get the idea.
|
Is there a way to have PHP print the data to a web browser in real time?
|
[
"",
"php",
""
] |
I have a table in a MSSQL database that looks like this:
```
Timestamp (datetime)
Message (varchar(20))
```
Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.
What is a good query or set of statements that, given a particular date, returns:
* 0 if the process never started
* 1 if the process started but did not finish
* 2 if the process started and finished
There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.
EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'.
|
```
Select Count(Message) As Status
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
```
You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...
```
Select Case When SumStarted = 0 And SumFinished = 0 Then 'Not Started'
When SumStarted = 1 And SumFinished = 0 Then 'Started'
When SumStarted = 1 And SumFinished = 1 Then 'Finished'
When SumStarted > 1 Then 'Multiple Starts'
When SumFinished > 1 Then 'Multiple Finish'
When SumFinished > 0 And SumStarted = 0 Then 'Finish Without Start'
End As StatusMessage
From (
Select Sum(Case When Message = 'Started' Then 1 Else 0 End) As SumStarted,
Sum(Case When Message = 'Finished' Then 1 Else 0 End) As SumFinished
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
) As AliasName
```
|
```
DECLARE @TargetDate datetime
SET @TargetDate = '2008-01-01'
DECLARE @Messages varchar(max)
SET @Messages = ''
SELECT @Messages = @Messages + '|' + Message
FROM process_monitor
WHERE @TargetDate <= Timestamp and Timestamp < DateAdd(dd, 1, @TargetDate)
and Message in ('Finished', 'Started')
ORDER BY Timestamp desc
SELECT CASE
WHEN @Messages = '|Finished|Started' THEN 2
WHEN @Messages = '|Started' THEN 1
WHEN @Messages = '' THEN 0
ELSE -1
END
```
|
Sql query to determine status?
|
[
"",
"sql",
"sql-server",
""
] |
I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using
```
document.body.clientHeight
```
but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big.
Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.
Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?
Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution.
|
have you considered using [jQuery](http://jquery.com)? it abstracts most of the browser specific functionality away into a common interface.
```
var width = $(document).width();
var height = $(document.height();
$('#mySpecialElement').width(width).height(height);
```
|
This *may* help the cause ...
> From <http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/> :
```
<script type="text/javascript">
<!--
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
//-->
</script>
```
|
Proper IE6 HTML element dimensions
|
[
"",
"javascript",
"internet-explorer",
""
] |
In a [Pygame](http://www.pygame.org/) application, I would like to render resolution-free GUI widgets described in SVG.
How can I achieve this?
(I like the [OCEMP GUI](http://ocemp.sourceforge.net/gui.html) toolkit, but it seems to be bitmap-dependent for its rendering.)
|
This is a complete example which combines hints by other people here.
It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.
```
#!/usr/bin/python
import array
import math
import cairo
import pygame
import rsvg
WIDTH = 512
HEIGHT = 512
data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)
screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
```
|
**SVG files are supported with Pygame Version 2.0**. Since Version 2.0.2, SDL Image supports SVG ([Scalable Vector Graphics](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics)) files (see [SDL\_image 2.0](https://www.libsdl.org/projects/SDL_image)). Therefore, with pygame version 2.0.1, SVG files can be loaded into a [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) object with [`pygame.image.load()`](http://www.pygame.org/docs/ref/image.html):
```
surface = pygame.image.load('my.svg')
```
Before Pygame 2, you had to implement [Scalable Vector Graphics](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics) loading with other libraries. Below are some ideas on how to do this.
---
A very simple solution is to use [CairoSVG](https://cairosvg.org/). With the function `cairosvg.svg2png`, an [Vector Graphics (SVG)](https://de.wikipedia.org/wiki/Scalable_Vector_Graphics) files can be directly converted to an [Portable Network Graphics (PNG)] file
Install [CairoSVG](https://pypi.org/project/CairoSVG/).
```
pip install CairoSVG
```
Write a function that converts a SVF file to a PNG ([`ByteIO`](https://docs.python.org/3/library/io.html)) and creates a [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) object may look as follows:
```
import cairosvg
import io
def load_svg(filename):
new_bites = cairosvg.svg2png(url = filename)
byte_io = io.BytesIO(new_bites)
return pygame.image.load(byte_io)
```
See also [Load SVG](https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_surface_and_image.md#load-svg)
---
An alternative is to use *svglib*. However, there seems to be a problem with transparent backgrounds. There is an issue about this topic [How to make the png background transparent? #171](https://github.com/deeplook/svglib/issues/171).
Install [svglib](https://pypi.org/project/svglib/).
```
pip install svglib
```
A function that parses and rasterizes an SVG file and creates a [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) object may look as follows:
```
from svglib.svglib import svg2rlg
import io
def load_svg(filename):
drawing = svg2rlg(filename)
str = drawing.asString("png")
byte_io = io.BytesIO(str)
return pygame.image.load(byte_io)
```
---
Anther simple solution is to use *pynanosvg*. The downside of this solution is that *nanosvg* is no longer actively supported and does not work with Python 3.9. [pynanosvg](https://github.com/ethanhs/pynanosvg) can be used to load and rasterize [Vector Graphics (SVG)](https://de.wikipedia.org/wiki/Scalable_Vector_Graphics) files. Install [Cython](https://cython.org/) and [pynanosvg](https://github.com/ethanhs/pynanosvg):
```
pip install Cython
pip install pynanosvg
```
The SVG file can be read, rasterized and loaded into a [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) object with the following function:
```
from svg import Parser, Rasterizer
def load_svg(filename, scale=None, size=None, clip_from=None, fit_to=None, foramt='RGBA'):
svg = Parser.parse_file(filename)
scale = min((fit_to[0] / svg.width, fit_to[1] / svg.height)
if fit_to else ([scale if scale else 1] * 2))
width, height = size if size else (svg.width, svg.height)
surf_size = round(width * scale), round(height * scale)
buffer = Rasterizer().rasterize(svg, *surf_size, scale, *(clip_from if clip_from else 0, 0))
return pygame.image.frombuffer(buffer, surf_size, foramt)
```
---
Minimal example:
[](https://i.stack.imgur.com/LOMwY.png)
```
import cairosvg
import pygame
import io
def load_svg(filename):
new_bites = cairosvg.svg2png(url = filename)
byte_io = io.BytesIO(new_bites)
return pygame.image.load(byte_io)
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygame_surface = load_svg('Ice-001.svg')
size = pygame_surface.get_size()
scale = min(window.get_width() / size[0], window.get_width() / size[1]) * 0.8
pygame_surface = pygame.transform.scale(pygame_surface, (round(size[0] * scale), round(size[1] * scale)))
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((127, 127, 127))
window.blit(pygame_surface, pygame_surface.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
```
|
SVG rendering in a Pygame application. Prior to Pygame 2.0, Pygame did not support SVG. Then how did you load it?
|
[
"",
"python",
"svg",
"pygame",
"widget",
"pygame-surface",
""
] |
I have always been for documenting code, but when it comes to AJAX + PHP, it's not always easy: the code is really spread out! Logic, data, presentation - you name it - are split and mixed between server-side and client-side code. Sometimes there's also database-side code (stored procedures, views, etc) doing part of the work.
This challenges me to come up with an efficient way to document such code. I usually provide a list of .js files inside .php file as well as list of .php files inside .js file. I also do in-line comments and function descriptions, where I list what function is used by what file and what output is expected. I do similar tasks for database procedures. Maybe there's a better method?
Any ideas or experiences?
Note: This question applies to any client+server-side applications, not just Javascript+PHP.
|
I think it's best to take a hierarchical approach.
For api-level documentation like on the function and class level, write inline documentation in the code and generate html documentation out of them using the many documentation tools out there ([JSDoc](http://jsdoc.sourceforge.net/), [phpDocumentor](http://www.phpdoc.org/), [OraDoclet](http://oradoclet.sourceforge.net/), etc). Bonus points if your doc tools can integrate with your source control tools so you can jump to specific lines of code from your api docs.
Once you have your doc tools in place, start generating the documentation as part of your build process (you have a build process, right?) for each new build and push the documentation to a standard web location.
Once these api docs are online, you can create a wiki for high level documentation such as browser->web->db interactions, user stories, schema diagrams, etc. It's best to write in brief prose or bullet points for high level documentation, linking to api docs and source control when necessary.
|
I think your method is pretty good. The only thing is that everything inside the js file is readable by others and therefore documenting what PHP files are used could lead to a security hole, in the off chance they can get to a file that returns something it shouldn't. Also, although not a big deal, on higher traffic sites, downloading say 500bytes of comments can add up.
Both of these are not big, but just thoughts I've had before.
|
Best way to document AJAX + PHP code?
|
[
"",
"php",
"ajax",
"documentation",
""
] |
Is there a tool/plugin/function for Firefox that'll dump out a memory usage of Javascript objects that you create in a page/script? I know about Firebug's profiler but I'd like something more than just times. Something akin to what Yourkit has for Java profiling of memory usage.
Reason is that a co-worker is using id's for "keys" in an array and is creating 1000's of empty slots when he does this. He's of the opinion that this is harmless whereas my opinion differs. I'd like to offer some proof to prove whether I'm right or not.
|
I haven't tried the Sofware verify tools, but Mozilla has tools that track overall memory consumed by firefox for the purpose of stemming leaks:
<http://www.mozilla.org/performance/tools.html>
and:
<https://wiki.mozilla.org/Performance:Leak_Tools>
There's also this guy saying to avoid large arrays in the context of closures, towards article bottom
<http://ajax.sys-con.com/node/352585>
|
I think [JavaScript Memory Validator](http://www.softwareverify.com/javascript/memory/feature.html) from Software Verification Limited can help you, it has allocations view, objects view, generations view, etc. It's not free but you can use the evaluation version to check your coworker's code. They also have a Performance and Coverage Validators...
|
Javascript memory profiler for Firefox
|
[
"",
"javascript",
"firefox",
"memory",
"profiling",
""
] |
Let's say we have `index.php` and it is stored in `/home/user/public/www` and `index.php` calls the class `Foo->bar()` from the file `inc/app/Foo.class.php`.
I'd like the bar function in the `Foo` class to get a hold of the path `/home/user/public/www` in this instance — I don't want to use a global variable, pass a variable, etc.
|
Wouldn't this get you the directory of the running script more easily?
```
$dir=dirname($_SERVER["SCRIPT_FILENAME"])
```
|
You can use [debug\_backtrace](https://www.php.net/debug_backtrace) to look at the calling path and get the file calling this function.
A short example:
```
class Foo {
function bar() {
$trace = debug_backtrace();
echo "calling file was ".$trace[0]['file']."\n";
}
}
```
|
Can I get the path of the PHP file originally called within an included file?
|
[
"",
"php",
"path",
""
] |
I would like to be able to monitor my major system health indicators from inside our Java-based system. Major points of interest include CPU temperature, motherboard temperature, fan speed, etc.
Is there a package available that:
1. Makes this sort of data available to Java?
2. Works on Windows or Linux or both?
3. Is open / free / cheap?
|
There are MIBs supported by both Windows and Linux that expose the parameters you are looking for via SNMP. Also, most major vendors have special MIBs published for their server hardware.
I have implemented SNMP MIBs and monitoring for Java applications using the commercial [iReasoning SNMP API](http://www.ireasoning.com/snmpapi.shtml) and they worked great. There is also the open source [SNMP4J](http://www.snmp4j.org/), which I don't personally have experience with, but looks pretty good.
So, for your needs, you would turn on the publishing of SNMP information for the hosts you want to monitor. No coding necessary. This is just a configuration issue.
For CPU temperature, for example, you must enable the MIB LM-SENSORS-MIB. Under Linux you can use the snmpwalk client to take a look at OID .1.3.6.1.4.1.2021.13.16.2.1.3
to see CPU temperature. Once you have that up and you know it's publishing data correctly, you can begin to implement your real monitoring solution.
You can use a Java SNMP library to poll and subscribe to SNMP traps for the hosts you want to monitor. You could also use any commercial or open-source monitoring tool (Google for *SNMP console*).
|
The closest thing you'll find is the Hyperic Sigar library:
<http://www.hyperic.com/products/sigar.html>
It doesn't get down to temperatures AFAIK but does show you a number of native stats like CPU, memory, disk I/O, network I/O, etc. It's ported to most of the architectures people are deploying Java on today. License is GPL although I think you can buy commercial licenses as well.
We use Sigar with Terracotta for cluster monitoring and have been very happy with it.
|
What is the best way for a Java program to monitor system health?
|
[
"",
"java",
"system-monitoring",
""
] |
I have used IPC in Win32 code a while ago - critical sections, events, and semaphores.
How is the scene in the .NET environment?
Are there any tutorial explaining all available options and when to use and why?
|
Most recent Microsoft's stuff in IPC is [Windows Communication Foundation](http://en.wikipedia.org/wiki/Windows_Communication_Foundation). Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly.
Useful resource:
* [Interprocess Communication with WCF](http://www.ddj.com/windows/196802111) on Dr. Dobb's portal
* [WCF Communication Options in the .NET Framework 3.5](http://www.infoq.com/news/2008/01/wcf-comm-options)
and of course [MSDN on WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx)
|
Apart from the obvious (WCF), there is a ZeroMQ binding for C#/CLR which is pretty good:
<http://www.zeromq.org/bindings:clr>
Does message-oriented IPC, pub/sub and various other strategies with much less code and config than WCF.
It's also at least an order of magnitude faster than anything else and has less latency if you require low latency comms.
With respects to semaphores, locks, mutexes etc. If you share by communicating rather than communicate by sharing, you'll have a whole load less hassle than the traditional paradigm.
|
IPC Mechanisms in C# - Usage and Best Practices
|
[
"",
"c#",
".net",
"ipc",
""
] |
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.
IE: given
```
struct mstct {
int myfield;
int myfield2;
};
```
I could write:
```
mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
```
And get `offset 4` for the output. How can I do it without that `mstct thing` declaration/allocating one?
I know that `&<struct>` does not always point at the first byte of the first field of the structure, I can account for that later.
|
How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
```
#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
```
|
Right, use the `offsetof` macro, which (at least with GNU CC) is available to both C and C++ code:
```
offsetof(struct mstct, myfield2)
```
|
C/C++ Structure offset
|
[
"",
"c++",
"c",
"oop",
""
] |
I definitifely like the one at stackoverflow, because it's clean and simple. Also the live preview with code/syntax hilighting is really helpful (and motivating).
What is your favourite Javascript Editor Framework and why?
|
I like [widgEditor](http://themaninblue.com/experiment/widgEditor/) because it's very simple and it only do the minimum. TinyMCE or FCKeditor are goods, but they are too big for what I need.
|
[TinyMCE](http://tinymce.moxiecode.com/index.php) looks good with lots of useful features.
|
What is your favourite Java Script WYSIWYG Editor component?
|
[
"",
"javascript",
"html",
"editor",
"textarea",
"wysiwyg",
""
] |
**Has anyone had success automating testing directly on embedded hardware?**
Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI devices (flash memory) etc..
**Is this even worth the effort?**
We typically target:
Processor: 8 or 16 bit microcontrollers (some DSP stuff)
Language: C (sometimes c++).
|
Sure. In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly.
The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, or purpose built HIL/SIL test software such as MxVDev.
Hardware in the Loop (HIL) testing is probably what you mean, and it simply involves some USB hardware I/O connected to the I/O of your device, with software on the computer running tests against it.
Whether it's worth it depends.
In the high reliability industry (airplane, automotive, etc) the customer specifies very extensive hardware testing, so you have to have it just to get the bid.
In the consumer industry, with non complex projects it's usually not worth it.
With any project where there's more than a few programmers involved, though, it's *really* nice to have a nightly regression test run on the hardware - it's hard to correctly simulate the hardware to the degree needed to satisfy yourself that the software testing is enough.
The testing then shows immediately when a problem has entered the build.
Generally you perform both black box and white box testing - you have diagnostic code running on the device that allows you to spy on signals and memory in the hardware (which might just be a debugger, or might be code you wrote that reacts to messages on a bus, for instance). This would be white box testing where you can see what's happening internally (and even cause some things to happen, such as critical memory errors which can't be tested without introducing the error yourself).
We also run a bunch of 'black box' tests where the diagnostic path is ignored and only the I/O is stimulated/read.
For a much cheaper setup, you can get $100 microcontroller boards with USB and/or ethernet (such as the Atmel UC3 family) which you can connect to your device and run basic testing.
It's especially useful for product maintenance - when the project is done, store a few working boards, the tester, and a complete set of software on CD. When you need to make a modification or debug a problem, it's easy to set it all back up and work on it with some knowledge (after testing) that the major functionality was not affected by your changes.
-Adam
|
Yes. I have had success, but it is not a stragiht-forward problem to solve. In a nutshell here is what my team did:
1. Defined a variety of unit tests using a home-built C unit-testing framework. Basically, just a lot of macros, most of which were named `TEST_EQUAL`, `TEST_BITSET`, `TEST_BITVLR`, etc.
2. Wrote a boot code generator that took these compiled tests and orchestrated them into an execution environment. It's just a small driver that executes our normal startup routine - but instead of going into the control loop, it executes a test suite. When done, it stores the last suite to run in flash memory, then it resets the CPU. It will then run then next suite. This is to provide isolation incase a suite dies. (However, you may want to disable this to make sure your modules cooperate. But that's an integration test, not a unit test.)
3. Individual tests would log their output using the serial port. This was OK for our design because the serial port was free. You will have to find a way to store your results if all your IO is consumed.
It worked! And it was great to have. Using our custom datalogger, you could hit the "Test" button, and a couple minutes later, you would have all the results. I highly recommend it.
**Updated** to clarify how the test driver works.
|
Test Automation with Embedded Hardware
|
[
"",
"c++",
"c",
"unit-testing",
"embedded",
"testing-strategies",
""
] |
I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.
Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.
|
## PyS60 -- its cool :)
I worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on
Symbian Mobiles and Powerful too. I did my Major project in PyS60, which was a [GSM locator](http://sourceforge.net/projects/gsmlocator)(its not the latest version) app for Symbian phones.
There is also a very neat py2sis utility which converts your py apps to portabble sis apps that can be installed on any Sumbian phones. The ease of use of Python scripting laanguage and a good set of warapped APIs for Mobile functions just enables you to do anything very neatly and quickly.
The latest Video and Camera APIs let you do neary everything that can be done with the phone. I'd suggest you few very good resources to start with
1. [Forum Nokia](http://www.forum.nokia.com/Resources_and_Information/Tools/Runtimes/Python_for_S60/)
2. [Nokia OpenSource Resource
center](http://opensource.nokia.com/projects/pythonfors60/)
3. [A very good tutorial (for beginners)](http://www.mobilenin.com/pys60/menu.htm)
Just access these, download the Emulator, and TAKE OFF for a ride with PyS60. M sure you'll love it.
P.S. : as the post is so old, I believe u must already be either loving it or finished off with it. But I just cudn't resist answering. :)
|
Have you checked out the [Mobile Python Book](http://www.mobilepythonbook.com/)?
> This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.
[](https://i.stack.imgur.com/zTC1X.png)
(source: [mobilenin.com](http://www.mobilenin.com/mobilepythonbook/book-cover.png))
|
Does anyone have experience with PyS60 mobile development
|
[
"",
"python",
"mobile",
"pys60",
""
] |
# 1st phase
I have a problem shutting down my running JBoss instance under Eclipse since I changed
the JNDI port of JBoss. Of course I can shut it down from the console view but not with
the stop button (it still searches JNDI port at the default 1099 port). I'm looking
forward to any solutions. Thank you!
## Used environment:
* JBoss 4.0.2 (using *default*)
* Eclipse 3.4.0. (using JBoss Tools 2.1.1.GA)
Default ports: 1098, 1099
Changed ports: 11098, 11099
I changed the following part in jbosspath/server/default/conf/jboss-service.xml:
```
<!-- ==================================================================== -->
<!-- JNDI -->
<!-- ==================================================================== -->
<mbean code="org.jboss.naming.NamingService"
name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
<!-- The call by value mode. true if all lookups are unmarshalled using
the caller's TCL, false if in VM lookups return the value by reference.
-->
<attribute name="CallByValue">false</attribute>
<!-- The listening port for the bootstrap JNP service. Set this to -1
to run the NamingService without the JNP invoker listening port.
-->
<attribute name="Port">11099</attribute>
<!-- The bootstrap JNP server bind address. This also sets the default
RMI service bind address. Empty == all addresses
-->
<attribute name="BindAddress">${jboss.bind.address}</attribute>
<!-- The port of the RMI naming service, 0 == anonymous -->
<attribute name="RmiPort">11098</attribute>
<!-- The RMI service bind address. Empty == all addresses
-->
<attribute name="RmiBindAddress">${jboss.bind.address}</attribute>
<!-- The thread pool service used to control the bootstrap lookups -->
<depends optional-attribute-name="LookupPool"
proxy-type="attribute">jboss.system:service=ThreadPool</depends>
</mbean>
<mbean code="org.jboss.naming.JNDIView"
name="jboss:service=JNDIView"
xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml">
</mbean>
```
## Eclipse setup:

*About my JBoss Tools preferences:*
I had a previous version, I got this problem, I read about some bugfix in JbossTools, so updated to 2.1.1.GA. Now the buttons changed, and I've got a new preferences view, but I cannot modify anything...seems to be abnormal as well:

## Error dialog:

## The stacktrace:
```
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at org.jboss.Shutdown.main(Shutdown.java:202)
Caused by: javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:254)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1370)
... 4 more
Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:228)
... 5 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
at java.net.Socket.connect(Socket.java:452)
at java.net.Socket.connect(Socket.java:402)
at java.net.Socket.<init>(Socket.java:309)
at java.net.Socket.<init>(Socket.java:211)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:69)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:62)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:224)
... 5 more
Exception in thread "main"
```
# 2nd phase:
After creating a new Server in File/new/other/server, it did appear in the preferences tab. Now the stop button is working (the server receives the shutdown messages without any additional modification of the jndi port -- there is no opportunity for it now) but it still throws an error message, though different, it's without exception stack trace: "Server JBoss 4.0 Server failed to stop."
|
OK, what you have to do is File->New->Other->Server, and set up your JBoss server there. It will then appear in Preferences->JBossTools->Servers.
Convoluted.
|
Here is a detailed fix for this problem:
The Eclipse WTP server connector won't shut down JBoss when the jndi port is remapped.
This is because the default server connector profiles don't use their own alias for the jndiPort. This problem is also discussed at eclipse.org:
<http://www.eclipse.org/forums/index.php?t=msg&goto=489439&S=0db4920aab0a501c80a626edff84c17d#msg_489439>
The solution comes from the .serverdef files in eclipse:
```
<eclipse>\plugins\org.eclipse.jst.server.generic.jboss_1.5.105.v200709061325\servers\jboss*.serverdef
```
They declare an xml property for the jndi port:
```
<property id="jndiPort"
label="%jndiPort"
type="string"
context="server"
default="1099" />
```
This simply needs to be used where the serverdef has the STOP command coded:
So this:
```
<stop>
<mainClass>org.jboss.Shutdown</mainClass>
<workingDirectory>${serverRootDirectory}/bin</workingDirectory>
<programArguments>-S</programArguments>
<vmParameters></vmParameters>
<classpathReference>jboss</classpathReference>
</stop>
```
becomes this:
```
<stop>
<mainClass>org.jboss.Shutdown</mainClass>
<workingDirectory>${serverRootDirectory}/bin</workingDirectory>
<programArguments>-s jnp://${serverAddress}:${jndiPort}</programArguments>
<vmParameters></vmParameters>
<classpathReference>jboss</classpathReference>
</stop>
```
The philosophy for this can be verified by comparison to the definition for the jndi connection:
```
<jndiConnection>
<providerUrl>jnp://${serverAddress}:${jndiPort}</providerUrl>
<initialContextFactory>org.jnp.interfaces.NamingContextFactory</initialContextFactory>
<jndiProperty>
<name></name>
<value></value>
</jndiProperty>
</jndiConnection>
```
Credit for the inspiration for this general case fix goes to: Moisa Laurentiu Florin. It was their contribution that got me to look for a way of substituting in the ${jndiPort} instead of a hard coded value.
This fix corrects both plain Eclipse WTP server connector. I'm still investigating the JBOss IDE connector
|
Problems with shutting down JBoss in Eclipse if I change JNDI port
|
[
"",
"java",
"eclipse",
"jboss",
"jboss-tools",
""
] |
I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace.
Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using this:
```
System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits(
new System.Drawing.Rectangle(0, 0, tempImage.Width, tempImage.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, tempImage.PixelFormat);
try
{
//use external library on the data
}//Exception not handled here; throw to calling method
finally
{
tempImage.UnlockBits(tempImageData);
}
```
(I've recently been playing around with the using statement, which is very useful in C#, which gave me the idea that I should do this.) Trouble is, even MS's own documentation (<http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx>) doesn't see it fit to use the try-finally pattern.
Is try-finally necessary or gratuitous?
**Update: I may end up catching and rethrowing the exception, since I don't know what it might be and wasn't catching them earlier.**
Thanks!
|
The try-finally pattern is correct. Since this is external code, you have no control over what exceptions are thrown, and the UnlockBits cleanup code needs to be executed regardless of what error has occurred.
|
Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option.
|
unlockbits, lockbits, and try-finally
|
[
"",
"c#",
".net",
""
] |
I make a lot of web applications and from time to time I need a color picker. What's one that I can use like an API and doesn't require a lot of code to plug in? I also need it to work in all browsers.
|
[Farbtastic](http://acko.net/dev/farbtastic) is a nice jQuery color picker
But apparently doesn't work in IE6
[Here](http://www.eyecon.ro/colorpicker/#about) is another jQuery color picker that looks nice, not sure about it compatibility though.
|
I like [jscolor](http://jscolor.com/try.php) the most, lightweight and lots of options.
|
What's a good JavaScript plugin color picker?
|
[
"",
"javascript",
"color-picker",
""
] |
I have an ant build that makes directories, calls javac and all the regular stuff. The issue I am having is that when I try to do a clean (delete all the stuff that was generated) the delete task reports that is was unable to delete some files. When I try to delete them manually it works just fine. The files are apparently not open by any other process but ant still does not manage to delete them. What can I do?
|
I encountered this problem once.
It was because the file i tried to delete was a part of a **classpath** for another task.
|
It depends ...
* The Ant process doesn't have enough permissions to delete the files (typically because they were created by a different user, perhaps a system user). Try running your Ant script as an administrative user, using Run As.
* Windows is really bad at cleaning up file locks when processes die or are killed; consequently, Windows thinks the file is locked by a process that died (or was killed). There's nothing you can do in this situation other than reboot.
* Get better tools to inspect your system state. I recommend downloading the [SysInternals](http://technet.microsoft.com/en-us/sysinternals/default.aspx) tools and using them instead of the default Windows equivalents.
|
Ant is not able to delete some files on windows
|
[
"",
"java",
"windows",
"ant",
"build-automation",
""
] |
I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the `this` pointer is being used. From the behavior of the program, I have deduced that the `this` pointer is referring to the class on which the method was invoked, and not the object being created by the literal.
This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example:
```
// inside class definition, itself an object literal, we have this function:
onRender: function() {
this.menuItems = this.menuItems.concat([
{
text: 'Group by Module',
rptletdiv: this
},
{
text: 'Group by Status',
rptletdiv: this
}]);
// etc
}
```
|
Cannibalized from another post of mine, here's more than you ever wanted to know about *this*.
Before I start, here's the most important thing to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes (ES6 `class` is [syntactic sugar](https://stackoverflow.com/a/30783368/2039244)). If something looks like a class, it's a clever trick. Javascript has **objects** and **functions**. (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)
The *this* variable is attached to functions. Whenever you invoke a function, *this* is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.
There are four ways to invoke functions in javascript. You can invoke the function as a *method*, as a *function*, as a *constructor*, and with *apply*.
## As a Method
A method is a function that's attached to an object
```
var foo = {};
foo.someMethod = function(){
alert(this);
}
```
When invoked as a method, *this* will be bound to the object the function/method is a part of. In this example, this will be bound to foo.
## As A Function
If you have a stand alone function, the *this* variable will be bound to the "global" object, almost always the *window* object in the context of a browser.
```
var foo = function(){
alert(this);
}
foo();
```
**This may be what's tripping you up**, but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behavior.
Many people get around the problem by doing something like, um, this
```
var foo = {};
foo.someMethod = function (){
var that=this;
function bar(){
alert(that);
}
}
```
You define a variable *that* which points to *this*. Closure (a topic all its own) keeps *that* around, so if you call bar as a callback, it still has a reference.
NOTE: In `use strict` mode if used as function, `this` is not bound to global. (It is `undefined`).
## As a Constructor
You can also invoke a function as a constructor. Based on the naming convention you're using (TestObject) this also **may be what you're doing and is what's tripping you up**.
You invoke a function as a Constructor with the new keyword.
```
function Foo(){
this.confusing = 'hell yeah';
}
var myObject = new Foo();
```
When invoked as a constructor, a new Object will be created, and *this* will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and *this* will be bound to the global object. Use that var that = this trick/pattern.
Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes.
## With the Apply Method
Finally, every function has a method (yes, functions are objects in Javascript) named "apply". Apply lets you determine what the value of *this* will be, and also lets you pass in an array of arguments. Here's a useless example.
```
function foo(a,b){
alert(a);
alert(b);
alert(this);
}
var args = ['ah','be'];
foo.apply('omg',args);
```
|
## Function calls
Functions are just a type of Object.
All Function objects have [call](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) and [apply](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply) methods which execute the Function object they're called on.
When called, the first argument to these methods specifies the object which will be referenced by the `this` keyword during execution of the Function - if it's `null` or `undefined`, the global object, `window`, is used for `this`.
Thus, calling a Function...
```
whereAmI = "window";
function foo()
{
return "this is " + this.whereAmI + " with " + arguments.length + " + arguments";
}
```
...with parentheses - `foo()` - is equivalent to `foo.call(undefined)` or `foo.apply(undefined)`, which is *effectively* the same as `foo.call(window)` or `foo.apply(window)`.
```
>>> foo()
"this is window with 0 arguments"
>>> foo.call()
"this is window with 0 arguments"
```
Additional arguments to `call` are passed as the arguments to the function call, whereas a single additional argument to `apply` can specify the arguments for the function call as an Array-like object.
Thus, `foo(1, 2, 3)` is equivalent to `foo.call(null, 1, 2, 3)` or `foo.apply(null, [1, 2, 3])`.
```
>>> foo(1, 2, 3)
"this is window with 3 arguments"
>>> foo.apply(null, [1, 2, 3])
"this is window with 3 arguments"
```
If a function is a property of an object...
```
var obj =
{
whereAmI: "obj",
foo: foo
};
```
...accessing a reference to the Function via the object and calling it with parentheses - `obj.foo()` - is equivalent to `foo.call(obj)` or `foo.apply(obj)`.
However, functions held as properties of objects are not "bound" to those objects. As you can see in the definition of `obj` above, since Functions are just a type of Object, they can be referenced (and thus can be passed by reference to a Function call or returned by reference from a Function call). When a reference to a Function is passed, no additional information about where it was passed *from* is carried with it, which is why the following happens:
```
>>> baz = obj.foo;
>>> baz();
"this is window with 0 arguments"
```
The call to our Function reference, `baz`, doesn't provide any context for the call, so it's effectively the same as `baz.call(undefined)`, so `this` ends up referencing `window`. If we want `baz` to know that it belongs to `obj`, we need to somehow provide that information when `baz` is called, which is where the first argument to `call` or `apply` and closures come into play.
## Scope chains
```
function bind(func, context)
{
return function()
{
func.apply(context, arguments);
};
}
```
When a Function is executed, it creates a new scope and has a reference to any enclosing scope. When the anonymous function is created in the above example, it has a reference to the scope it was created in, which is `bind`'s scope. This is known as a "closure."
```
[global scope (window)] - whereAmI, foo, obj, baz
|
[bind scope] - func, context
|
[anonymous scope]
```
When you attempt to access a variable this "scope chain" is walked to find a variable with the given name - if the current scope doesn't contain the variable, you look at the next scope in the chain, and so on until you reach the global scope. When the anonymous function is returned and `bind` finishes executing, the anonymous function still has a reference to `bind`'s scope, so `bind`'s scope doesn't "go away".
Given all the above you should now be able to understand how scope works in the following example, and why the technique for passing a function around "pre-bound" with a particular value of `this` it will have when it is called works:
```
>>> baz = bind(obj.foo, obj);
>>> baz(1, 2);
"this is obj with 2 arguments"
```
|
How does "this" keyword work within a function?
|
[
"",
"javascript",
"this",
"language-design",
"language-features",
""
] |
Am looking for C# open source NMEA parser.
|
Well, I'm not familiar with it myself, but some quick searches show one on [CodeProject](http://www.codeproject.com/KB/cs/NMEAtoOSG.aspx), which links to 2 other such, [here](http://www.codeproject.com/KB/mobile/WritingGPSApplications1.aspx) and [here](http://www.codeproject.com/KB/mobile/WritingGPSApplications2.aspx). Any of those help?
|
check out [sharpGPS](http://www.codeplex.com/SharpGPS) . there are several other gps and nmea related projects o codeplex too
|
C# open source NMEA parser
|
[
"",
"c#",
"nmea",
""
] |
I am trying to take a rather large CSV file and insert it into a MySQL database for referencing in a project. I would like to use the first line of the file to create the table using proper data types and not varchar for each column. The ultimate goal is to automate this process as I have several similar files but the each has different data and a different amount of "columns" in CSV files. The problem that I am having is gettype() is returning 'string' for each column instead of int, float and string as I would like it to.
Platform is PHP 5, OS is ubuntu 8.04
here is my code so far:
```
<?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'file.csv';
$tableName = 'file_csv';
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents); // explode to make sure we are only using the first line.
$fieldList = explode(',', $fileLines[0]); // separate columns, put into array
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."<br/>\n";
for($i = 0; $i <= count($fieldList); $i++)
{
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
echo ' PRIMARY KEY (`0`)'."<br/>\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';
```
Example First line:
1,0,0,0,0,0,0,0,0,0,0,0,0.000000,0.000000,0,0,0,,0,0,1,0,50,'Word of Recall (OLD)',
|
Building on [Nouveau](https://stackoverflow.com/questions/173498/using-php-to-take-the-first-line-of-a-csv-file-and-create-a-mysql-table-with-th#173526)'s code you could do this
```
for($i = 0; $i <= count($fieldList); $i++)
{
if (is_numeric($fieldList[$i]))
{
if (strpos($fieldList[$i],'.') !== false){
$fieldList[$i] = (int)$fieldList[$i];
}else{
$fieldList[$i] = (float)$fieldList[$i];
}
}
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
case 'double':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
```
That works, note the addition of "case 'double':" in the switch, but there may be a better way to do the int/float check as they would only work with standard uk/us numbers.
|
Try casting the value and comparing it with the original one:
```
define('DECIMAL_SEPARATOR', '.');
switch ($fieldList[$i])
{
case (string)(int)$fieldList[$i]:
$typeInfo = (strpos($fieldList[$i], DECIMAL_SEPARATOR) === false) ? 'int(11)' : 'float';
break;
case (string)(float)$fieldList[$i]:
$typeInfo = 'float';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
```
Additionaly, check for the presence of decimal separator in the first case for numbers that are round, yet they have the decimal fraction part.
|
Using PHP to take the first line of a CSV file and create a MySQL Table with the data
|
[
"",
"php",
"mysql",
"file-io",
"csv",
""
] |
I recently wrote a parser in Python using Ply (it's a python reimplementation of yacc). When I was almost done with the parser I discovered that the grammar I need to parse requires me to do some look up during parsing to inform the lexer. Without doing a look up to inform the lexer I cannot correctly parse the strings in the language.
Given than I can control the state of the lexer from the grammar rules I think I'll be solving my use case using a look up table in the parser module, but it may become too difficult to maintain/test. So I want to know about some of the other options.
In Haskell I would use Parsec, a library of parsing functions (known as combinators). Is there a Python implementation of Parsec? Or perhaps some other production quality library full of parsing functionality so I can build a context sensitive parser in Python?
EDIT: All my attempts at context free parsing have failed. For this reason, I don't expect ANTLR to be useful here.
|
An option you may consider, if an LL parser is ok to you, is to give [ANTLR](http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget) a try, it can generate python too (actually it is LL(\*) as they name it, \* stands for the quantity of lookahead it can cope with).
|
I believe that [pyparsing](http://pyparsing.wikispaces.com/ "PyParsing web site") is based on the same principles as parsec.
|
Python implementation of Parsec?
|
[
"",
"python",
"parsing",
"parsec",
"combinators",
""
] |
I have a couple of triggers on a table that I want to keep ***separate*** and would like to priortize them.
I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ?
|
Use sp\_settriggerorder. You can specify the first and last trigger to fire depending on the operation.
[sp\_settriggerorder on MSDN](http://msdn.microsoft.com/en-us/library/ms186762.aspx)
From the above link:
**A. Setting the firing order for a DML trigger**
The following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE operation occurs on the Sales.SalesOrderHeader table.
```
USE AdventureWorks;
GO
sp_settriggerorder
@triggername= 'Sales.uSalesOrderHeader',
@order='First',
@stmttype = 'UPDATE';
```
**B. Setting the firing order for a DDL trigger**
The following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER\_TABLE event occurs in the AdventureWorks database.
```
USE AdventureWorks;
GO
sp_settriggerorder
@triggername= 'ddlDatabaseTriggerLog',
@order='First',
@stmttype = 'ALTER_TABLE',
@namespace = 'DATABASE';
```
|
Rememebr if you change the trigger order, someone else could come by later and rearrange it again. And where would you document what the trigger order should be so a maintenance developer knows not to mess with the order or things will break? If two trigger tasks definitely must be performed in a specific order, the only safe route is to put them in the same trigger.
|
How do you priortize multiple triggers of a table?
|
[
"",
"sql",
"sql-server-2005",
"t-sql",
"triggers",
""
] |
I've got a "little" problem with Zend Framework Zend\_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.
I'm not sure if it's particularly Zend\_Pdf problem or php in general.
Source text is encoded in utf-8, as well as the php source file which does the job.
Thank you in advance for your help ;)
P.S. I run Zend Framework v. 1.6 and I use FONT\_TIMES\_BOLD font. FONT\_TIMES\_ROMAN does work
|
`Zend_Pdf` supports UTF-8 in version 1.5 of Zend Framework. However, the standard PDF fonts support only the Latin1 character set. This means you can't use `Zend_Pdf_Font::FONT_TIMES_BOLD` or any other "built-in" font. To use special characters you must load another TTF font that includes characters from other character sets.
I use Mac OS X, so I tried the following code and it produces a PDF document with the correct characters.
```
$pdfDoc = new Zend_Pdf();
$pdfPage = $pdfDoc->newPage(Zend_Pdf_Page::SIZE_LETTER);
// load TTF font from Mac system library
$font = Zend_Pdf_Font::fontWithPath('/Library/Fonts/Times New Roman Bold.ttf');
$pdfPage->setFont($font, 36);
$unicodeString = 'aąbcčdeę';
$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');
$pdfDoc->pages[] = $pdfPage;
$pdfDoc->save('utf8.pdf');
```
See also this bug log: <http://framework.zend.com/issues/browse/ZF-3649>
|
I believe Zend\_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?
Also - what font are you trying to render with? Have you tried alternate fonts?
|
How to generate pdf files _with_ utf-8 multibyte characters using Zend Framework
|
[
"",
"php",
"zend-framework",
"pdf",
"unicode",
""
] |
Is there any framework for querying XML SQL Syntax, I seriously tire of iterating through node lists.
---
Or is this just wishful thinking (if not idiotic) and certainly not possible since XML isn't a relational database?
|
[XQuery](http://www.w3schools.com/xquery/default.asp) and XPath... XQuery is more what you are looking for if a SQL structure is desirable.
|
.Net Framework provides LINQ to do this or you can use the .Net System.Data namespace to load data from XML files.
You can even create queries that have joins among the tables, etc.
For example, System.Data.DataTable provides a `ReadXml()` method.
|
Querying XML like SQL?
|
[
"",
"sql",
"xml",
"language-agnostic",
"frameworks",
""
] |
I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the **window.onload** event), but it's different for every browser.
Is there a definitive way to do this on all the browsers?
So far I know of:
* **DOMContentLoaded** : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:
document.addEventListener( "DOMContentLoaded", [init function], false );
* **Deferred script**: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.
* **Polling**: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?
I'd like to be able to go without using document.write or external files.
This can be done simply via jQuery:
```
$(document).ready(function() { ... })
```
but, I'm writing a JS library and can't count on jQuery always being there.
|
There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.
Mozilla, Opera, and modern WebKit support the `DOMContentLoaded` event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's `bindReady()` function.
|
I found this page, which shows a compact self-contained solution. It seems to work on every browser and has an explanation on how:
<http://www.kryogenix.org/days/2007/09/26/shortloaded>
|
Getting notified when the page DOM has loaded (but before window.onload)
|
[
"",
"javascript",
"dom",
""
] |
I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing.
After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache.
The original code looked something like this:
```
private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {
final String key = "Data-" + email;
SomeData[] data = (SomeData[]) StaticCache.get(key);
if (data == null) {
data = service.getSomeDataForEmail(email);
StaticCache.set(key, data, CACHE_TIME);
}
else {
logger.debug("getSomeDataForEmail: using cached object");
}
return data;
}
```
So, to make sure that only one thread was calling the web service when the object at `key` expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email b@b.com would not be blocked by method calls to a@a.com).
I updated the method to look like this:
```
private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {
SomeData[] data = null;
final String key = "Data-" + email;
synchronized(key) {
data =(SomeData[]) StaticCache.get(key);
if (data == null) {
data = service.getSomeDataForEmail(email);
StaticCache.set(key, data, CACHE_TIME);
}
else {
logger.debug("getSomeDataForEmail: using cached object");
}
}
return data;
}
```
I also added logging lines for things like "before synchronization block", "inside synchronization block", "about to leave synchronization block", and "after synchronization block", so I could determine if I was effectively synchronizing the get/set operation.
However it doesn't seem like this has worked. My test logs have output like:
```
(log output is 'threadname' 'logger name' 'message')
http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block
http-80-Processor253 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired
http-80-Processor253 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]
http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block
http-80-Processor263 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired
http-80-Processor263 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]
http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block
http-80-Processor131 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired
http-80-Processor131 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]
http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block
http-80-Processor104 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired
http-80-Processor104 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]
http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block
http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block
```
I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations.
Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the `final String key` is declared within the method, I was thinking that each thread would be getting a reference to *the same object* and therefore would synchronization on this single object.
What am I doing wrong here?
**Update**: after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as
```
final String key = "blah";
...
synchronized(key) { ...
```
do not exhibit the same concurrency problem - only one thread at a time is entering the block.
**Update 2**: Thanks to everyone for the help! I accepted the first answer about `intern()`ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the `key`'s had the same value.
As others have pointed out, using `intern()` for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes.
Currently I'm using the simple solution of just synchronizing the entire method - but I **really** like the code samples provided by martinprobst and MBCook, but since I have about 7 similar `getData()` methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!
|
Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings:
```
final String firstkey = "Data-" + email;
final String key = firstkey.intern();
```
Two Strings with the same value are otherwise not necessarily the same object.
Note that this may introduce a new point of contention, since deep in the VM, intern() may have to acquire a lock. I have no idea what modern VMs look like in this area, but one hopes they are fiendishly optimised.
I assume you know that StaticCache still needs to be thread-safe. But the contention there should be tiny compared with what you'd have if you were locking on the cache rather than just the key while calling getSomeDataForEmail.
**Response to question update**:
I think that's because a string literal always yields the same object. Dave Costa points out in a comment that it's even better than that: a literal always yields the canonical representation. So all String literals with the same value anywhere in the program would yield the same object.
**Edit**
Others have pointed out that **synchronizing on intern strings is actually a really bad idea** - partly because creating intern strings is permitted to cause them to exist in perpetuity, and partly because if more than one bit of code anywhere in your program synchronizes on intern strings, you have dependencies between those bits of code, and preventing deadlocks or other bugs may be impossible.
Strategies to avoid this by storing a lock object per key string are being developed in other answers as I type.
Here's an alternative - it still uses a singular lock, but we know we're going to need one of those for the cache anyway, and you were talking about 50 threads, not 5000, so that may not be fatal. I'm also assuming that the performance bottleneck here is slow blocking I/O in DoSlowThing() which will therefore hugely benefit from not being serialised. If that's not the bottleneck, then:
* If the CPU is busy then this approach may not be sufficient and you need another approach.
* If the CPU is not busy, and access to server is not a bottleneck, then this approach is overkill, and you might as well forget both this and per-key locking, put a big synchronized(StaticCache) around the whole operation, and do it the easy way.
Obviously this approach needs to be soak tested for scalability before use -- I guarantee nothing.
This code does NOT require that StaticCache is synchronized or otherwise thread-safe. That needs to be revisited if any other code (for example scheduled clean-up of old data) ever touches the cache.
IN\_PROGRESS is a dummy value - not exactly clean, but the code's simple and it saves having two hashtables. It doesn't handle InterruptedException because I don't know what your app wants to do in that case. Also, if DoSlowThing() consistently fails for a given key this code as it stands is not exactly elegant, since every thread through will retry it. Since I don't know what the failure criteria are, and whether they are liable to be temporary or permanent, I don't handle this either, I just make sure threads don't block forever. In practice you may want to put a data value in the cache which indicates 'not available', perhaps with a reason, and a timeout for when to retry.
```
// do not attempt double-check locking here. I mean it.
synchronized(StaticObject) {
data = StaticCache.get(key);
while (data == IN_PROGRESS) {
// another thread is getting the data
StaticObject.wait();
data = StaticCache.get(key);
}
if (data == null) {
// we must get the data
StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE);
}
}
if (data == null) {
// we must get the data
try {
data = server.DoSlowThing(key);
} finally {
synchronized(StaticObject) {
// WARNING: failure here is fatal, and must be allowed to terminate
// the app or else waiters will be left forever. Choose a suitable
// collection type in which replacing the value for a key is guaranteed.
StaticCache.put(key, data, CURRENT_TIME);
StaticObject.notifyAll();
}
}
}
```
Every time anything is added to the cache, all threads wake up and check the cache (no matter what key they're after), so it's possible to get better performance with less contentious algorithms. However, much of that work will take place during your copious idle CPU time blocking on I/O, so it may not be a problem.
This code could be commoned-up for use with multiple caches, if you define suitable abstractions for the cache and its associated lock, the data it returns, the IN\_PROGRESS dummy, and the slow operation to perform. Rolling the whole thing into a method on the cache might not be a bad idea.
|
Synchronizing on an intern'd String might not be a good idea at all - by interning it, the String turns into a global object, and if you synchronize on the same interned strings in different parts of your application, you might get really weird and basically undebuggable synchronization issues such as deadlocks. It might seem unlikely, but when it happens you are really screwed. As a general rule, only ever synchronize on a local object where you're absolutely sure that no code outside of your module might lock it.
In your case, you can use a synchronized hashtable to store locking objects for your keys.
E.g.:
```
Object data = StaticCache.get(key, ...);
if (data == null) {
Object lock = lockTable.get(key);
if (lock == null) {
// we're the only one looking for this
lock = new Object();
synchronized(lock) {
lockTable.put(key, lock);
// get stuff
lockTable.remove(key);
}
} else {
synchronized(lock) {
// just to wait for the updater
}
data = StaticCache.get(key);
}
} else {
// use from cache
}
```
This code has a race condition, where two threads might put an object into the lock table after each other. This should however not be a problem, because then you only have one more thread calling the webservice and updating the cache, which shouldn't be a problem.
If you're invalidating the cache after some time, you should check whether data is null again after retrieving it from the cache, in the lock != null case.
Alternatively, and much easier, you can make the whole cache lookup method ("getSomeDataByEmail") synchronized. This will mean that all threads have to synchronize when they access the cache, which might be a performance problem. But as always, try this simple solution first and see if it's really a problem! In many cases it should not be, as you probably spend much more time processing the result than synchronizing.
|
Synchronizing on String objects in Java
|
[
"",
"java",
"multithreading",
"synchronization",
"thread-safety",
"synchronized",
""
] |
I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could respond.
I am not a Windows guru, and am unsure of how to best accomplish this.
From this page:
<http://bytes.com/forum/thread270002.html>
it would appear that mouse\_event would be good, except that since my app is floating over everything else, I'm guessing my generated events would never make it to the other apps underneath.
It seems the alternative is SendMessage, but that requires a fair amount of manual manipulation of windows, and the mouse events generated aren't "authentic."
Any thoughts on the best way to approach this?
|
After looking at System hooks and other low level solutions I found a much simpler method.
First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.
Second, the following code will let mouse events "fall" through your form.
```
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return createParams;
}
}
```
Lastly, set TopMost to be true.
Your form will now float on top of everything visually, but will give up focus to all other apps.
|
Sounds like you want to do something like filtering user input.
Maybe you just need an keyboard/mouse hook.
You maybe want to take a look at the windows API call SetWindowsHookEx.
There should also be enough samples how to do that in C# available, the first thing i found was [this link](http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx) (maybe not the best article but should give you the idea).
|
How to pass mouse events to applications behind mine in C#/Vista?
|
[
"",
"c#",
"events",
"windows-vista",
"mouse",
""
] |
In MSVC, [DebugBreak()](http://msdn.microsoft.com/en-us/library/ms679297.aspx) or [\_\_debugbreak](http://msdn.microsoft.com/fr-fr/library/f408b4et.aspx) cause a debugger to break. On x86 it is equivalent to writing "\_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the [XCode question](https://stackoverflow.com/questions/37299/xcode-equivalent-of-asm-int-3-debugbreak-halt) about that, but it doesn't seem portable enough.
Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG\_BREAK or something into the code.
|
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
```
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
```
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use `DEBUG_BREAK` in your code.
|
A method that is portable to most POSIX systems is:
```
raise(SIGTRAP);
```
|
Is there a portable equivalent to DebugBreak()/__debugbreak?
|
[
"",
"c++",
"portability",
"debugbreak",
""
] |
I have seen the official demos on lwjgl.org but I would like to see some more tutorial level examples.
|
Google "import org.lwjgl" to find lots of examples, as all code that uses LWJGL must contain that string to import parts of the package.
|
If it still does matter: <http://nehe.gamedev.net/>
All tutorials are ported to LWJGL too.
|
Where can I find sample uses of LWJGL?
|
[
"",
"java",
"opengl",
"openal",
"lwjgl",
""
] |
I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco.
SQL is not my strong suit, and I prefer Hibernate's `Criteria` building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like?
Thanks,
Yuval =8-)
|
For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.
```
Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', '%fran%');
List results = crit.list();
```
|
```
Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);
List results = crit.list();
```
|
Case-insensitive search using Hibernate
|
[
"",
"sql",
"hibernate",
"select",
"case-sensitive",
""
] |
Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.
But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.
Is there a way to say to Eclipse *"Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"*?
|
I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:
```
// @formatter:off
StringBuilder sql = new StringBuilder()
.append("SELECT whatever \n")
.append("FROM some_table");
// @formatter:on
```
It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if I’m not mistaken.
|
I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem.
Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even work with SQL statements, for example:
```
public static final String SELECT_SOMETHING = "SELECT"
+ "OBJECTID, THIS, THAT, THEOTHER, THING"
+ " FROM DBNAME.DBSCHEMA.TABLE_T"
+ " WHERE ID = ?";
```
This statement formats reasonably, because where possible items were split apart and concatenated together. When I don't do this, I get unpredictable results:
```
public static final String SELECT_SOMETHING = "SELECT OBJECTID, SOMETHING FROM DBNAME.DBSCHEMA.TABLE_T WHERE ID = ?";
```
For comments, I place them all on a single line when possible, and allow it to word wrap when it does the formatting.
Also, it is possible to change the style using the code formatter to make things work better for your coding style. You may want everyone on the team to use the same format, just to avoid conflicts. Because it is easier to compare changes with other developers, or prior versions using your source control tool, even if it makes parts of your code less readable, using the formatter has still been to my advantage.
Still, I understand your frustration when the formatter makes bad decisions!
|
Can I Define Exceptions to Eclipse cleanup rules?
|
[
"",
"java",
"eclipse",
""
] |
If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.
Today our signal handler looks as follows:
```
void catchSignal (int reason) {
std :: cerr << "Caught a signal: " << reason << std::endl;
exit (1);
}
```
I can hear the screams of horror with the above, as I have read from this [thread](http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&q=deadlock#) that it is evil to call a non-reentrant function from a signal handler.
Is there a portable way to handle the signal and provide information to users?
**EDIT:** Or at least portable within the POSIX framework?
|
This [table](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948) lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.
By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick:
```
#include <csignal>
#ifdef _WINDOWS_
#define _exit _Exit
#else
#include <unistd.h>
#endif
#define PRINT_SIGNAL(X) case X: \
write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \
break;
void catchSignal (int reason) {
char s[] = "Caught signal: (";
write (STDERR_FILENO, s, sizeof(s) - 1);
switch (reason)
{
// These are the handlers that we catch
PRINT_SIGNAL(SIGUSR1);
PRINT_SIGNAL(SIGHUP);
PRINT_SIGNAL(SIGINT);
PRINT_SIGNAL(SIGQUIT);
PRINT_SIGNAL(SIGABRT);
PRINT_SIGNAL(SIGILL);
PRINT_SIGNAL(SIGFPE);
PRINT_SIGNAL(SIGBUS);
PRINT_SIGNAL(SIGSEGV);
PRINT_SIGNAL(SIGTERM);
}
_Exit (1); // 'exit' is not async-signal-safe
}
```
**EDIT:** Building on windows.
After trying to build this one windows, it appears that 'STDERR\_FILENO' is not defined. From the documentation however its value appears to be '2'.
```
#include <io.h>
#define STDIO_FILENO 2
```
**EDIT:** 'exit' should not be called from the signal handler either!
As pointed out by [fizzer](https://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413), calling \_Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig\_atomic\_t" type can be used to notify the main program that it should exit.
The following I found useful in my searches.
1. [Introduction To Unix Signals Programming](http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html)
2. [Extending Traditional Signals](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html)
|
FWIW, 2 is standard error on Windows also, but you're going to need some conditional compilation because their write() is called \_write(). You'll also want
```
#ifdef SIGUSR1 /* or whatever */
```
etc around all references to signals not guaranteed to be defined by the C standard.
Also, as noted above, you don't want to handle SIGUSR1, SIGHUP, SIGINT, SIGQUIT and SIGTERM like this.
|
Portable way to catch signals and report problem to the user
|
[
"",
"c++",
"c",
"posix",
"signals",
"reentrancy",
""
] |
At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?
```
$mysqli = new mysqli("localhost", "root", "", "test");
...do stuff, perhaps redirect to another page...
$mysqli->close();
```
|
From: <https://www.php.net/manual/en/mysqli.close.php>
> "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."
|
Just because you redirect doesn't mean the script stops executing. A redirect is just a header being sent. If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persistent connections). Don't worry about it.
|
What happens if MySQL connections continually aren't closed on PHP pages?
|
[
"",
"php",
"mysql",
""
] |
I have the following situation:
```
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
```
In my current implementation I save the value of `whichFoo` in a data member in the constructor and use a `switch` in `callFoo()` to decide which of the foo's to call. Alternatively, I can use a `switch` in the constructor to save a pointer to the right `fooN()` to be called in `callFoo()`.
My question is which way is more efficient if an object of class A is only constructed once, while `callFoo()` is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a `switch`?
Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it.
Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :)
|
How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?
In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually *measure* the different choices. You may be surprised!
More info: There is an excellent article [Member Function Pointers and the Fastest Possible C++ Delegates](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) which goes into very deep detail about the implementation of member function pointers.
|
You can write this:
```
class Foo {
public:
Foo() {
calls[0] = &Foo::call0;
calls[1] = &Foo::call1;
calls[2] = &Foo::call2;
calls[3] = &Foo::call3;
}
void call(int number, int arg) {
assert(number < 4);
(this->*(calls[number]))(arg);
}
void call0(int arg) {
cout<<"call0("<<arg<<")\n";
}
void call1(int arg) {
cout<<"call1("<<arg<<")\n";
}
void call2(int arg) {
cout<<"call2("<<arg<<")\n";
}
void call3(int arg) {
cout<<"call3("<<arg<<")\n";
}
private:
FooCall calls[4];
};
```
The computation of the actual function pointer is linear and fast:
```
(this->*(calls[number]))(arg);
004142E7 mov esi,esp
004142E9 mov eax,dword ptr [arg]
004142EC push eax
004142ED mov edx,dword ptr [number]
004142F0 mov eax,dword ptr [this]
004142F3 mov ecx,dword ptr [this]
004142F6 mov edx,dword ptr [eax+edx*4]
004142F9 call edx
```
Note that you don't even have to fix the actual function number in the constructor.
I've compared this code to the asm generated by a `switch`. The `switch` version doesn't provide any performance increase.
|
What is the cost of using a pointer to member function vs. a switch?
|
[
"",
"c++",
"function-pointers",
""
] |
Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?
I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?
I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above.
```
#include <iostream>
using namespace std;
class MemoryLeak
{
private:
char *s;
public:
MemoryLeak() {}
void store()
{
s = "Storing a string"; // ONE
}
char *retrieve()
{
return s;
}
};
int main()
{
MemoryLeak *obj = new MemoryLeak();
obj->store();
cout << obj->retrieve() << endl; // TWO
delete obj;
return 0;
}
```
Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this.
Any pointers or help is, as always, much appreciated :) Thanks.
|
String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.
|
It is undefined behaviour to modify a string literal, and is most likely the cause of the crash in your program (ISO C++: 2.13.4/2). The standard allows for a conversion from a string literal to `char*` for backwards compatibility to C and you should only have that conversion in your code if you absolutely need it.
If you wish to treat the string literal as a constant, then you can change the type of your member to a `const char *`.
If your design requires that `s` can be modified, then I would recommend changing its type to `std::string`.
|
String literals inside functions: automatic variables or allocated in heap?
|
[
"",
"c++",
"c",
"memory",
"memory-management",
"memory-leaks",
""
] |
What is the most efficient way to clone a JavaScript object? I've seen `obj = eval(uneval(o));` being used, but [that's non-standard and only supported by Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval).
I've done things like `obj = JSON.parse(JSON.stringify(o));` but question the efficiency.
I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists.
|
# Native deep cloning
There's now a JS standard called ["structured cloning"](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), that works experimentally in Node 11 and later, will land in browsers, and which has [polyfills for existing systems](https://www.npmjs.com/package/@ungap/structured-clone).
```
structuredClone(value)
```
If needed, loading the polyfill first:
```
import structuredClone from '@ungap/structured-clone';
```
See [this answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838) for more details.
# Older answers
## Fast cloning with data loss - JSON.parse/stringify
If you do not use `Date`s, functions, `undefined`, `Infinity`, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:
`JSON.parse(JSON.stringify(object))`
```
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost
}
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date); // result of .toISOString()
```
See [Corban's answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074) for benchmarks.
## Reliable cloning using a library
Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. **Don't reinvent the wheel** - if you're already using a library, check if it has an object cloning function. For example,
* lodash - [`cloneDeep`](https://lodash.com/docs#cloneDeep); can be imported separately via the [lodash.clonedeep](https://www.npmjs.com/package/lodash.clonedeep) module and is probably your best choice if you're not already using a library that provides a deep cloning function
* Ramda - [`clone`](https://ramdajs.com/docs/#clone)
* AngularJS - [`angular.copy`](https://docs.angularjs.org/api/ng/function/angular.copy)
* jQuery - [`jQuery.extend(true, { }, oldObject)`](https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN); `.clone()` only clones DOM elements
* just library - [`just-clone`](https://www.npmjs.com/package/just-clone); Part of a library of zero-dependency npm modules that do just do one thing.
Guilt-free utilities for every occasion.
|
Checkout this benchmark: <http://jsben.ch/#/bWfk9>
In my previous tests where speed was a main concern I found
```
JSON.parse(JSON.stringify(obj))
```
to be the slowest way to deep clone an object (it is slower than [jQuery.extend](https://api.jquery.com/jQuery.extend/) with `deep` flag set true by 10-20%).
jQuery.extend is pretty fast when the `deep` flag is set to `false` (shallow clone). It is a good option, because it includes some extra logic for type validation and doesn't copy over undefined properties, etc., but this will also slow you down a little.
If you know the structure of the objects you are trying to clone or can avoid deep nested arrays you can write a simple `for (var i in obj)` loop to clone your object while checking hasOwnProperty and it will be much much faster than jQuery.
Lastly if you are attempting to clone a known object structure in a hot loop you can get MUCH MUCH MORE PERFORMANCE by simply in-lining the clone procedure and manually constructing the object.
JavaScript trace engines suck at optimizing `for..in` loops and checking hasOwnProperty will slow you down as well. Manual clone when speed is an absolute must.
```
var clonedObject = {
knownProp: obj.knownProp,
..
}
```
Beware using the `JSON.parse(JSON.stringify(obj))` method on `Date` objects - `JSON.stringify(new Date())` returns a string representation of the date in ISO format, which `JSON.parse()` **doesn't** convert back to a `Date` object. [See this answer for more details](https://stackoverflow.com/questions/11491938/issues-with-date-when-using-json-stringify-and-json-parse/11491993#11491993).
Additionally, please note that, in Chrome 65 at least, native cloning is not the way to go. According to JSPerf, performing native cloning by creating a new function is nearly **800x** slower than using JSON.stringify which is incredibly fast all the way across the board.
**[Update for ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)**
If you are using Javascript ES6 try this native method for cloning or shallow copy.
```
Object.assign({}, obj);
```
|
What is the most efficient way to deep clone an object in JavaScript?
|
[
"",
"javascript",
"object",
"clone",
""
] |
I want to filter a `java.util.Collection` based on a predicate.
|
Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html "What's New in JDK 8")) solves this problem using streams and lambdas in one line of code:
```
List<Person> beerDrinkers = persons.stream()
.filter(p -> p.getAge() > 16).collect(Collectors.toList());
```
Here's a [tutorial](http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/ "Java 8 collections and lambdas").
Use [`Collection#removeIf`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):
```
persons.removeIf(p -> p.getAge() <= 16);
```
---
[lambdaj](https://code.google.com/archive/p/lambdaj/) allows filtering collections without writing loops or inner classes:
```
List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
greaterThan(16)));
```
Can you imagine something more readable?
**Disclaimer:** I am a contributor on lambdaj
|
Assuming that you are using [Java 1.5](http://java.sun.com/j2se/1.5.0/docs/index.html), and that you cannot add [Google Collections](https://code.google.com/p/guava-libraries/), I would do something very similar to what the Google guys did. This is a slight variation on Jon's comments.
First add this interface to your codebase.
```
public interface IPredicate<T> { boolean apply(T type); }
```
Its implementers can answer when a certain predicate is true of a certain type. E.g. If `T` were `User` and `AuthorizedUserPredicate<User>` implements `IPredicate<T>`, then `AuthorizedUserPredicate#apply` returns whether the passed in `User` is authorized.
Then in some utility class, you could say
```
public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
Collection<T> result = new ArrayList<T>();
for (T element: target) {
if (predicate.apply(element)) {
result.add(element);
}
}
return result;
}
```
So, assuming that you have the use of the above might be
```
Predicate<User> isAuthorized = new Predicate<User>() {
public boolean apply(User user) {
// binds a boolean method in User to a reference
return user.isAuthorized();
}
};
// allUsers is a Collection<User>
Collection<User> authorizedUsers = filter(allUsers, isAuthorized);
```
If performance on the linear check is of concern, then I might want to have a domain object that has the target collection. The domain object that has the target collection would have filtering logic for the methods that initialize, add and set the target collection.
UPDATE:
In the utility class (let's say Predicate), I have added a select method with an option for default value when the predicate doesn't return the expected value, and also a static property for params to be used inside the new IPredicate.
```
public class Predicate {
public static Object predicateParams;
public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
Collection<T> result = new ArrayList<T>();
for (T element : target) {
if (predicate.apply(element)) {
result.add(element);
}
}
return result;
}
public static <T> T select(Collection<T> target, IPredicate<T> predicate) {
T result = null;
for (T element : target) {
if (!predicate.apply(element))
continue;
result = element;
break;
}
return result;
}
public static <T> T select(Collection<T> target, IPredicate<T> predicate, T defaultValue) {
T result = defaultValue;
for (T element : target) {
if (!predicate.apply(element))
continue;
result = element;
break;
}
return result;
}
}
```
The following example looks for missing objects between collections:
```
List<MyTypeA> missingObjects = (List<MyTypeA>) Predicate.filter(myCollectionOfA,
new IPredicate<MyTypeA>() {
public boolean apply(MyTypeA objectOfA) {
Predicate.predicateParams = objectOfA.getName();
return Predicate.select(myCollectionB, new IPredicate<MyTypeB>() {
public boolean apply(MyTypeB objectOfB) {
return objectOfB.getName().equals(Predicate.predicateParams.toString());
}
}) == null;
}
});
```
The following example, looks for an instance in a collection, and returns the first element of the collection as default value when the instance is not found:
```
MyType myObject = Predicate.select(collectionOfMyType, new IPredicate<MyType>() {
public boolean apply(MyType objectOfMyType) {
return objectOfMyType.isDefault();
}}, collectionOfMyType.get(0));
```
UPDATE (after Java 8 release):
It's been several years since I (Alan) first posted this answer, and I still cannot believe I am collecting SO points for this answer. At any rate, now that Java 8 has introduced closures to the language, my answer would now be considerably different, and simpler. With Java 8, there is no need for a distinct static utility class. So if you want to find the 1st element that matches your predicate.
```
final UserService userService = ... // perhaps injected IoC
final Optional<UserModel> userOption = userCollection.stream().filter(u -> {
boolean isAuthorized = userService.isAuthorized(u);
return isAuthorized;
}).findFirst();
```
The JDK 8 API for optionals has the ability to `get()`, `isPresent()`, `orElse(defaultUser)`, `orElseGet(userSupplier)` and `orElseThrow(exceptionSupplier)`, as well as other 'monadic' functions such as `map`, `flatMap` and `filter`.
If you want to simply collect all the users which match the predicate, then use the `Collectors` to terminate the stream in the desired collection.
```
final UserService userService = ... // perhaps injected IoC
final List<UserModel> userOption = userCollection.stream().filter(u -> {
boolean isAuthorized = userService.isAuthorized(u);
return isAuthorized;
}).collect(Collectors.toList());
```
See [here](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) for more examples on how Java 8 streams work.
|
How to filter a Java Collection (based on predicate)?
|
[
"",
"java",
"collections",
"filter",
""
] |
What is the best way to handle a big team that has access to a stable but no so pretty code, that is easy to introduce bugs into?
I'm looking for something along the lines of SVN locking the file(s).
|
Write unit tests if you don't have them already. Then start refactoring, and keep doing regression tests upon every commit.
|
Tell them to leave it alone.
It works, what is the benefit of changing it other than prettying it up (and the potential cost is high) so you just need to explain the cost/benefit analysis.
I would hope your developers would be smart enough to understand this and, if not, you can use your source code control system logs, rolled up tightly, to beat them to death:-) .
|
how to handle code that is deemed dangerous to change, but stable?
|
[
"",
"c++",
"svn",
"refactoring",
""
] |
My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."
|
If you write a C++ program, it links dynamically to the C Runtime Library, or CRT for short. This library contains your printf, your malloc, your strtok, etcetera. The library is contained in the file called MSVCR80.DLL. This file is not by default installed on a Windows system, hence the application cannot run.
The solution? Either install the DLL on the target machine through VCREDIST.EXE (the Visual C++ Redistributable Package), or link to the CRT statically (plug the actual code for the used functions straight into your EXE).
Distributing and installing VCREDIST along with a simple application is a pain in the arse, so I went for the second option: static linking. It's really easy: go to your project's properties, unfold C/C++, click Code Generation, and set the Runtime Library to one of the non-DLL options. That's all there is to it.
|
The problem here is a missing DLL dependency, such as the CRT (C Runtime Library). A good tool for diagnosing this sort of problem is Dependency Walker (depends.exe), which you can find here:
<http://www.dependencywalker.com/>
You would run this program on the computer that generates the error message you posted, and use it to open the exe that's generating this error. Dependency Walker will quickly and graphically indicate any DLLs that are required but not available on the machine.
|
Visual C++/Studio: Application configuration incorrect?
|
[
"",
"c++",
"c",
"visual-studio",
"visual-c++",
""
] |
I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way?
For example, the format could be described as:
```
<Field1(8)><Field2(16)><Field3(12)>
```
And an example file with two records could look like:
```
SomeData0000000000123456SomeMoreData
Data2 0000000000555555MoreData
```
I just want to make sure I'm not overlooking a more elegant way than Substring().
---
**Update:** I ultimately went with a regex like Killersponge suggested:
```
private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);
const string REGEX_LOT = "^(?<Field1>.{6})" +
"(?<Field2>.{16})" +
"(?<Field3>.{12})";
```
I then use the following to access the fields:
```
Match match = reLot.Match(record);
string field1 = match.Groups["Field1"].Value;
```
|
Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :)
You *could* use a regex to match a whole record at a time and capture the fields, but I think that would be overkill.
|
Use [FileHelpers](http://www.filehelpers.net/).
Example:
```
[FixedLengthRecord()]
public class MyData
{
[FieldFixedLength(8)]
public string someData;
[FieldFixedLength(16)]
public int SomeNumber;
[FieldFixedLength(12)]
[FieldTrim(TrimMode.Right)]
public string someMoreData;
}
```
Then, it's as simple as this:
```
var engine = new FileHelperEngine<MyData>();
// To Read Use:
var res = engine.ReadFile("FileIn.txt");
// To Write Use:
engine.WriteFile("FileOut.txt", res);
```
|
Read fixed width record from text file
|
[
"",
"c#",
".net",
"parsing",
"fixed-width",
""
] |
I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:
```
a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy
```
I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text.
For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.?
Do you have data showing the pixel width of each character? Or a program to generate it?
I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.
|
This would not only be impossible to do server-side, it would also not make sense. You don't what browser your client will be using, and you don't know what font settings on the client side will override whatever styling information you assign to a piece of HTML. You might think that you're using absolute positioning pixels in your style properties, but the client could simply be ignoring those or using some plugin to zoom everything because the client uses a high-dpi screen.
Using fixed widths is generally a bad idea.
|
How about overflow: scroll?
|
Rendered pIxel width data for each character in a browser's font
|
[
"",
"javascript",
"jquery",
"html",
"css",
"font-size",
""
] |
Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a `SetFont()` call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and wxPython In Action book don't discuss this.
Is there a way to easily apply the same `SetFont()` method to all these text objects without making separate calls each time?
|
You can do this by calling SetFont on the parent window (Frame, Dialog, etc) before adding any widgets. The child widgets will inherit the font.
|
Maybe try subclassing the text object and in your class `__init__` method just call SetFont()?
Or, do something like:
```
def f(C):
x = C()
x.SetFont(font) # where font is defined somewhere else
return x
```
and then just decorate every text object you create with with it:
```
text = f(wx.StaticText)
```
(of course, if `StaticText` constructor requires some parameters, it will require changing the first lines in `f` function definition).
|
Applying a common font scheme to multiple objects in wxPython
|
[
"",
"python",
"fonts",
"wxpython",
""
] |
I saw this quote on the question: [What is a good functional language on which to build a web service?](https://stackoverflow.com/questions/105710)
> Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM).
Is this true? If so, what is it about the JVM that creates this fundamental limitation?
|
This post: [Recursion or Iteration?](https://stackoverflow.com/questions/72209/recursion-or-loop#72522) might help.
In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see [John Rose's informal proposal](https://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm)).
There is also more discussion in [Sun bug #4726340](https://bugs.java.com/bugdatabase/view_bug?bug_id=4726340), where the evaluation (from 2002) ends:
> I believe this could be done nonetheless, but it is not a small task.
Currently, there is some work going on in the [Da Vinci Machine](http://openjdk.java.net/projects/mlvm/subprojects.html) project. The tail call subproject's status is listed as "proto 80%"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.
|
The fundamental limitation is simply that the JVM does not provide tail calls in its byte code and, consequently, there is no direct way for a language built upon the JVM to provide tail calls itself. There are workarounds that can achieve a similar effect (e.g. trampolining) but they come at the grave cost of awful performance and obfuscating the generated intermediate code which makes a debugger useless.
So the JVM cannot support any production-quality functional programming languages until Sun implement tail calls in the JVM itself. They have been discussing it for years but I doubt they will ever implement tail calls: it will be very difficult because they have prematurely optimized their VM before implementing such basic functionality, and Sun's effort is strongly focused on dynamic languages rather than functional languages.
Hence there is a very strong argument that Scala is not a real functional programming language: these languages have regarded tail calls as an essential feature since Scheme was first introduced over 30 years ago.
|
Does the JVM prevent tail call optimizations?
|
[
"",
"java",
"jvm",
"scala",
"tail-recursion",
""
] |
Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...
Does multiple inheritance slow down a class?
|
Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.
In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.
Of course this is all implementation defined.
Edit: As noted elsewhere, in some multiple inheritance scenarios, an adjustment to the 'this' pointer is required before making the call. Raymond Chen describes [how this works](http://blogs.msdn.com/oldnewthing/archive/2004/02/06/68695.aspx) for COM objects. Basically, calling a virtual function on an object that inherits from multiple bases can require an extra subtraction and a jmp instruction on top of the extra pointer lookup required for a virtual call.
|
[Deep inheritance hierarchies] greatly increases the maintenance burden by adding unnecessary complexity, forcing users to learn the interfaces of many classes even when all they want to do is use a specific derived class. It can also have an impact on memory use and program performance by adding unnecessary vtables and indirection to classes that do not really need them. If you find yourself frequently creating deep inheritance hierarchies, you should review your design style to see if you've picked up this bad habit. **Deep hierarchies are rarely needed and almost never good.** And if you don't believe that but think that "OO just isn't OO without lots of inheritance," then a good counter-example to consider is the [C++] standard library itself. -- [Herb Sutter](https://rads.stackoverflow.com/amzn/click/com/0201615622)
|
Does several levels of base classes slow down a class/struct in c++?
|
[
"",
"c++",
"oop",
""
] |
*UPDATE: Focus your answers on hardware solutions please.*
What hardware/tools/add-in are you using to improve ASP.NET compilation and first execution speed? We are looking at solid state hard drives to speed things up, but the prices are really high right now.
I have two 7200rpm harddrives in RAID 0 right now and I'm not satisfied with the performance anymore.
So my main question is what is the best cost effective way right now to improve ASP.NET compilation speed and overall development performance when you do a lot of debugging?
Scott Gu has a pretty good blog post about this, anyone has anything else to suggest?
<http://weblogs.asp.net/scottgu/archive/2007/11/01/tip-trick-hard-drive-speed-and-visual-studio-performance.aspx>
|
One of the important things to do is keeping projects of not-so-often changed assemblies unloaded. When a change occurs, load it, compile and unload again. It makes huge differences in large solutions.
|
First make sure your that you are using [Web Application Projects](http://msdn.microsoft.com/en-us/asp.net/aa336618.aspx) (WAP). In our experience, compared to Website Projects, WAP compiles roughly 10x faster.
Then, consider migrating all the logic (including complex UI components) into separate library projects. The C# compiler way faster than the ASP.NET compiler (at least for VS2005).
|
What is the best way to improve ASP.NET/C# compilation speed?
|
[
"",
"c#",
".net",
"asp.net",
""
] |
I work on a large C# application (approximately 450,000 lines of code), we constantly have problems with desktop heap and GDI handle leaks. WPF solves these issues, but I don't know what is the best way to upgrade (I expect this is going to take a long time). The application has only a few forms but these can contain many different sets of user-controls which are determined programatically.
This is an internal company app so our release cycles are very short (typically 3 week release cycle).
Is there some gradual upgrade path or do we have to take the hit in one massive effort?
|
You can start by creating a WPF host.
Then you can use the <WindowsFormHost/> control to host your current application. Then, I suggest creating a library of your new controls in WPF. One at a time, you can create the controls (I suggest making them custom controls, not usercontrols). Within the style for each control, you can start with using the <ElementHost/> control to include the "old" windows forms control. Then you can take your time to refactor and recreate each control as complete WPF.
I think it will still take an initial effort to create your control wrappers and design a WPF host for the application. I am not sure the size of the application and or the complexity of the user controls, so I'm not sure how much effort that would be for you. Relatively speaking, it is significantly less effort and much faster to get you application up and running in WPF this way.
I wouldn't just do that and forget about it though, as you may run into issues with controls overlaying each other (Windows forms does not play well with WPF, especially with transparencies and other visuals)
Please update us on the status of this project, or provide more technical information if you would like more specific guidance. Thanks :)
|
Do you use a lot of User controls for the pieces? WPF can host winform controls, so you could piecewise bring in parts into the main form.
|
What is the easiest way to upgrade a large C# winforms app to WPF
|
[
"",
"c#",
".net",
"wpf",
"upgrade",
""
] |
I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort.
For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that you shouldn't have to worry about such things when you very definitely do.
One particular problem I find is that I have to explicitly dispose and cleanup everything in code. If I don't, then the memory profilers don't really help because there is so much chaff floating about you can't find a leak within all the data they're trying to show you. I wonder if I've got the wrong idea, or if the tool I've got isn't the best.
What kind of strategies and tools are useful for tackling memory leaks in .NET?
|
I use Scitech's [MemProfiler](http://memprofiler.com/) when I suspect a memory leak.
So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion.
The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen.
|
Just for the forgetting-to-dispose problem, try [the solution described in this blog post](http://www.interact-sw.co.uk/iangblog/2004/03/23/locking). Here's the essence:
```
public void Dispose ()
{
// Dispose logic here ...
// It's a bad error if someone forgets to call Dispose,
// so in Debug builds, we put a finalizer in to detect
// the error. If Dispose is called, we suppress the
// finalizer.
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#if DEBUG
~TimedLock()
{
// If this finalizer runs, someone somewhere failed to
// call Dispose, which means we've failed to leave
// a monitor!
System.Diagnostics.Debug.Fail("Undisposed lock");
}
#endif
```
|
What strategies and tools are useful for finding memory leaks in .NET?
|
[
"",
"c#",
".net",
"memory-management",
"memory-leaks",
""
] |
Let's say I have code like this:
```
$dbh = new PDO("blahblah");
$stmt = $dbh->prepare('SELECT * FROM users where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
```
The PDO documentation says:
> The parameters to prepared statements don't need to be quoted; the driver handles it for you.
**Is that truly all I need to do to avoid SQL injections? Is it really that easy?**
You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.
|
The short answer is **YES**, PDO prepares are secure enough if used properly.
---
I'm adapting [this answer](https://stackoverflow.com/a/12118602/338665) to talk about PDO...
The long answer isn't so easy. It's based off an attack [demonstrated here](http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string).
# The Attack
So, let's start off by showing the attack...
```
$pdo->query('SET NAMES gbk');
$var = "\xbf\x27 OR 1=1 /*";
$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute(array($var));
```
In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:
1. **Selecting a Character Set**
```
$pdo->query('SET NAMES gbk');
```
For this attack to work, we need the encoding that the server's expecting on the connection both to encode `'` as in ASCII i.e. `0x27` *and* to have some character whose final byte is an ASCII `\` i.e. `0x5c`. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: `big5`, `cp932`, `gb2312`, `gbk` and `sjis`. We'll select `gbk` here.
Now, it's very important to note the use of `SET NAMES` here. This sets the character set **ON THE SERVER**. There is another way of doing it, but we'll get there soon enough.
2. **The Payload**
The payload we're going to use for this injection starts with the byte sequence `0xbf27`. In `gbk`, that's an invalid multibyte character; in `latin1`, it's the string `¿'`. Note that in `latin1` **and** `gbk`, `0x27` on its own is a literal `'` character.
We have chosen this payload because, if we called `addslashes()` on it, we'd insert an ASCII `\` i.e. `0x5c`, before the `'` character. So we'd wind up with `0xbf5c27`, which in `gbk` is a two character sequence: `0xbf5c` followed by `0x27`. Or in other words, a *valid* character followed by an unescaped `'`. But we're not using `addslashes()`. So on to the next step...
3. **$stmt->execute()**
The important thing to realize here is that PDO by default does **NOT** do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling `mysql_real_escape_string()` (the MySQL C API function) on each bound string value.
The C API call to `mysql_real_escape_string()` differs from `addslashes()` in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using `latin1` for the connection, because we never told it otherwise. We did tell the *server* we're using `gbk`, but the *client* still thinks it's `latin1`.
Therefore the call to `mysql_real_escape_string()` inserts the backslash, and we have a free hanging `'` character in our "escaped" content! In fact, if we were to look at `$var` in the `gbk` character set, we'd see:
```
縗' OR 1=1 /*
```
Which is exactly what the attack requires.
4. **The Query**
This part is just a formality, but here's the rendered query:
```
SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1
```
Congratulations, you just successfully attacked a program using PDO Prepared Statements...
# The Simple Fix
Now, it's worth noting that you can prevent this by disabling emulated prepared statements:
```
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
```
This will *usually* result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently [fallback](https://github.com/php/php-src/blob/master/ext/pdo_mysql/mysql_driver.c#L210) to emulating statements that MySQL can't prepare natively: those that it can are [listed](http://dev.mysql.com/doc/en/sql-syntax-prepared-statements.html) in the manual, but beware to select the appropriate server version).
# The Correct Fix
The problem here is that we used `SET NAMES` instead of C API's `mysql_set_charset()`. Otherwise, the attack would not succeed. But the worst part is that PDO didn't expose the C API for `mysql_set_charset()` until 5.3.6, so in prior versions it **cannot** prevent this attack for every possible command!
It's now exposed as a [DSN parameter](http://www.php.net/manual/en/ref.pdo-mysql.connection.php), which should be used **instead of** `SET NAMES`...
This is provided we are using a MySQL release since 2006. If you're using an earlier MySQL release, then a [bug](http://bugs.mysql.com/bug.php?id=8378) in `mysql_real_escape_string()` meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes *even if the client had been correctly informed of the connection encoding* and so this attack would still succeed. The bug was fixed in MySQL [4.1.20](http://dev.mysql.com/doc/refman/4.1/en/news-4-1-20.html), [5.0.22](http://dev.mysql.com/doc/relnotes/mysql/5.0/en/news-5-0-22.html) and [5.1.11](http://dev.mysql.com/doc/relnotes/mysql/5.1/en/news-5-1-11.html).
# The Saving Grace
As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. [`utf8mb4`](http://dev.mysql.com/doc/en/charset-unicode-utf8mb4.html) is *not vulnerable* and yet can support *every* Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is [`utf8`](http://dev.mysql.com/doc/en/charset-unicode-utf8.html), which is also *not vulnerable* and can support the whole of the Unicode [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane).
Alternatively, you can enable the [`NO_BACKSLASH_ESCAPES`](http://dev.mysql.com/doc/en/sql-mode.html#sqlmode_no_backslash_escapes) SQL mode, which (amongst other things) alters the operation of `mysql_real_escape_string()`. With this mode enabled, `0x27` will be replaced with `0x2727` rather than `0x5c27` and thus the escaping process *cannot* create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. `0xbf27` is still `0xbf27` etc.)—so the server will still reject the string as invalid. However, see [@eggyal's answer](https://stackoverflow.com/a/23277864/623041) for a different vulnerability that can arise from using this SQL mode (albeit not with PDO).
# Safe Examples
The following examples are safe:
```
mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
```
Because the server's expecting `utf8`...
```
mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
```
Because we've properly set the character set so the client and the server match.
```
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
```
Because we've turned off emulated prepared statements.
```
$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));
```
Because we've set the character set properly.
```
$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
```
Because MySQLi does true prepared statements all the time.
# Wrapping Up
If you:
* Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) **AND** PDO's DSN charset parameter (in PHP ≥ 5.3.6)
**OR**
* Don't use a vulnerable character set for connection encoding (you only use `utf8` / `latin1` / `ascii` / etc)
**OR**
* Enable `NO_BACKSLASH_ESCAPES` SQL mode
You're 100% safe.
Otherwise, you're vulnerable **even though you're using PDO Prepared Statements...**
# Addendum
I've been slowly working on a patch to change the default to not emulate prepares for a future version of PHP. The problem that I'm running into is that a LOT of tests break when I do that. One problem is that emulated prepares will only throw syntax errors on execute, but true prepares will throw errors on prepare. So that can cause issues (and is part of the reason tests are borking).
|
Prepared statements / parameterized queries are sufficient to prevent SQL injections, but only when used all the time, for the every query in the application.
If you use un-checked dynamic SQL anywhere else in an application it is still vulnerable to *2nd order* injection.
2nd order injection means data has been cycled through the database once before being included in a query, and is much harder to pull off. AFAIK, you almost never see real engineered 2nd order attacks, as it is usually easier for attackers to social-engineer their way in, but you sometimes have 2nd order bugs crop up because of extra benign `'` characters or similar.
You can accomplish a 2nd order injection attack when you can cause a value to be stored in a database that is later used as a literal in a query. As an example, let's say you enter the following information as your new username when creating an account on a web site (assuming MySQL DB for this question):
```
' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '
```
If there are no other restrictions on the username, a prepared statement would still make sure that the above embedded query doesn't execute at the time of insert, and store the value correctly in the database. However, imagine that later the application retrieves your username from the database, and uses string concatenation to include that value a new query. You might get to see someone else's password. Since the first few names in users table tend to be admins, you may have also just given away the farm. (Also note: this is one more reason not to store passwords in plain text!)
We see, then, that if prepared statements are only used for a single query, but neglected for some other queries, they are **not** sufficient to protect against sql injection attacks throughout an entire application, because they lack a mechanism to enforce all access to a database within an application uses safe code. However, used as part of good application design — which may include practices such as code review or static analysis, or use of an ORM, data layer, or service layer that limits dynamic sql — ***prepared statements are the primary tool for solving the Sql Injection problem.*** If you follow good application design principles, such that your data access is separated from the rest of your program, it becomes easy to enforce or audit that every query correctly uses parameterization. In this case, sql injection (both first and second order) is completely prevented.
---
\*It turns out that MySql/PHP were (long, long time ago) just dumb about handling parameters when wide characters are involved, and there was a *rare* case outlined in the [other highly-voted answer here](https://stackoverflow.com/a/12202218/3043) that can allow injection to slip through a parameterized query.
|
Are PDO prepared statements sufficient to prevent SQL injection?
|
[
"",
"php",
"security",
"pdo",
"sql-injection",
""
] |
Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users.
|
You could try [glib's key-value-file-parser](http://library.gnome.org/devel/glib/unstable/glib-Key-value-file-parser.html)
|
I would recommend '[libconfig](http://www.hyperrealm.com/libconfig/)'.
|
Linux configuration file libraries
|
[
"",
"c++",
"c",
"linux",
"configuration",
"file",
""
] |
I'd like to get at least one JRE/JDK level on my Windows machine where I have the JRE/JDK source that matches the exact level of the JRE/JDK. My purpose is to be able to go into the system classes while debugging. Any suggestions about how to do this? Thanks in advance.
|
Most of the useful source will be in the src.zip file in your JDK.
You can get source up to jdk 6u3 from [jdk6.dev.java.net](https://jdk6.dev.java.net/). On Linux you can get OpenJDK source and packages from [openjdk.java.net](http://openjdk.java.net/).
|
I had this problem for a long time; the source-download site must just not have been maintained for a while there.
It seems fixed now, though:
<http://download.java.net/jdk6/6u10/archive/>
(Has links for all the JDK 6 source downloads, not just 6u10.)
|
How to get JRE/JDK with matching source?
|
[
"",
"java",
""
] |
I have a Windows Form app written in C#. Its job is to send messages to a list of users. While those messages are being sent, I'd like to display status of the operation for each user. What I am doing (for each user) is creating a Label control and adding it to Panel. This works without a problem for a small set of users. When I increase the size to 1000 or more, the Visual Studio Debugger displays the following message:
> *A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in
> System.Windows.Forms.dll A first chance exception of type
> 'System.Reflection.TargetInvocationException' occurred in
> mscorlib.dll*
And then the application hangs. Any thoughts on what I'm doing wrong and how I can fix this?
|
Given the size, I would consider displaying your status in a RichTextBox.
What is happening is that you are generating too many handles and the Framework can't handle them all.
|
Use DataGridView instead
|
Trouble when adding a lot of Controls to a .NET Windows Form (C#)
|
[
"",
"c#",
"winforms",
""
] |
Here's the very dumb way:
```
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
```
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough.
I've an generator that generates factor in this way:
(factor1, multiplicity1)
(factor2, multiplicity2)
(factor3, multiplicity3)
and so on...
i.e. the output of
```
for i in factorGenerator(100):
print i
```
is:
```
(2, 2)
(5, 2)
```
I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make
```
for i in divisorGen(100):
print i
```
output this:
```
1
2
4
5
10
20
25
50
100
```
---
**UPDATE:** Many thanks to Greg Hewgill and his "smart way" :)
Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D
**UPDATE 2:** Stop saying this is a duplicate of [this](https://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number) post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.
|
Given your `factorGenerator` function, here is a `divisorGen` that should work:
```
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
if i >= nfactors:
return
```
The overall efficiency of this algorithm will depend entirely on the efficiency of the `factorGenerator`.
|
To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do `n / i`, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.
Python code:
```
import math
def divisorGenerator(n):
large_divisors = []
for i in xrange(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
print list(divisorGenerator(100))
```
Which should output a list like:
```
[1, 2, 4, 5, 10, 20, 25, 50, 100]
```
|
What is the best way to get all the divisors of a number?
|
[
"",
"python",
"algorithm",
"math",
""
] |
I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:
1. No directories. JUST the file name.
2. File name needs to be all lowercase.
3. Whitespaces need to be replaced with underscores.
Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).
|
And a simple combination of RegExp and other javascript is what I would recommend:
```
var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT";
a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1");
a = a.replace(/\s/g,"_");
a = a.toLowerCase();
alert(a);
```
|
If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at <http://regexlib.com/>.
Edit to say: [Here's one that might work for you](http://regexlib.com/REDetails.aspx?regexp_id=1934):
```
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
```
|
What's the (JavaScript) Regular Expression I should use to ensure a string is a valid file name?
|
[
"",
"javascript",
"regex",
"filenames",
""
] |
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.
[Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways:
1. Use threads
2. Use wxYield
3. Chunk the work and do it in the IDLE event handler
Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
|
Threads. They're what I always go for because you can do it in every framework you need.
And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.
|
Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run.
Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have.
Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!
|
Keeping GUIs responsive during long-running tasks
|
[
"",
"python",
"user-interface",
"wxpython",
""
] |
I am looking to use a PHP library for uploading pictures to a web server so that I can use something that has been tested and hopefully not have to design one myself. Does anyone know of such a library?
Edit: I am aware that file uploads are built into PHP, I am looking for a library that may make the process simpler and safer.
|
I personally use [HTTP\_Upload](http://pear.php.net/package/HTTP_Upload) from PEAR. It works pretty well for our purposes (uplaoding media files into a development system and uploading arbitrary files for an educational system)
|
The cunningly name [upload class](http://www.verot.net/php_class_upload.htm) is very good and has a very responsive and supportive developer. Apart from uploading, it also has built-in support for lots of common image functions.
|
What is a good PHP library to handle file uploads?
|
[
"",
"php",
"file-upload",
""
] |
I would like to save data in cookies (user name, email address, etc...) but I don't the user to easily read it or modify it. I need to be able able to read the data back. How can I do that with php 5.2+?
It would be used for "welcome back bob" kind of feature. It is not a replacement for persistence or session storage.
|
We use mcrypt in our projects to achieve encryption. Below is a code sample based on content found on the internet:
```
<?php
class MyProjCrypt {
private $td;
private $iv;
private $ks;
private $salt;
private $encStr;
private $decStr;
/**
* The constructor initializes the cryptography library
* @param $salt string The encryption key
* @return void
*/
function __construct($salt) {
$this->td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); // algorithm
$this->ks = mcrypt_enc_get_key_size($this->td); // key size needed for the algorithm
$this->salt = substr(md5($salt), 0, $this->ks);
}
/**
* Generates a hex string of $src
* @param $src string String to be encrypted
* @return void
*/
function encrypt($src) {
srand(( double) microtime() * 1000000); //for sake of MCRYPT_RAND
$this->iv = mcrypt_create_iv($this->ks, MCRYPT_RAND);
mcrypt_generic_init($this->td, $this->salt, $this->iv);
$tmpStr = mcrypt_generic($this->td, $src);
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
//convert the encrypted binary string to hex
//$this->iv is needed to decrypt the string later. It has a fixed length and can easily
//be seperated out from the encrypted String
$this->encStr = bin2hex($this->iv.$tmpStr);
}
/**
* Decrypts a hex string
* @param $src string String to be decrypted
* @return void
*/
function decrypt($src) {
//convert the hex string to binary
$corrected = preg_replace("[^0-9a-fA-F]", "", $src);
$binenc = pack("H".strlen($corrected), $corrected);
//retrieve the iv from the encrypted string
$this->iv = substr($binenc, 0, $this->ks);
//retrieve the encrypted string alone(minus iv)
$binstr = substr($binenc, $this->ks);
/* Initialize encryption module for decryption */
mcrypt_generic_init($this->td, $this->salt, $this->iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($this->td, $binstr);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
$this->decStr = trim($decrypted);
}
}
```
|
I suggest you not only encrypt but also sign the data. If you don't sign the data, you won't be able to tell reliably whether the user modified the data. Also, to avoid replay you may want to add some timestamp/validity period information into the data.
|
How to save encrypted data in cookie (using php)?
|
[
"",
"php",
"security",
"encryption",
"cookies",
""
] |
I miss it so much (used it a lot in C#). can you do it in C++?
|
Yes, you can. See [here](http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx).
```
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
```
|
The Visual assist add-in for VC supports regions for c++. Don't know if 2008 has build in regions for C++ though.
|
Can you create collapsible #Region like scopes in C++ within VS 2008?
|
[
"",
"c++",
"visual-studio",
"visual-studio-2008",
"pragma",
"readability",
""
] |
What's the best way to get a string containing a folder name that I can be certain does **not** exist? That is, if I call `DirectoryInfo.Exists` for the given path, it should return false.
EDIT: The reason behind it is I am writing a test for an error checker, the error checker tests whether the path exists, so I wondered aloud on the best way to get a path that doesn't exist.
|
Name it after a GUID - just take out the illegal characters.
|
There isn't really any way to do precisely what you way you want to do. If you think about it, you see that even after the call to `DirectoryInfo.Exists` has returned false, some other program could have gone ahead and created the directory - this is a race condition.
The normal method to handle this is to create a new temporary directory - if the creation succeeds, then you know it hadn't existed before you created it.
|
What's the best way to get the name of a folder that doesn't exist?
|
[
"",
"c#",
"directory",
""
] |
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.
I don't know if it depends on the technologies used, but I'll use Tomcat 5.5
---
I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)
|
I think what you're looking for here is request, session or application data.
In a servlet you can add an object as an attribute to the request object, session object or servlet context object:
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);
}
```
If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:
```
request.getAttribute("sharedId");
```
If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:
```
request.getSession().getAttribute("sharedId");
```
Until the session expires based on inactivity from the user.
Is reset by you:
```
request.getSession().invalidate();
```
Or one servlet removes it from scope:
```
request.getSession().removeAttribute("sharedId");
```
If you put it in the servlet context it will be available while the application is running:
```
this.getServletConfig().getServletContext().getAttribute("sharedId");
```
Until you remove it:
```
this.getServletConfig().getServletContext().removeAttribute("sharedId");
```
|
Put it in one of the 3 different scopes.
request - lasts life of request
session - lasts life of user's session
application - lasts until applciation is shut down
You can access all of these scopes via the HttpServletRequest variable that is passed in to the methods that extend from the [HttpServlet class](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html)
|
How can I share a variable or object between two or more Servlets?
|
[
"",
"java",
"web-applications",
"servlets",
""
] |
I've been searching around, and I haven't found how I would do this from C#.
I was wanting to make it so I could tell Google Chrome to go **Forward**, **Back**, **Open New Tab**, **Close Tab**, **Open New Window**, and **Close Window** from my C# application.
I did something similar with WinAmp using
```
[DllImport("user32", EntryPoint = "SendMessageA")]
private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);
```
and a a few others. But I don't know what message to send or how to find what window to pass it to, or anything.
So could someone show me how I would send those 6 commands to Chrome from C#? thanks
EDIT:
Ok, I'm getting voted down, so maybe I wasn't clear enough, or people are assuming I didn't try to figure this out on my own.
First off, I'm not very good with the whole DllImport stuff. I'm still learning how it all works.
I found how to do the same idea in winamp a few years ago, and I was looking at my code. I made it so I could skip a song, go back, play, pause, and stop winamp from my C# code. I started by importing:
```
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow([MarshalAs(UnmanagedType.LPTStr)] string lpClassName, [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SendMessageA(IntPtr hwnd, int wMsg, int wParam, uint lParam);
[DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetWindowText(IntPtr hwnd, string lpString, int cch);
[DllImport("user32", EntryPoint = "FindWindowExA")]
private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);
[DllImport("user32", EntryPoint = "SendMessageA")]
private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);
```
Then the code I found to use this used these constants for the messages I send.
```
const int WM_COMMAND = 0x111;
const int WA_NOTHING = 0;
const int WA_PREVTRACK = 40044;
const int WA_PLAY = 40045;
const int WA_PAUSE = 40046;
const int WA_STOP = 40047;
const int WA_NEXTTRACK = 40048;
const int WA_VOLUMEUP = 40058;
const int WA_VOLUMEDOWN = 40059;
const int WINAMP_FFWD5S = 40060;
const int WINAMP_REW5S = 40061;
```
I would get the *hwnd* (the program to send the message to) by:
```
IntPtr hwnd = FindWindow(m_windowName, null);
```
then I would send a message to that program:
```
SendMessageA(hwnd, WM_COMMAND, WA_STOP, WA_NOTHING);
```
I assume that I would do something very similar to this for Google Chrome. but I don't know what some of those values should be, and I googled around trying to find the answer, but I couldn't, which is why I asked here. So my question is how do I get the values for:
**m\_windowName** and **WM\_COMMAND**
and then, the values for the different commands, **forward**, **back**, **new tab**, **close tab**, **new window**, **close window**?
|
Start your research at <http://dev.chromium.org/developers>
---
**EDIT**: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window messages.
You're looking at an implementation detail on how you remote controlled Winamp. Sending messages is just one way to do it and it's the way the Winamp developers chose. Those messages you're using are user defined messages that have a specific meaning *only* to Winamp.
What you have to do in the first step is to find out *if* Chromium supports some kind of remote controlling and what those mechanisms are.
|
You can get the window name easily using Visual Studio's Spy++ and pressing CTRL+F, then finding chrome. I tried it and got
"Chrome\_VistaFrame" for the out window. The actual window with the webpage in is "Chrome\_RenderWidgetHostHWND".
As far as WM\_COMMAND goes - you'll need to experiment. You'll obviously want to send button clicks (WM\_MOUSEDOWN of the top off my head). As the back,forward buttons aren't their own windows, you'll need to figure out how to do this with simulating a mouse click at a certain x,y position so chrome knows what you're doing. Or you could send the keyboard shortcut equivalent for back/forward and so on.
An example I wrote a while ago does this with trillian and winamp: [sending messages to windows via c# and winapi](http://www.sloppycode.net/code-snippets/cs/sendmessage.aspx)
There's also tools out there to macro out this kind of thing already, using a scripting language - autoit is one I've used: [autoit.com](http://www.autoitscript.com/)
|
C# - Sending messages to Google Chrome from C# application
|
[
"",
"c#",
"google-chrome",
"message",
""
] |
Consider a *hypothetical* method of an object that does stuff for you:
```
public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
}
}
```
How can one wait for a BackgroundWorker to be done?
---
In the past people have tried:
```
while (_worker.IsBusy)
{
Sleep(100);
}
```
But [this deadlocks](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&SiteID=1), because `IsBusy` is not cleared until after the `RunWorkerCompleted` event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)
Others have add suggested kludging it into:
```
while (_worker.IsBusy)
{
Application.DoEvents();
}
```
The problem with that is that is `Application.DoEvents()` causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).
I would hope to use some solution involving Event synchronization objects, where the code **waits** for an event - that the worker's `RunWorkerCompleted` event handlers sets. Something like:
```
Event _workerDoneEvent = new WaitHandle();
public void CancelDoingStuff()
{
_worker.CancelAsync();
_workerDoneEvent.WaitOne();
}
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
_workerDoneEvent.SetEvent();
}
```
But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.
So how can you wait for an BackgroundWorker to finish?
---
**Update**
People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyWork;
worker.RunWorkerAsync();
WaitForWorkerToFinish(worker);
```
That is *not* it, that is *not* what I'm doing, and that is *not* what is being asked here. If that were the case, there would be no point in using a background worker.
|
If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):
```
private BackgroundWorker worker = new BackgroundWorker();
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
}
public void Cancel()
{
worker.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(!e.Cancel)
{
// do something
}
_resetEvent.Set(); // signal that worker is done
}
```
|
There is a problem with [this](https://stackoverflow.com/questions/123661/net-how-to-wait-for-a-backgroundworker-to-complete#123791) response. The UI needs to continue to process messages while you are waiting, otherwise it will not repaint, which will be a problem if your background worker takes a long time to respond to the cancel request.
A second flaw is that `_resetEvent.Set()` will never be called if the worker thread throws an exception - leaving the main thread waiting indefinitely - however this flaw could easily be fixed with a try/finally block.
One way to do this is to display a modal dialog which has a timer that repeatedly checks if the background worker has finished work (or finished cancelling in your case). Once the background worker has finished, the modal dialog returns control to your application. The user can't interact with the UI until this happens.
Another method (assuming you have a maximum of one modeless window open) is to set ActiveForm.Enabled = false, then loop on Application,DoEvents until the background worker has finished cancelling, after which you can set ActiveForm.Enabled = true again.
|
How to wait for a BackgroundWorker to cancel?
|
[
"",
"c#",
".net",
"multithreading",
"backgroundworker",
""
] |
At the moment we use [HSQLDB](http://www.hsqldb.org/) as an embedded database, but we search for a database with less memory footprint as the data volume grows.
[Derby / JavaDB](http://developers.sun.com/javadb/) is not an option at the moment because it stores properties globally in the system properties. So we thought of [h2](http://www.h2database.com/html/main.html).
While we used HSQLDB we created a Server-object, set the parameters and started it. This is described [here](http://hsqldb.org/doc/guide/ch04.html#N10BBC) (and given as example in the class org.hsqldb.test.TestBase).
The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.
|
From the download, I see that the file tutorial.html has this
```
import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
```
|
Yes, you can run H2 in embedded mode. You just use the JDBC driver and connect to an embedded url like this (their example):
> This database can be used in embedded
> mode, or in server mode. To use it in
> embedded mode, you need to:
>
> ```
> * Add h2.jar to the classpath
> * Use the JDBC driver class: org.h2.Driver
> * The database URL jdbc:h2:~/test opens the database 'test' in your user home directory
> ```
Example of connecting with JDBC to an embedded H2 database (adapted from <http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcDataSource.html> ):
```
import org.h2.jdbcx.JdbcDataSource;
// ...
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:˜/test");
ds.setUser("sa");
ds.setPassword("sa");
Connection conn = ds.getConnection();
```
If you're looking to use H2 in a purely in-memory / embedded mode, you can do that too. See this link for more:
* <http://www.h2database.com/html/features.html#in_memory_databases>
You just need to use a special URL in normal JDBC code like "jdbc:h2:mem:db1".
|
Embedding the Java h2 database programmatically
|
[
"",
"java",
"database",
"embedding",
"h2",
""
] |
I am trying to read an Http response stream twice via the following:
```
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
RssReader reader = new RssReader(stream);
do
{
element = reader.Read();
if (element is RssChannel)
{
feed.Channels.Add((RssChannel)element);
}
} while (element != null);
StreamReader sr = new StreamReader(stream);
feed._FeedRawData = sr.ReadToEnd();
```
However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).
Basically, I would like to parse the stream for XML and have access to the raw data (in string format).
Any ideas?
|
Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:
```
Stream responseStream = CopyAndClose(resp.GetResponseStream());
// Do something with the stream
responseStream.Position = 0;
// Do something with the stream again
private static Stream CopyAndClose(Stream inputStream)
{
const int readSize = 256;
byte[] buffer = new byte[readSize];
MemoryStream ms = new MemoryStream();
int count = inputStream.Read(buffer, 0, readSize);
while (count > 0)
{
ms.Write(buffer, 0, count);
count = inputStream.Read(buffer, 0, readSize);
}
ms.Position = 0;
inputStream.Close();
return ms;
}
```
|
Copying the stream to a [MemoryStream](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream?view=netframework-4.0) as suggested by [Iain](https://stackoverflow.com/a/147961/2484903) is the right approach. But since
.NET Framework 4 (released 2010) we have [Stream.CopyTo](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copyto?view=netframework-4.0). Example from the docs:
```
// Create the streams.
MemoryStream destination = new MemoryStream();
using (FileStream source = File.Open(@"c:\temp\data.dat",
FileMode.Open))
{
Console.WriteLine("Source length: {0}", source.Length.ToString());
// Copy source to destination.
source.CopyTo(destination);
}
Console.WriteLine("Destination length: {0}", destination.Length.ToString());
```
Afterwards you can read `destination` as many times as you like:
```
// re-set to beginning and convert stream to string
destination.Position = 0;
StreamReader streamReader = new StreamReader(destination);
string text = streamReader.ReadToEnd();
// re-set to beginning and read again
destination.Position = 0;
RssReader cssReader = new RssReader(destination);
```
(I have seen [Endy's comment](https://stackoverflow.com/questions/147941/how-can-i-read-an-http-response-stream-twice-in-c#comment-19788214) but since it is an appropriate, current answer, it should have its own answer entry.)
|
How can I read an Http response stream twice in C#?
|
[
"",
"c#",
"stream",
""
] |
When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them.
How do you keep everything manageable?
|
My advice:
* Read [Installing Python Modules](http://docs.python.org/install/index.html).
* Read [Distributing Python Modules](http://docs.python.org/distutils/index.html).
* Start using easy\_install from [setuptools](http://peak.telecommunity.com/DevCenter/setuptools). Read the documentation for setuptools.
* Always use [virtualenv](http://pypi.python.org/pypi/virtualenv). My site-packages directory contains **setuptools and virtualenv only**.
* Check out Ian Bicking's new project [pyinstall](http://www.openplans.org/projects/topp-engineering/blog/2008/09/24/pyinstall-a-new-hope/).
* Follow everything [Ian Bicking](http://blog.ianbicking.org) is working on. It is always goodness.
* When creating your own packages, use distutils/setuptools. Consider using `paster create` (see <http://pythonpaste.org>) to create your initial directory layout.
|
In addition to PEP8 and easy\_install, you should check out virtualenv. Virtualenv allows you to have multiple different python library trees. At work, we use virtualenv with a bootstrapping environment to quickly set up a development/production environment where we are all in sync w.r.t library versions etc. We generally coordinate library upgrades.
|
How do you organize Python modules?
|
[
"",
"python",
"module",
""
] |
We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu.
When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed that the load on the CPU had spiked dramatically (sometimes reaching 10 and stopping to respond to page requests).
We tried dumping a full minute of Xdebug profiling data from PHP, but looking through it revealed only a few somewhat slow parts, but nothing to explain the huge jump.
We are now pretty sure that nothing in the new version of our website is triggering the problem, but we have no way to be sure. We have rolled back a lot of the changes, but the problem still persists.
When look at processes, we see that single Apache processes use quite a bit of CPU over a longer period of time than strictly necessary. However, when using strace on the affected process, we never see anything but
```
accept(3,
```
and it hangs for a while before receiving a new connection, so we can't actually see what is causing the problem.
The stack is PHP 5, Apache 2 (prefork), MySQL 5.1. Most things run through Memcached. We've tried APC and eAccelerator.
So, what should be our next step? Are there any profiling methods we overlooked/don't know about?
|
The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend the disk (because it was not set up properly for VMWare). This completely killed performance, and Apache and MySQL would occasionally use 100% CPU (for a very short time), and the system would be so slow to update the CPU usage meters that it seemed to be stuck there.
We ended up setting up a new VM (which also gave us the opportunity to thoroughly document everything on the server). On the new VM we allocated plenty of disk space, and moved sessions into memory (using memcached). Our load dropped to 0.2 on off-peak use and around 1 near peak use (on a 2-CPU VM). Moving the sessions into memcached took a lot of disk IO away (we were constantly using about 2MB/s of disk IO, which is very bad).
Conclusion; sometimes you just have to start over... :)
|
Seeing an accept() call from your Apache process isn't at all unusual - that's the webserver waiting for a new request.
First of all, you want to establish what the parameters of the load are. Something like
```
vmstat 1
```
will show you what your system is up to. Look in the 'swap' and 'io' columns. If you see anything other than '0' in the 'si' and 'so' columns, your system is swapping because of a low memory condition. Consider reducing the number of running Apache children, or throwing more RAM in your server.
If RAM isn't an issue, look at the 'cpu' columns. You're interested in the 'us' and 'sy' columns. These show you the percentage of CPU time spent in either user processes or system. A high 'us' number points the finger at Apache or your scripts - or potentially something else on the server.
Running
```
top
```
will show you which processes are the most active.
Have you ruled out your database? The most common cause of unexpectedly high load I've seen on production LAMP stacks come down to database queries. You may have deployed new code with an expensive query in it; or got to the point where there are enough rows in your dataset to cause previously cheap queries to become expensive.
During periods of high load, do
```
echo "show full processlist" | mysql | grep -v Sleep
```
to see if there are either long-running queries, or huge numbers of the same query operating at once. Other mysql tools will help you optimise these.
You may find it useful to configure and use mod\_status for Apache, which will allow you to see what request each Apache child is serving and for how long it has been doing so.
Finally, get some long-term statistical monitoring set up. Something like zabbix is straightforward to configure, and will let you monitor resource usage over time, such that if things get slow, you have historical baselines to compare against, and a better ieda of when problems started.
|
Apache uses excessive CPU
|
[
"",
"php",
"mysql",
"performance",
"apache",
""
] |
For example, I rarely need:
```
using System.Text;
```
but it's always there by default. I assume the application will use more memory if your code contains unnecessary [using directives](http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx). But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
---
*Edit: Note that this question is not about the unrelated concept called a [using statement](http://msdn.microsoft.com/en-us/library/yh598w02.aspx), designed to help one manage resources by ensuring that when an object goes out of scope, its [IDisposable.Dispose](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method is called. See [Uses of "using" in C#](https://stackoverflow.com/questions/75401/uses-of-using-in-c).*
|
It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference.
|
There **are** few reasons for removing unused using(s)/namespaces, besides coding preference:
* removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types)
* can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces.
* will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown)
What removing the unused namespaces **won't** do:
* alter in any way the output of the compiler.
* alter in any way the execution of the compiled program (faster loading, or better performance).
The resulting assembly is the same with or without unused using(s) removed.
|
Why should you remove unnecessary C# using directives?
|
[
"",
"c#",
"assemblies",
"using",
""
] |
My client has a multi-page PDF file. They need it split by page. Does anyone know of a way to do this - preferably in C#.
|
[PDFSharp](http://www.pdfsharp.com/) is an open source library which may be what you're after:
> Key Features
>
> * Creates PDF documents on the fly from any .Net language
> * Easy to understand object model to compose documents
> * One source code for drawing on a PDF page as well as in a window or on the printer
> * Modify, merge, and split existing PDF files
[This sample](http://www.pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=37&Itemid=48) shows how to convert a PDF document with n pages into n documents with one page each.
|
I did this using [ITextSharp](http://itextsharp.sourceforge.net) -- there are commercial options that may have a good API but this is open source and free, and not hard to use.
Check out [this code](http://itextsharp.sourceforge.net/examples/Split.cs), it's one of their code samples -- it's pretty good. It splits a PDF file into two files at the passed-in page number. You can modify it to loop and split page by page.
|
How can I split up a PDF file into pages (preferably C#)
|
[
"",
"c#",
"pdf",
""
] |
I'm a big fan of the Jadclipse plugin and I'd really like to upgrade to Eclipse 3.4 but the plugin currently does not work. Are there any other programs out there that let you use jad to view source of code you navigate to from Eclipse? (Very useful when delving into ambiguous code in stack traces).
|
I'm successfully using JadClipse with Eclipse 3.4
Eclipse 3.4.0.I20080617-2000
JadClipse 3.3.0
It just works!
EDIT:
Actually, see [OlegSOM's answer](https://stackoverflow.com/questions/122110/is-there-a-way-to-get-jadclipse-working-with-eclipse-3-4/224779#224779) below for the additional steps that you might need to remember to take, if like me you forget to read documentation sometimes!
|
Read attentively the documentation ... :
1. The JadClipse plug-in is not activated when I start Eclipse.
You'll need to launch Eclipse with the -clean flag to allow the
environment to detect the plug-in. Subsequent launching of
Eclipse won't require the -clean flag.
**eclipse -clean**
2. The Eclipse Class File Viewer instead of the JadClipse Class File Viewer is
opened. Go to **Window > Preferences... > General > Editors > File Associations**
and make sure that the JadClipse Class File Viewer has the DEFAULT file
association for \*.class files. ( - press Default button !!!)
It really helps :)))
|
Is there a way to get jadclipse working with Eclipse 3.4?
|
[
"",
"java",
"eclipse",
"plugins",
"eclipse-plugin",
"jad",
""
] |
If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks
|
It sounds like you're serializing and storing the individual objects in the array (after much reading between the lines). Use the ObjectOutputStream to store the array itself. If the objects stored in the array are serializable, they'll be stored too. When you deserialize you'll get the entire array back intact.
|
What do you mean by "unknown"? You can get the length of any java array with the length field.
```
int[] myArray = deserializeSomeArray();
int size = myArray.length;
```
|
Java: Serializing unknown Arraysize
|
[
"",
"java",
"serialization",
"objectsize",
""
] |
I am creating an RSS reader as a hobby project, and at the point where the user is adding his own URL's.
I was thinking of two things.
* A plaintext file where each url is a single line
* SQLite where i can have unique ID's and descriptions following the URL
Is the SQLite idea to much of an overhead or is there a better way to do things like this?
|
What about as an [OPML](http://en.wikipedia.org/wiki/Opml) file? It's XML, so if you needed to store more data then the OPML specification supplies, you can always add your own namespace.
Additionally, importing and exporting from other RSS readers is all done via OPML. Often there is library support for it. If you're interested in having users switch then you have to support OPML. Thansk to jamesh for bringing that point up.
|
Why not XML?
If you're dealing with RSS anyway you mayaswell :)
|
Best way to store urls locally
|
[
"",
"c#",
"sqlite",
"plaintext",
""
] |
When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.
I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR.
How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build?
I was thinking along the lines of:
* adding a VERSION file, but with what content?
* storing information in the META-INF file, but under what property with which content?
* copying sources into the result archive
* added svn:properties to all sources with keywords in places the compiler leaves them be
---
I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable.
```
<taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask">
<classpath>
<pathelement location="${dir.lib}/ant/svnant.jar"/>
<pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/>
<pathelement location="${dir.lib}/ant/svnkit.jar"/>
<pathelement location="${dir.lib}/ant/svnjavahl.jar"/>
</classpath>
</taskdef>
```
Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file.
```
<target name="version">
<svn><wcVersion path="${dir.source}"/></svn>
<echo file="${dir.build}/VERSION">${revision.range}</echo>
</target>
```
Refs:
svnrevision: <http://svnbook.red-bean.com/en/1.1/re57.html>
svn info <http://svnbook.red-bean.com/en/1.1/re13.html>
subclipse svn task: <http://subclipse.tigris.org/svnant/svn.html>
svn client: <http://svnkit.com/>
|
Use the *svnversion* command in your Ant script to get the revision number:
```
<exec executable="svnversion" outputproperty="svnversion" failonerror="true">
<env key="path" value="/usr/bin"/>
<arg value="--no-newline" />
</exec>
```
Then use the *${svnversion}* property somewhere in your EAR. We put it in the EAR file name, but you could also put it in a readme or version file inside the EAR, or specify the version in the EAR's *META-INF/manifest.mf*:
```
<!-- myapp-r1234.ear -->
<property name="ear" value="myapp-r${svnrevision}.ear" />
```
|
You'd want to provide the Subversion branch and repository number. As discussed in [How to access the current Subversion build number?](https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number), the `svn info` command will give you this information, which you can then use to build a VERSION file or place in any of the other files that you're building into your \*AR files. If you've nothing else in mind, you could consider using the [XmlProperty Ant task](http://ant.apache.org/manual/Tasks/xmlproperty.html) to extract the relevant information from the output of your
svn info --xml command
|
How best to store Subversion version information in EAR's?
|
[
"",
"java",
"svn",
"ant",
"release",
""
] |
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?
At the moment I am doing:
```
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideInfoHeader");
}
```
but what I want is something generic:
```
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug(this.className() + "::" + this.functionName());
}
```
|
"`__FUNCTION__`" is supported by both MSVC and GCC and should give you the information you need.
|
I see from your example that you are using [Qt](http://qt.nokia.com/). In which case your best bet is to use `Q_FUNC_INFO` found in `<QGlobal>`. Here's the description:
> Expands to a string that describe the
> function the macro resides in. How
> this string looks more specifically is
> compiler dependent. With GNU GCC it is
> typically the function signature,
> while with other compilers it might be
> the line and column number.
|
How to get the function name while in a function for debug strings?
|
[
"",
"c++",
"debugging",
"qt",
""
] |
[Python for Unix and Linux System Administration](http://oreilly.com/catalog/9780596515829/) is aimed at sysadmins.
Any other favorites besides this.
|
Mark Pilgrim's <http://www.diveintopython.net/> is very good and clear.
|
First, you can start off the learn the basics of Python at Python documentation Index. Also of interest there would be the tutorial, library references. For sysadmin, some of the libraries you can use are , to name a few
1. shutil (moving/copying files)
2. os eg
os.walk() -> recursive directories looking for files
os.path.join() -> join file paths
os.getmtime(), os.getatime() -> file timestamp
os.remove(), os.removedirs() -> remove files
os.rename() -> rename files ..
and many more... please see help(os) for more operating system stuffs...
3. sys
4. ftplib, telnetlib --> for file transfer and telnetting...
5. glob() -> file globbing, wildcards
6. re -> regular expression, if you ever need to use it.(but its not necessary)
7. paramiko -> SSH, if you want to use Secure shell
8. socket -> socket library if you need to do networking....
9. most often times as a sysadmin, you will need to read/write files so learn about doing that
10. a) using for loop
```
for line in open("file"):
print line
```
11. b) with a file handle
```
f=open("file")
for line in f:
print line
f.close()
```
12. c) using while loop
```
f=open("file")
while 1:
line=f.readline()
if not line: break
print line
f.close()
```
13. datetime, time -> handle date and time , such as calculating how many days old or differences between 2 dates etc
14. fileinput -> for editing files in place.
15. md5 or hashlib -> calculating hash digest/md5 eg to find duplicate files ...
Of course, there are many more but i leave it to you to explore.
|
Which Python book would you recommend for a Linux Sysadmin?
|
[
"",
"python",
"linux",
"system-administration",
""
] |
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?
So something that would yield this kind of translation table:
```
\r --> \r\n
\n --> \r\n
\n\n --> \r\n\r\n
\n\r --> \r\n
\r\n --> \r\n
\r\n\n --> \r\n\r\n
```
|
I believe this will do what you need:
```
using System.Text.RegularExpressions;
// ...
string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n");
```
I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match "\r\n" and "\n\r" first.
To apply it to an entire stream, just run it on chunks of input. (You could do this with a stream wrapper if you want.)
---
The original perl:
```
$str =~ s/\r\n|\n\r|\n|\r/\r\n/g;
```
The test results:
```
[bash$] ./test.pl
\r -> \r\n
\n -> \r\n
\n\n -> \r\n\r\n
\n\r -> \r\n
\r\n -> \r\n
\r\n\n -> \r\n\r\n
```
---
Update: Now converts \n\r to \r\n, though I wouldn't call that normalization.
|
I'm with Jamie Zawinski on RegEx:
"Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems"
For those of us who prefer readability:
* Step 1
Replace \r\n by \n
Replace \n\r by \n (if you really want this, some posters seem to think not)
Replace \r by \n
* Step 2
Replace \n by Environment.NewLine or \r\n or whatever.
|
Normalize newlines in C#
|
[
"",
"c#",
".net",
""
] |
I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So `/section/document` becomes `/section/document/2008-10-06`
What's the best way to do this?
|
Here's how we do it:
In Struts.xml, have a dynamic result such as:
```
<result name="redirect" type="redirect">${url}</result>
```
In the action:
```
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "redirect";
}
```
You can actually use this same technology to set dynamic values for any variable in your struts.xml using OGNL. We've created all sorts of dynamic results including stuff like RESTful links. Cool stuff.
|
One can also use `annotations` and the Convention plug-in to avoid repetitive configuration in struts.xml:
```
@Result(location="${url}", type="redirect")
```
The ${url} means "use the value of the getUrl method"
|
How to do dynamic URL redirects in Struts 2?
|
[
"",
"java",
"url",
"redirect",
"struts2",
""
] |
OK, first let me state that I have never used this control and this is also my first attempt at using a web service.
My dilemma is as follows. I need to query a database to get back a certain column and use that for my autocomplete. Obviously I don't want the query to run every time a user types another word in the textbox, so my best guess is to run the query once then use that dataset, array, list or whatever to then filter for the autocomplete extender...
I am kinda lost any suggestions??
|
Why not keep track of the query executed by the user in a session variable, then use that to filter any further results?
The trick to preventing the database from overloading I think is really to just limit how frequently the auto updater is allowed to update, something like once per 2 seconds seems reasonable to me.
What I would do is this: Store the current list returned by the query for word A server side and tie that to a session variable. This should be basically the entire list I would think. Then, for each new word typed, so long as the original word A exists, you can filter the session info and spit the filtered results out without having to query again. So basically, only query again when word A changes.
I'm using "session" in a PHP sense, you may be using a different language with different terminology, but the concept should be the same.
|
This question depends upon how transactional your data store is. Obviously if you are looking for US states (a data collection that would not change realistically through the life of the application) then I would either cache a System.Collection.Generic List<> type or if you wanted a DataTable.
You could easily set up a cache of the data you wish to query to be dependent upon an XML file or database so that your extender always queries the data object casted from the cache and the cache object is only updated when the datasource changes.
|
Ajax autocomplete extender populated from SQL
|
[
"",
"sql",
"ajax",
""
] |
I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect `SERVER['argc']`, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.
|
Use the [`php_sapi_name()`](http://php.net/php_sapi_name) function.
```
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
```
Here are some relevant notes from the docs:
> **php\_sapi\_name** — Returns the type of interface between web server and PHP
>
> Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
In PHP >= 4.2.0, there is also a predefined constant, `PHP_SAPI`, that has the same value as `php_sapi_name()`.
|
This will always work. (If the PHP version is 4.2.0 or higher)
```
define('CLI', PHP_SAPI === 'cli');
```
Which makes it easy to use at the top of your scripts:
```
<?php PHP_SAPI === 'cli' or die('not allowed');
```
|
What is the canonical way to determine commandline vs. http execution of a PHP script?
|
[
"",
"php",
"http",
"command-line",
"command-line-interface",
""
] |
This is a question you can read everywhere on the web with various answers:
```
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
```
etc.
However, there is always "the best way".
|
People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet [`pathinfo()`](http://php.net/manual/en/function.pathinfo.php):
```
$ext = pathinfo($filename, PATHINFO_EXTENSION);
```
This is built-in. `pathinfo()` can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non-ASCII characters, you need to set the locale first. For example:
```
setlocale(LC_ALL, 'en_US.UTF-8');
```
Also, note this doesn't take into consideration the file content or [MIME type](https://en.wikipedia.org/wiki/MIME#MIME_header_fields), you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE\_URL.
|
[`pathinfo()`](http://uk.php.net/manual/en/function.pathinfo.php)
```
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
```
|
How can I get a file's extension in PHP?
|
[
"",
"php",
"file-extension",
""
] |
I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone *really* find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE\*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?
```
const char* path = "/dev/disk3";
char b;
// this works
FILE* f= fopen(path, "rb");
int i = fread(&b, 1, 1, f); // returns 1, success!
// this does not work
ifstream cf(path, ios::binary);
cf.read(&b, 1);
bool good = cf.good(); // returns false, failure.
```
|
The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read *1023* bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE\*. However, FILE\* left to its own devices was reading ahead using a nicer, rounder number of bytes.
Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right.
|
Works fine for me, its not a problem inherent to c++ stream file I/O as you seem to think.
Maybe try adding `ios::in` to the openmode flags. According to 27.8.1.6 of the standard, it is required to or with ios::in so this probably won't do anything.
Try checking which bit is actually set - instead of calling good(), try checking bad(), eof(), and fail() individually. This might give a clue as to what the error was.
|
Why can't c++ ifstreams read from devices?
|
[
"",
"c++",
"macos",
"gcc",
"fstream",
""
] |
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:
```
namespace Lib {
class A {
};
A operator+(const A&, const A&);
} // namespace Lib
```
or the global namespace
```
namespace Lib {
class A {
};
} // namespace Lib
Lib::A operator+(const Lib::A&, const Lib::A&);
```
From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?
|
You should define them in the library namespace.
The compiler will find them anyway through argument dependant lookup.
No need to pollute the global namespace.
|
Putting it into the library namespace works because of [Koenig lookup](http://en.wikipedia.org/wiki/Argument_dependent_name_lookup).
|
Namespaces and Operator Overloading in C++
|
[
"",
"c++",
"operator-overloading",
"namespaces",
""
] |
One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:
```
self.__value = 1
def value():
return self.__value
```
Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.
I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?
|
Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '\_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '\_\_value' attribute, the attribute is actually being stored as '`_ContainerThing__value`'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.
This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a *single* leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.
For the record, '`__value`' and '`value`' (and '`_value`') are not the same name. The underscores are part of the name.
|
"I know this seems to go against the general idea of private and public" Not really "against", just different from C++ and Java.
Private -- as implemented in C++ and Java is not a very useful concept. It helps, sometimes, to isolate implementation details. But it is way overused.
Python names beginning with two `__` are special and you should not, as a normal thing, be defining attributes with names like this. Names with `__` are special and part of the implementation. And exposed for your use.
Names beginning with one `_` are "private". Sometimes they are concealed, a little. Most of the time, the "consenting adults" rule applies -- don't use them foolishly, they're subject to change without notice.
We put "private" in quotes because it's just an agreement between you and your users. You've marked things with `_`. Your users (and yourself) should honor that.
Often, we have method function names with a leading `_` to indicate that we consider them to be "private" and subject to change without notice.
The endless getters and setters that Java requires aren't as often used in Python. Python introspection is more flexible, you have access to an object's internal dictionary of attribute values, and you have first class [functions](http://docs.python.org/lib/built-in-funcs.html) like `getattr()` and `setattr()`.
Further, you have the `property()` function which is often used to bind getters and setters to a single name that behaves like a simple attribute, but is actually well-defined method function calls.
|
Subclassing a class with private members
|
[
"",
"python",
"oop",
"encapsulation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.