Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Hi I have a shell script which should run based on the return of php code:
```
x=1
while [[ "$x" != 5 ]]
do
echo "Welcome $x"
php test.php
x=$?
done
```
And the php code
```
echo "Testdfdf test".PHP_EOL;
exit(4);
```
So I want whenever I get 5 from php to quit the loop.
But I get sometimes:
```
./myshell: line 7: 20529 Segmentation fault php test.php
```
Should it loop without problem? | Probably because of this error which affects both Ubuntu and Debian... <https://bugs.launchpad.net/ubuntu/+source/php5/+bug/343870> | It should and it does, but no clue about why php is ending with a segfault. | Shell Script Segmentation Fault | [
"",
"php",
"shell",
""
] |
The title pretty much sums it up - its the easiest thing in the
world in C++ and Windows, but Java seems to struggle with this issue.
I would like to stay away from solutions involving loading bitmaps of fonts, and instead try go for a native truetype font loader, if possible. Kerning and antialiasing is quite important in my application. | Use the JOGL/Java 2D bridge: render the font on a texture.
Check out "Java 2D and JOGL"[1]
[1]: <http://weblogs.java.net/blog/campbell/archive/2007/01/java_2d_and_jog.html> "" | JOGL has a class, TextRenderer, which should do what you want. It accepts a Java "Font" object, and I think you can specify any ttf file for such objects. It does also support antialiasing, I'm not sure what kerning is but probably that too. :)
Unfortunately the JOGL docs are currently... missing. Dunno where they went, hopefully they'll be back soon (in a day or two). Otherwise I would link you to the documentation for the class. Sorry! | How to use fonts in opengl in java? | [
"",
"java",
"opengl",
"fonts",
""
] |
I am currently successfully downloading live Bloomberg market prices, as well as historical series, using the service's COM API and win32com. Does anyone have any experience doing the same for Reuters live and historical data into Python?
I know that live feeds are available for both services in Excel, so Reuters must also have an API that I can access. Only problem is while Bloomberg support is excellent and describes its API in depth, for this type of query Reuters hasn't been able to get back to me for 2 months! Instead keep trying to sell me their email subscription service which is NOT what I need!!
Anyway rant over any help much appreciated. | **UPDATE in 2018:**
Thomson Reuters now offers the Eikon Data API with a Python package. Please note that you do need a desktop-license to access the API. The information/documentation can be found on the [Developer Portal](https://developers.thomsonreuters.com/eikon-apis/eikon-data-apis).
\*\*Disclaimer: I am currently employed by Thomson Reuters | Check out <http://devcartel.com> they have PyRFA -- Reuters market data API for Python. | Accessing Reuters data in Python | [
"",
"python",
"finance",
"reuters",
"refinitiv-eikon-api",
""
] |
I have some code like this:
```
if (condition) {
var variable = blah;
}
if (differentcondition) {
var variable = blah;
}
```
Is this correct?
I assume that the variable wouldn't be assigned if the condition doesn't return true.
JSLint keeps on telling me, variable already defined.
Am I doing this wrong?
Thanks.
OK, Here's my actual usecase, i'm doing event delegation like this:
```
$("#container").click(function (event){
if ($(event.target).is('img.class1')) {
var imagesrc = $(event.target).attr('src');
// Do something with imagesrc
}
if ($(event.target).is('img.class2')) {
var imagesrc = $(event.target).attr('src');
// Do something with imagesrc
}
// This condition is mutually exclusive to the above 2
if ($(event.target).is('img.class3')) {
var imagesrc = $(event.target).attr('src');
// Do something with imagesrc
}
// This condition is mutually exclusive to 1 and 2 but not to 3
if ($(event.target).is('img.class4')) {
var imagesrc = $(event.target).attr('src');
// Do something with imagesrc
}
});
```
Actually these 2 classes are not mutually exclusive.
This works for me, but is it correct?
The answers were very informative, but I still don't understand how I should set up the variables here.
Actually I also want to say that certain conditions are mutually exclusive, and certain conditions are not.
How should I structure this?
I probably should've used this example from the beginning. | Because javascript has something called "Hoisting" which makes your code do things it doesn't look like it should be doing. Basically, that means a javascript interpreter will move all var declarations, regardless of where they are in the body of a function, to the top of the function body. Then it will move all function definitions to the top, just under all the vars. Then it will finish compiling the function.
Putting a var inside an if statement is not against "the rules" of the language, but it means that, because of var hoisting, that var will be defined regardless of whether the if statement's condition is satisfied.
Keep in mind also that hoisting does not include the assignment, so as others have pointed out, the var declarations will be moved to the top, and left undefined until they're assigned later.
This is an example of a feature that must have seemed like a good idea at the time, but it has turned out to be more confusing than helpful. | This is because in JavaScript, variables only have different scope within function blocks. Unlike other languages, if-blocks do not have a different scope in JavaScript.
In your case, JSLint would tell you the variable is already defined because it is possible that both conditions are true, in which case you'd be overwriting your variables.
Here is an example of how scopes work in JavaScript:
```
function Something() {
var thing1 = "hello";
(function() {
var thing2 = "world";
})();
// This line will throw a ReferenceError because "thing2" is not defined in this scope
// It only exists within the scope of the function executed above
alert(thing1 + thing2);
}
function SomethingElse() {
var thing1 = "hello";
if(true) {
var thing2 = "world";
}
// This line will work because thing2 is not limited to the if-block
alert(thing1 + thing2);
}
``` | What's wrong with defining JavaScript variables within if blocks? | [
"",
"javascript",
"variables",
"scope",
""
] |
Hmm. Instead of "defanging" input or using some kind of regex to remove tags, how safe is it to dump user stuff into a `<textarea>`?
For example, say there's a PHP page that does the following:
```
echo '<textarea>';
echo $_GET['whuh_you_say'] ;
echo '</textarea>';
```
Normally this is vulnerable to xss attacks, but in the `textarea`, all script tags will just show up as `<script>` and they won't be executed.
Is this unsafe? | ```
</textarea>
<script type="text/javascript">
alert("this safe...");
/* load malicious c0dez! */
</script>
<textarea>
``` | If your users aren't supposed to be using any HTML tags whatsoever (which if you're proposing this textarea solution, that's the case), just run it through `htmlspecialchars()` or `htmlentities()` and be done with it. Guaranteed safety. | Using a `<textarea>` to protect against scripts | [
"",
"php",
"security",
"textarea",
"xss",
""
] |
I am working against the deadline and i am sweating now. From past few days I have been working on a problem and now its the time to shout out.
I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecycle, I will be adding data to the SDATA instance.So, this SDATA instance always has the data.
Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if I check the data structures when I am adding the data, all the structures contains data. But when I call this singleton instance from the MBean, am kind of having the empty data.
Can anyone explain or have hints on what's happening ? Any help will be appreciated.
I tried all sorts of SDATA class being final and all methods being synchronized, static, etc.,, just to make sure. But no luck till now.
Another unfortunate thing is that, I some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
***SDATA class with single ton and data access methods***
```
public class ServicePerformanceData {
private Hashtable<String, ServiceExecutionDataCollector> serviceExecutionDataMap = new Hashtable<String, ServiceExecutionDataCollector>();
private HashMap<ServiceExecutionType, String> serviceTypeCountMap = new HashMap<ServiceExecutionType, String>();
private HashSet<String> serviceNameSet = new HashSet<String>();
private static final long DEFAULT_COUNT = 1;
private static final ServicePerformanceData INSTANCE = new ServicePerformanceData();
private Object SYNC = new Object();
private ServicePerformanceData() {
// don't allow anyone to instantiate this class
}
// clearly this must be a singleton
public static ServicePerformanceData getInstance() {
return INSTANCE;
}
public void add(ServiceExecutionDataCollector data) {
// I just add some runtime information to the data structures in this INSTANCE
synchronized (SYNC) {
if (INSTANCE.serviceTypeCountMap.containsKey(data.getServiceType())) {
String count = INSTANCE.serviceTypeCountMap.get(data.getServiceType());
INSTANCE.serviceTypeCountMap.put(data.getServiceType(), Integer.toString(Integer.parseInt(count) + 1));
} else {
INSTANCE.serviceTypeCountMap.put(data.getServiceType(), Integer.toString(1));
}
INSTANCE.serviceExecutionDataMap.put(data.getServiceName(), data);
INSTANCE.serviceNameSet.add(data.getServiceName());
}
}
public int getServiceTypeCount(ServiceExecutionType type) {
if (INSTANCE.serviceTypeCountMap.containsKey(type)) {
return Integer.parseInt(INSTANCE.serviceTypeCountMap.get(type));
}
return 0;
}
public Set getNameList() {
return INSTANCE.serviceNameSet;
}
// I am copying all the data just to make sure that data structures have data
public void copyAllMasterData() {
synchronized (SYNC) {
serviceExecutionDataMap.putAll(ServicePerformanceData.INSTANCE.serviceExecutionDataMap);
serviceNameSet.addAll(ServicePerformanceData.INSTANCE.serviceNameSet);
serviceTypeCountMap.putAll(ServicePerformanceData.INSTANCE.serviceTypeCountMap);
}
}
```
}
***PerformanceStatistics MBean Class*** When i call the data like ServicePerformanceData .getInstance(), i have nothing in that structure. Thus i am not able to get any result with this.
```
public class PerformanceStatistics
implements PerformanceStatisticsMBean {
public void completeExecutionDump() {
//
}
public int getexecuteSSCount() {
return ServicePerformanceData.getInstance().getServiceTypeCount(ServiceExecutionType.ADD);
}
public String executionInfo(String serviceName) {
// GIVES EMPTY LIST EVEN THOUGH THE ACTUAL instance HAS THE DATA
return ServicePerformanceData.getInstance().getExecutionInfo(serviceName.trim());
}
public String calledServicesArray() {
// servicePerformanceData DOES NOT CONTAIN ANY DATA EVEN THOUGH THE ACTUAL instance HAS THE DATA
ServicePerformanceData servicePerformanceData = ServicePerformanceData.getInstance();
servicePerformanceData.copyAllMasterData();
System.out.println("ServicePerformanceData.INSTANCE" + ServicePerformanceData.getInstance());
System.out.println(servicePerformanceData);
// GIVES EMPTY LIST EVEN THOUGH THE ACTUAL instance HAS THE DATA
System.out.println("Name List" + ServicePerformanceData.getInstance().getNameList());
return ServicePerformanceData.getInstance().getNameList().toString();
}
```
} | After a lot of research and carefully looking into the design, this seems to be a problem with the Weblogic class loaders. My product has 6 different applications and it is not warranted that the same call loader loads all the applications.
Thus, in the above case, the actual data is getting updated in a class loaded by ClassLoader\_X and the access is done by the class with ClassLoader\_Y. Clearly, the data is not transparent across the class loaders. So, i always have the different instances of the same class and the data in the accessor class is always empty.
Once i moved both the data creation and consumption classes to a single application/Jar, everything works good. I did not change any of the above code. | Could it be that the class is loaded from different class loaders? | Can not access the Instance Data of a Singleton class from MBean | [
"",
"java",
"singleton",
"jmx",
"data-access",
"mbeans",
""
] |
Code sample should explain things:
```
class A
{
B* pB;
C* pC;
D d;
public :
A(int i, int j) : d(j)
{
pC = new C(i, "abc");
} // note pB is not initialised, e.g. pB(NULL)
...
};
```
Obviously pB should be initialised to NULL explicitly to be safe (and clear), but, as it stands, **what is the value of pB after construction of A?** Is it default initialised (which is zero?) or not (i.e. indeterminate and whatever was in memory). I realise initialisation in C++ has a fair few rules.
I think it isn't default initialised; as running in debug mode in Visual Studio it has set pB pointing to 0xcdcdcdcd - which means the memory has been new'd (on the heap) but not initialised. However in release mode, pB always points to NULL. Is this just by chance, and therefore not to be relied upon; or are these compilers initialising it for me (even if it's not in the standard)? It also seems to be NULL when compiled with Sun's compiler on Solaris.
I'm really looking for a specific reference to the standard to say one way or the other.
Thanks. | Here is the relevant passage fromt he standard:
> 12.6.2 Initializing bases and members [class.base.init]
>
> 4 If a given nonstatic data member or
> base class is not named by a mem-
> initializer-id in the
> mem-initializer-list, then
>
> --If the entity is a nonstatic data
> member of (possibly cv-qualified)
> class type (or array thereof) or a base class, and the entity class
> is a non-POD class, the entity is default-initialized (*dcl.init*).
> If the entity is a nonstatic data member of a const-qualified type,
> the entity class shall have a user-declared default constructor.
>
> --**Otherwise, the entity is not
> initialized**. If the entity is of
> const-qualified type or reference type, or of a (possibly cv-quali-
> fied) POD class type (or array thereof) containing (directly or
> indirectly) a member of a const-qualified type, the program is
> ill-
> formed.
>
> After the call to a constructor for
> class X has completed, if a member
>
> of X is neither specified in the
> constructor's mem-initializers, nor
> default-initialized, nor initialized
> during execution of the body of
> the constructor, the member has
> indeterminate value. | According to the [C++0x standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf) section 12.6.2.4, in the case of your pointer variable, if you don't include it in the initializer list and you don't set it in the body of the constructor, then it has indeterminate value. 0xCDCDCDCD and 0 are two possible such values, as is anything else. :-) | C++: member pointer initialised? | [
"",
"c++",
"pointers",
"default",
""
] |
What's the translation of this snippet in VB .NET?
```
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Boolean> predicate)
{
foreach (TSource element in source)
{
if (predicate(element))
yield return element;
}
}
``` | The problem here isn't converting an extension method - it's converting an iterator block (the method uses `yield return`. VB doesn't have any equivalent language construct - you'd have to create your own implementation of `IEnumerable<T>` which did the filtering, then return an instance of the class from the extension method.
That's exactly what the C# compiler does, but it's hidden behind the scenes.
One point to note, which might not be obvious otherwise: `IEnumerator<T>` implements `IDisposable`, and a `foreach` loop disposes of the iterator at the end. This can be very important - so if you *do* create your own implementation of this (and I'd recommend that you don't, frankly) you'll need to call `Dispose` on the iterator returned from `source.GetEnumerator()` in your own `Dispose` method. | This question is old, but for people coming here from Google there is good news - new releases of VB.NET have support for the c# yield return operator (I believe this isn VS.NET 2010/2012 w/ .net 4.0)... Here is the converted sample:
```
<System.Runtime.CompilerServices.Extension> _
Public Iterator Function Where(Of TSource)(source As IEnumerable(Of TSource), predicate As Func(Of TSource, [Boolean])) As IEnumerable(Of TSource)
'' non-lambda version of the method body
'For Each element As TSource In source
' If predicate(element) Then
' Yield element
' End If
'Next
For Each element As TSource In From item In source Where predicate(item)
Yield element
Next
End Function
```
There is no need to change static to shared as VB.NET extension methods must be defined in Modules which are automatically 'shared' or static. | C# to VB .NET yield return conversion | [
"",
"c#",
".net",
"vb.net",
""
] |
I'm trying to pad a time (playtime of an MP3) using sprintf() in PHP.
```
sprintf("%02d:2d:2d", $time);
```
The function that returns the time gets, for example, '1:56' if the MP3 is 1 minute 56 seconds long, and that call brings back "01:56:00" (whereas it needs to be 00:01:56). How can I make this work? How can I tell sprintf to pad on the left?
Or is there a better way to go about this? A more appropriate function maybe?
Thanks | I think you'll need to calculate each element separately, so how about:
```
sprintf("%02d:%02d:%02d", floor($time/3600), floor($time/60)%60, $time%60);
``` | You can use the [date-function](http://www.php.net/manual/en/function.date.php).
Something like this should work, if $time is in unix timestamp format:
```
print(date("H:i:s", $time));
``` | Padding a time on the left with sprintf? | [
"",
"php",
"printf",
""
] |
The browser on the iPhone is capable of using advanced web technologies introduced in HTML5. One of these is the app cache that allows web pages to run on the client, from the cache, without a connection to the internet. Together with Local Storage you can also save data permanently "in" the page.
My question is, would it then be possible to make a website that when visited and set as a web clip (bookmark on the home screen), could be accessed again, at any moment. Using HTML5, Javascript and css, you can make some very good apps and at the same time avoid the pricey developer fee, the harsh app approval and the single platform development platform?
Or am I just dreaming? | Yes, what you describe is certainly possible. You can take advantage of Apple's support for the HTML5 app cache by creating a manifest file indicating which resources are to be cached, and specifying that file from within the HTML page of your web app. Details on how to do this are in [Apple's documentation](https://developer.apple.com/library/content/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/OfflineApplicationCache/OfflineApplicationCache.html).
Update: I have tried this on my own web app, and it works. You have to make sure that the manifest file is served as type text/cache-manifest, like it says in the documentation. Also, I don't know how long Safari is guaranteed to keep the files cached. I have found that manually clearing Safari's cache will clear the cached web app files as well, even for a web app link saved on the device's home screen. | I have been building a native html app with iui and Iweb up scripts and installer called Sentenza, I am doing the app to test Sentenza for a review.
But all said there is still lack of easy framworks for a user I am sure it be easy to make
a cental js script that as default actions like the button commands for a new page
I think this could be possable to redo the html 5 seen and there is no need for cashing as
Sentenza far as I know already enabls this long as your use a ajax call and not a index.html
call it works
and its simple I have (a lalala ="Pagename.page" ) or if the page is just small then i can
do a ancker command thats also contactlled by JS and css as far as i know
```
body
div id="home" title="home" selected="true"
div id="link1" title="New Page"
```
I look like a new page
```
/div
```
I am a noob when it comes to all this but if we making these to work and look like native app then I feel this kinda things should be stream lined, I not sure how we could do this but I am sure we could make a simple mainframe framwork that never needs to be opened or
edited for the end user they just include the meta and css tags and off they go if your intested in helping me do something like this please email webmaster (*at*) mokodev (*Dot*) info I want to make this framework free but also based on the already known IUI and IWeb frameworks, the mainframe would work on any OS as it be just flat css and js files but if we can get it to work i can also try make a windows IU template builder this
would enable people get started. | iPhone web apps running as native apps | [
"",
"javascript",
"iphone",
"html",
"offline",
"mobione",
""
] |
The `equals()` method (and for that matter, also the `compareTo()` method) can become a performance hotspot (e.g. in a high-traffic `HashMap`). I was wondering what tricks folks have adopted to optimize these methods for these cases when they prove necessary.
IntelliJ IDEA, for example, generates the following:
```
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
...
}
```
What else have you come across that can be a guideline for writing a good performing `equals()` method? | Some general ideas that are not necessarily specific to `equals()`
* **Fail as early as possible**. Similar to the snippet you posted, start with the broadest exclusion criteria first and then become more fine grained, so that the method can return as soon as possible
* **Compare only attributes required for equality**. I've sometimes seen people compare every single piece of a information a class provides, even though only a handful of attributes actually play a semantic role for the equality of two class instances. This of course highly depends on your class and the design
* **Avoid equality recursion, if possible**. Depending on what kind of class attributes you are comparing, you might get yourself into situations where you are recursively calling `equals()` on yourself or other objects, which can have a hidden performance impact
In addition to performance considerations, don't forget the [`equals` API contract](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)) to ensure that your equality is *reflexive*, *symmetric*, *transitive* and *consistent* and to always override `hashcode()` as well, when you override `equals()`. | [How to Write an Equality Method in Java](http://www.artima.com/lejava/articles/equality.html) is an extremely detailed and well written article explaining common pitfalls in writing an equality method and how to avoid them. | Optimizing equals() method | [
"",
"java",
"performance",
"equals",
"equality",
""
] |
That's what I wanna achieve :
There will be dll which contains only methods which calls my actual methods from my application and I can share that dll with outside world regardless of which methods it includes because actual methods will be in the dll in my application but if some one uses that outside dll he/she can manages to get my application to do something in limits of I desire.
I hope I could describe what I want. I don't know if you have ever used Skype4COM.dll. It actually works like that, it somehow connects to Skype Client and let me call some one I want. For example :
```
Skype s = new Skype();
s.PlaceCall("phoneNumber");
```
I import Skype4COM dll in my project and when i write code like above in C#, it connects to Skype and make a call.
I think there is no actual methods which makes calls in Skype4Com.dll. I think it only does have some sort of methods which reach actual methods in Skype API and make the call so whatever the developers change in Skype, it doesn't affect Skype4Com.dll wrapper as long as signature stays the same.
So, that's what I want to achive, I am not quite interested in writing wrappers tho, that was a sample case, I want to write a dll which reachs my API and uses method signatures and let people use the application from outside so as long as the signatures stay same, if I want to change something between block I don't need to change the dll given out to outside..
Thank in advance.... | If I understand you correctly, you want to expose a limited subset of the functions of your application to outside users. In effect, you want to offer a service, but nothing else.
Then you should use Windows Communication Foundation to host a service inside of your application (or elsewhere). This service could use industry-standard protocols like SOAP; or could use REST; or it could use faster binary transfers over TCP/IP for your .NET clients.
It's perfect for a service-oriented situation like yours. | What you're describing is a COM wrapper around Skype. If you really want a COM wrapper around your C# DLL, you can do that. Microsoft has provided [an example](http://msdn.microsoft.com/en-us/library/c3fd4a20.aspx) that demonstrates how to create a COM Class from C#.
If you're looking into providing a wrapper around your code from managed DLLs, then it's as simple as providing a public interface that consumers of your DLL can use. You'll probably also want to install your code in the GAC (Global Assembly Cache) so that anyone that wants to call into your API can do so without putting copies of your code all over their system. | How to Communicate DLLs in C# | [
"",
"c#",
"api",
"dll",
""
] |
I'm getting an Undefined reference error message, on this statement:
```
GlobalClass *GlobalClass::s_instance = 0;
```
Any ideas? Code is shown below:
================================================
```
#ifndef GLOBALCLASS_H_
#define GLOBALCLASS_H_
#include <string>
class GlobalClass {
public:
std::string get_value();
void set_value(std::string);
static GlobalClass *instance();
static GlobalClass *s_instance;
private:
std::string m_value;
};
#endif /* GLOBALCLASS_H_ */
```
===============================================
```
#include <string>
#include "GlobalClass.h"
/*
GlobalClass(int v = 0)
{
m_value = v;
}
*/
static GlobalClass *s_instance;
std::string GlobalClass::get_value()
{
return m_value;
}
void GlobalClass::set_value(std::string v)
{
m_value = v;
}
static GlobalClass *instance() {
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
```
===========================================================
```
#include <iostream>
#include "GlobalClass.h"
using namespace std;
int main() {
GlobalClass::s_instance = 0;
std::string myAddress = "abc";
GlobalClass::instance()->set_value(myAddress); \\ <=== compiler error
std::cout << "====>address is is " << GlobalClass::instance()->get_value()
<< std::endl;
return 0;
}
``` | Are you trying to implement a Singleton class? Ie. You want only a single instance of of the class, and you want that instance available to anyone who includes the class. I think its commonly known as a Singleton, the following example works as expected:
Singleton.h:
```
#include <string>
class Singleton
{
public:
static Singleton* instance()
{
if ( p_theInstance == 0 )
p_theInstance = new Singleton;
return p_theInstance;
}
void setMember( const std::string& some_string )
{
some_member = some_string;
}
const std::string& get_member() const
{
return some_member;
}
private:
Singleton() {}
static Singleton* p_theInstance;
std::string some_member;
};
```
Singleton.cpp:
```
Singleton* Singleton::p_theInstance = 0;
```
main.cpp:
```
#include <string>
#include <iostream>
#include "Singleton.h"
int main()
{
std::string some_string = "Singleton class";
Singleton::instance()->setMember(some_string);
std::cout << Singleton::instance()->get_member() << "\n";
}
```
Note that the constructor is private, we don't want anyone to be creating instances of our singleton, unless its via the 'instance()' operator. | When you declare a static field `s_instance` in your .h file, it only tells the compiler that this field exists somewhere. This allows your `main` function to reference it. However, it doesn't define the field anywhere, i.e., no memory is reserved for it, and no initial value is assigned to it. This is analogous to the difference between a function prototype (usually in a .h file) and function definition (in a .cpp file).
In order to actually define the field, you need to add the following line to your .cpp file at global scope (not inside any function):
```
GlobalClass* GlobalClass::s_instance = 0;
```
It is important that you don't add the `static` modifier to this definition (although you should still have the `static` modifier on the declaration inside the class in the .h file). When a definition outside a class is marked `static`, that definition can only be used inside the same .cpp file. The linker will act as if it doesn't exist if it's used in other .cpp files. This meaning of `static` is different from `static` inside a class and from `static` inside a function. I'm not sure why the language designers used the same keyword for three different things, but that's how it is. | Undefined reference - C++ linker error | [
"",
"c++",
"compilation",
""
] |
Lets say I have a string that represents a date that looks like this:
"Wed Jul 08 17:08:48 GMT 2009"
So I parse that string into a date object like this:
```
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy");
Date fromDate = (Date)formatter.parse(fromDateString);
```
That gives me the correct date object. Now I want to display this date as a CDT value.
I've tried many things, and I just can't get it to work correctly. There must be a simple method using the DateFormat class to get this to work. Any advice? My last attempt was this:
```
formatter.setTimeZone(toTimeZone);
String result = formatter.format(fromDate);
``` | Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone.
```
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
```
Having said that, my standard advice on date/time stuff is to use [Joda Time](http://joda-time.sourceforge.net), which is an altogether better API.
EDIT: Short but complete program:
```
import java.text.*;
import java.util.*;
public class Test
{
public List<String> names;
public static void main(String [] args)
throws Exception // Just for simplicity!
{
String fromDateString = "Wed Jul 08 17:08:48 GMT 2009";
DateFormat formatter = new SimpleDateFormat
("EEE MMM dd HH:mm:ss zzz yyyy");
Date fromDate = (Date)formatter.parse(fromDateString);
TimeZone central = TimeZone.getTimeZone("America/Chicago");
formatter.setTimeZone(central);
System.out.println(formatter.format(fromDate));
}
}
```
Output: Wed Jul 08 12:08:48 CDT 2009 | Using:
```
formatter.setTimeZone(TimeZone.getTimeZone("US/Central"));
```
outputs:
```
Wed Jul 08 12:08:48 CDT 2009
```
for the date in your example on my machine. That is after substituting zzz for ZZZ in the format string. | How do I display a date with a custom timezone? | [
"",
"java",
"date",
"timezone",
"date-format",
""
] |
Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like `"+c-R+D-E"` (there are a few extra letters).
I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.
```
# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
```
Are there some better/cleaner ways to do this? | I don't know about cleaner, but there's another alternative:
```
for (op, code) in zip(s[0::2], s[1::2]):
print op, code
```
A no-copy version:
```
from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
print op, code
``` | Maybe this would be cleaner?
```
s = "+c-R+D-e"
for i in xrange(0, len(s), 2):
op, code = s[i:i+2]
print op, code
```
You could perhaps write a generator to do what you want, maybe that would be more pythonic :) | Iterate over a string 2 (or n) characters at a time in Python | [
"",
"python",
"iteration",
""
] |
I want to efficiently check if a table contains any rows that match <condition A> and do not match <condition B>, where the conditions are arbitrary.
In Oracle, this *almost* works:
```
select count(*) from dual
where exists (
select * from people
where (<condition A>)
and not (<condition B>)
);
-- returns zero if all rows that match <condition A> also match <condition B>
-- (well, almost)
```
The problem is the dreaded null values. Lets say <condition A> is **name = 'Aaron'** and <condition B> is **age = 21**. The query will correctly identify any Aarons whose age is not equal to 21, but it fails to identify any Aarons whose age is null.
Here is a correct solution, but on a table with millions of records it can take a while:
```
select (
select count(*) from people
where (<condition A>)
) - (
select count(*) from people
where (<condition A>)
and (<condition B>)
) from dual;
-- returns zero if all rows that match <condition A> also match <condition B>
-- (correct, but it is s l o w...)
```
Unfortunately the two conditions will be arbitrary, complex, changing, and generally out of my control. They are generated from the application's persistence framework from user searches, and while we try to keep our indexes up with our users, a lot of the time they will cause big table scans (which is why that first query with the "exists" clause is so much faster than the second - it can stop as soon as it finds one matching record, and it doesn't have to do two separate scans).
How can I do this efficiently without futzing up on the nulls? | If you do have the id field, try:
select count(\*) from dual
where exists (
select \* from people
where (cond a)
and zzz.id not in (select id from people where (cond b))
); | If for every nullable column you can come up with a dummy value that should never be valid, then you could do something like this:
```
select count(*) from dual
where exists (
select * from (
select NVL(name, 'No Name') name, NVL(age, -1) age from people
)
where (<condition A>)
and not (<condition B>)
);
```
You would probably want to create function-based indexes on those expressions.
This is certainly easier than parsing through the conditions at runtime and trying to replace the column names with NVL expressions, and it should have the same end result. | Negating an arbitrary where clause condition (including the null tests) | [
"",
"sql",
"oracle",
"null",
"where-clause",
""
] |
Duplicate: [Killing a thread (C#)](https://stackoverflow.com/questions/1051838/killing-a-thread-c)
---
I'm currently passing my thread a threadstart delegate and starting it.
I need a way to kill this thread if I don't receive a response back from it within 3 seconds.
What is the best way to accomplish this? It doesn't have to be with thread/threadstart necessarily, that's just what I've been using so far. | Check out this [SO-solution](https://stackoverflow.com/questions/299198/implement-c-generic-timeout) using the IAsyncResult.AsyncWaitHandle.WaitOne() method | Killing a thread is always a bad idea, and should be reserved for scenarios where you are already dealing with a sickly process you are about to kill anyway. Do you own the code in the thread? Perhaps put in some state checks and exit cleanly if the flag is set?
If not, and you need the code to work after the abort, a separate **process** may be safer than a thread-start. At least you won't cripple your *own* code (with, for example, an unreleased lock, or a hung static constructor / type initializer). | How do I kill a thread if it takes too long in C#? | [
"",
"c#",
"multithreading",
""
] |
i have to use special chars in my python-application.
For example: ƃ
I have information like this:
```
U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
```
But when i just pust symbols into python-script i get an error:
> Non-ASCII character '\xc8' ...
> How can i use it in strings for my application? | You should tell the interpreter which encoding you're using, because apparently on your system it defaults to ascii. See [PEP 263](http://www.python.org/dev/peps/pep-0263/). In your case, place the following at the top of your file:
```
# -*- coding: utf-8 -*-
```
Note that you don't have to write *exactly* that; PEP 263 allows more freedom, to accommodate several popular editors which use slightly different conventions for the same purpose. Additionally, this string may also be placed on the second line, e.g. when the first is used for the [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). | While the answers so fare are all correct, I thought I'd provide a more complete treatment:
The simplest way to represent a non-ASCII character in a script literal is to use the u prefix and u or U escapes, like so:
```
print u"Look \u0411\u043e\u0440\u0438\u0441, a G-clef: \U0001d11e"
```
This illustrates:
1. using the u prefix to make sure the string is a `unicode` object
2. using the u escape for characters in the basic multi-lingual plane (U+FFFD and below)
3. using the U escape for characters in other planes (U+10000 and above)
4. that Ƃ (U+0182 LATIN CAPITAL LETTER B WITH TOPBAR) and Б (U+0411 CYRILLIC CAPTIAL LETTER BE) just one example of many confusingly similar Unicode codepoints
The default script encoding for Python that works everywhere is ASCII. As such, you'd have to use the above escapes to encode literals of non-ASCII characters. You can inform the Python interpreter of the encoding of your script with a line like:
```
# -*- coding: utf-8 -*-
```
This only changes the encoding of your script. But then you could write:
```
print u"Look Борис, a G-clef: "
```
Note that you still have to use the u prefix to obtain a `unicode` object, not a `str` object.
Lastly, it *is* possible to change the default encoding used for `str`... but this not recommended, as it is a global change and may not play well with other python code. | Special chars in Python | [
"",
"python",
"chars",
""
] |
I need to execute basic queries on a text file which consists of several columns. I tried to use StelsCSV which is a JDBC Driver for CSV files. It is good but commercial. Do you know other tools for the same task? | [HSQL](http://www.hsqldb.org/) has functionality for manipulatng csv data, and it's open source. | Haven't used this but here is one: <http://csvjdbc.sourceforge.net/>
Also: <https://xlsql.dev.java.net/> | What is the best tool to query delimited text files in Java? | [
"",
"java",
"csv",
"text",
"hsqldb",
""
] |
```
create table A (
id int(10) not null,
val1 varchar(255),
primary key (id)
);
```
Approach [a]:
```
create table B (
a_id int(10) not null,
val2 varchar(255),
foreign key (a_id) references A(id)
);
```
Approach [b]:
```
create table B (
id int(10) not null,
a_id int(10) not null,
val2 varchar(255),
foreign key (a_id) references A(id),
primary key (id)
);
```
By choosing [a], I can avoid creation of the "id" surrogate key in table 'B'. Which is the preferred approach for creating table 'B' from a modeling perspective? | As i understand it : in [a], you are creating a 1:1 relationship, in [b] you are not.
**They aren't alternatives!**
In case [b], if table A would hold invoices, table B could be used for invoicelines whereas in [a] this cannot, since there can only be one record for each record in table A. (Thus only 1 invoiceline per invoice)
So, if you really want an answer, use [b], your [a] construct could be replaced with one table only, and is probably not what you mean. (also since you didn't set a primary key, the same as the FK in a 1:1 relationship) | You never *need* a surrogate key (hence it's name). It looks like you're mixing a logical model and a physical model. For your logical model, you presumably would have
```
CREATE TABLE A (
Val1 varchar() not null,
constraint PK_A KEY (Val1) --?
)
CREATE TABLE B (
Val1 varchar() not null,
Val2 varchar() not null,
constraint PK_B KEY (Val2), --? or Val1,Val2?
constraint FK_A FOREIGN KEY (Val1) references A
)
```
(The above in made-up SQL, but hopefully you see the point)
Now, for a physical model, you might introduce surrogates wherever they make sense - where the logical keys are long (e.g. varchars). But whether you do or not is really up to you. And remember to enforce the logical keys still | Do I need a surrogate key in a one-to-many relationship? | [
"",
"sql",
"database-design",
""
] |
I have an application that uses a variety of external resources (web services, filesystem, database), and therefore can be quite difficult to configure. The plan is to add a self-diagnostic tool to the application so it can report problems with the configuration and allow the user to correct it. Are there any design patterns, libraries, examples, etc, that I should consider when designing such a feature?
The application is written in C# and ASP.NET. | One way could be to have, in the admin area of your site, a set of pages that report on the state of these external resources. For example, it might tell you the database it is configured to connected to (and if it could establish a connection), what server it is running on (if loadbalanced), and so on).
For web services, I have a little service that runs and every couple of minutes "pings" the web service to see if it is still there. If it isn't I get a text message on my phone (through another third party service incidentally) and a detailed error report in an email - You might prefer that than having to know to check a web page on the site.
I don't know if there are any specific design patterns for this, I just add this reporting element to the normal layers in the application. | **If they can see you, you can see them**
Add a layer to your (external) apps that sends asynchronous "pings" out in some form. Could be a messaging, topic-like middleware tool.
If you don't have control over the external systems, possibly add a sep-A-RAT-e "facade" app that does the diagnostics (eg calling a http connection with a timeout) and then send out pings on the external apps behalf.
Add a listener to your central app with a configurable list of remote apps (message types) that are expected to ping in and raise an alert if one of them fails to do so.
Just make sure, to run all of this in separate threads and asynchronously. You don't want blocking UI threads or too many open network connections that wait for a timeout.
This way your central app has very little overhead. It doesn't need to do the polling itself, just sits there with a queue listener and a map of apps and when they last called in. If one of them reaches a threshold for not having called in lately, you have a problem and your app has some way to let you know. | How would I build an application that can diagnose itself at runtime? | [
"",
"c#",
"asp.net",
"testing",
""
] |
I want to present a schema to my BA team.
```
Select TABLE_NAME, col.DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS col
order by col.TABLE_CATALOG, TABLE_NAME, TABLE_SCHEMA, col.ORDINAL_POSITION
```
I want to present 3 rows of sample data as well but I wanted to pivot it out so they get an output that has the following 3 columns:
1. Table\_Name
2. Data\_Type
3. Sample\_Data
How do I pivot that data? | I built this using XML PATH
```
SET NOCOUNT ON
SELECT
'SELECT ''' + col.TABLE_NAME + ''' AS TableName,' +
'''' + col.COLUMN_NAME + ''' AS ColumnName,'+
' ''' + col.DATA_TYPE + ''' as DataType, ' +
'
(
SELECT top 3 CONVERT (VARCHAR, p2.' + col.COLUMN_NAME + ') + '',''
FROM ' + col.TABLE_SCHEMA + '.' + col.TABLE_NAME + ' p2
ORDER BY p2. ' + col.COLUMN_NAME + '
FOR XML PATH('''')
)
UNION ALL'
FROM INFORMATION_SCHEMA.COLUMNS col
ORDER BY
col.TABLE_CATALOG,
col.TABLE_NAME,
col.TABLE_SCHEMA,
col.ORDINAL_POSITION
```
I copy paste the result of this query into a new query editor window. I delete the last UNION ALL and execute the query.
It gives me an additional comma in the Returned data, but my B.A.'s were OK with that. | Here is a solution based on cursors and dynamic SQL. I've includes the table schema and column names in the final result as well, though the question just asks fro table name, data type, and sample data.
Also, I wasn't sure if you wanted three rows of sample data per table/column, or if you wanted one row per table/column with three columns of sample data. I went with the former, please let me know if you wanted the later. I did include a "No data" indicator for tables that don't have any sample data.
Tested on SQL Server 2005, but I think it should work with 2000 as well.
```
Create Table #results
(id Integer Not Null Identity(1, 1)
,table_schema nVarChar(128) Not Null
,table_name nVarChar(128) Not Null
,column_name nVarChar(128) Not Null
,data_type nVarChar(128) Not Null
,sample_data nVarChar(max) Null);
Declare @table_name nVarChar(128)
,@table_schema nVarChar(128)
,@column_name nVarChar(128)
,@data_type nVarChar(128)
,@sql nVarChar(max)
,@inserted Integer;
Declare rs Cursor Local Forward_Only Static Read_Only
For Select
col.table_schema
,col.table_name
,col.column_name
,col.data_type
From INFORMATION_SCHEMA.COLUMNS col
Order By col.TABLE_CATALOG
,col.TABLE_SCHEMA
,col.TABLE_NAME
,col.ORDINAL_POSITION
Open rs;
Fetch Next From rs Into @table_schema, @table_name, @column_name, @data_Type;
While @@Fetch_Status = 0 Begin;
Set @table_schema = QuoteName(@table_schema);
Set @table_name = QuoteName(@table_name);
Set @column_name = QuoteName(@column_name);
Set @sql = N'
Insert Into #results
(table_schema
,table_name
,column_name
,data_type
,sample_data)
Select Top 3 ' + QuoteName(@table_schema, '''') + N'
,' + QuoteName(@table_name, '''') + N'
,' + QuoteName(@column_name, '''') + N'
,' + QuoteName(@data_type, '''') + N'
,' + @column_name + N'
From ' + @table_schema + N'.' + @table_name;
Exec (@sql);
Select @inserted = count(*)
From #results
Where table_schema = @table_schema
And table_name = @table_name
And column_name = @column_name;
If @inserted = 0
Insert Into #results (table_schema, table_name, column_name, data_type, sample_data)
Values (@table_schema, @table_name, @column_name, @data_type, ' -- No Data -- ');
Fetch Next From rs Into @table_schema, @table_name, @column_name, @data_Type;
End;
Close rs;
Deallocate rs;
-- Probably should include the schema and column name too:
Select table_schema, table_name, column_name, data_type, sample_data
From #results
Order by [id];
-- But this is what the question asked for:
-- Select table_name, data_type, sample_data
-- From #results
-- Order by [id];
Drop Table #results;
```
There are probably more elegant solutions available, but this should get you started, I think. Good luck! | Sample SQL Data | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
When compiling a 64bit application, why does strlen() return a 64-bit integer? Am i missing somthing?
I understand that strlen() returns a size\_t type, and by definition this shouldn’t change, but... Why would strlen **need** to return a 64-bit integer?
The function is designed to be used with strings. With that said:
Do programmers commonly create multi-gigabyte or multi-terabyte strings?
If they did, wouldn’t they need a better way to determine the string length than searching for a NULL character?
I think this is ridiculous, in fact, maybe we need a StrLenAsync() function with a callback just to handle the ultra long process for searching for the NULL in the 40TB string. Sound stupid? Yea, well strlen() returns a 64-bit integer!
Of course, the proposed StrLenAsync() function is a joke. | It looks like, when compiling for a 64-bit target, size\_t is defined as 64-bit. This makes sense, since size\_t is used for sizes of all kinds of objects, not just strings. | On a 64-bit app, it's definitely possible to create a 5GB string.
The spec is not intended to keep you from doing stupid things.
Even if it wasn't needed, it wouldn't be worth changing the specification of strlen away from using a size\_t just to make the return value 4 instead of 8 bytes. | Why does strlen() return a 64-bit integer? Am i missing something? | [
"",
"c++",
"standards",
"64-bit",
""
] |
```
a:link {color:#FF0000} /* unvisited link */
a:visited {color:#00FF00} /* visited link */
a:hover {color:#FF00FF} /* mouse over link */
a:active {color:#0000FF} /* selected link */
```
The [pseudo-classes](http://www.w3schools.com/CSS/css_pseudo_classes.asp) (link, visited, hover, active) don't do exactly what I want which is to highlight the last-clicked link on a page to be a different color from all of the other links on the page.
Would this require JQuery and, if so, any suggestions? | It wouldn't *require* jQuery, but it's sure easy to do with jQuery.
```
$("a").click(function () {
$("a").css("color", "blue");
$(this).css("color", "yellow");
});
``` | You don't need Javascript. The CSS pseudo-class that you're looking for is '**focus**'.
*ps: it holds the 'last clicked' color only until you click on something else in the page.*
```
a:link {color:#00FF00}
a:visited {color:#00FF00}
a:hover {color:#FF00FF}
a:focus {color:#0000FF} /* this one! */
```
```
<b>
<a href="javascript:void(0);">link 1</a>
<a href="javascript:void(0);">link 2</a>
<a href="javascript:void(0);">link 3</a>
<a href="javascript:void(0);">link 4</a>
</b>
```
There is a pure CSS hack to make the link hold the color even after the user click on other elements, using radio buttons with the labels as pseudo-links:
```
label {
color: #00FF00;
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10 and IE 11 */
user-select: none; /* Standard syntax */
text-decoration: underline;
font-weight: 800;
}
label:hover {
color: #FF00FF;
}
input[type="radio"] {
display: none;
}
input[type="radio"]:checked + label {
color: #0000FF;
}
```
```
<input type="radio" name="menu" id="link1">
<label for="link1">link 1</label>
<input type="radio" name="menu" id="link2">
<label for="link2">link 2</label>
<input type="radio" name="menu" id="link3">
<label for="link3">link 3</label>
<input type="radio" name="menu" id="link4">
<label for="link4">link 4</label>
```
If you want to keep the link color after the user interact with other elements on the page without the CSS hack, you can use Javascript, adding a class to those links then adding an event listener:
```
document.addEventListener("click",
function(e) {
e = e || window.event;
if (e.target.classList.contains('menulink')){
for (var i = 0; i < document.getElementsByClassName("menulink").length; i++ ) {
document.getElementsByClassName("menulink")[i].style.color='#00FF00';
}
e.target.style.color='#0000FF';
}
});
```
```
a:link { color: #00FF00; }
a:visited { color: #00FF00; }
a:hover { color: #FF00FF !important; }
```
```
<b>
<a href="#" class="menulink">link 1</a>
<a href="#" class="menulink">link 2</a>
<a href="#" class="menulink">link 3</a>
<a href="#" class="menulink">link 4</a>
</b>
```
In the above snippet, once a link is clicked, it reset the color of all links (painting it with green), then paints the clicked one with a different color. | How to set the last-clicked anchor to be a different color from all other links? | [
"",
"javascript",
"jquery",
"html",
"css",
"hyperlink",
""
] |
I have a login box in my MasterPage. Whenever the login information is not correct, I valorize `ViewData["loginError"]` to show the error message to the user.
Login is an action of the UserController, so the form that contains the login has `action = "/User/Login"`.
As a user can try to log in from any page, in case of success I redirect him to his personal page, but in case of error I want him to stay on the very same page where he tried to login. I've found that this works:
```
return Redirect(Request.UrlReferrer.ToString());
```
but it seems that, as I'm not returning a proper view, the data on ViewData is lost, so I cannot show the error message.
Any suggestion on how to solve this and similar problems?
Thanks | You probably want to use the `TempData` property, this will be persisted across to the next HTTP request. | Why not handle the login via AJAX instead a full post? You could easily supply the status, a redirect URL, and any error messages via JSON.
```
public ActionResult Logon( string username, string password )
{
...
// Handle master page login
if (Request.IsAjaxRequest())
{
if (success)
{
return Json( new { Status = true, Url = Url.Action( "Index", "Home" ) } );
}
else
{
return Json( new { Status = false, Message = ... } );
}
}
else // handle login page logon or no javascript
{
if (success)
{
return RedirectToAction( "Index", "Home" );
}
else
{
ViewData["error"] = ...
return View("Logon");
}
}
}
```
Client-side
```
$(function() {
$('#loginForm input[type=submit]').click( function() {
$('#loginError').html('');
$.ajax({
url: '<%= Url.Action("Logon","Account") %>',
dataType: 'json',
type: 'post',
data: function() { return $('#loginForm').serialize(); },
success: function(data,status) {
if (data.Status) {
location.href = data.Url;
}
else {
$('#loginError').html( data.Message );
}
}
});
return false;
});
});
``` | ASP.NET MVC: return Redirect and ViewData | [
"",
"c#",
"asp.net-mvc",
""
] |
Consider this code:
```
class Jm44 {
public static void main(String args[]){
int []arr = {1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}
```
It prints:
```
0
0
3
0
```
What's this? For-each is supposed to run over all the elements in the array, why would it run `arr[3]=0` but not `arr[2]=0`? | If you look at what happens to `arr` in the first loop, it becomes obvious.
```
int[] arr = {1, 2, 3, 4};
for (int i : arr) {
System.out.println("i = " + i);
arr[i] = 0;
System.out.println("arr = " + Arrays.toString(arr));
}
for (int i : arr) {
System.out.println(i);
}
```
This prints:
```
i = 1
arr = [1, 0, 3, 4]
i = 0
arr = [0, 0, 3, 4]
i = 3
arr = [0, 0, 3, 0]
i = 0
arr = [0, 0, 3, 0]
0
0
3
0
```
You are modifying the values in the array, using the values in the array as indexes. The "foreach" loop goes through the *values* of the array, not the *indexes* of the array. After removing the syntactic sugar, here is what your foreach loop actually is:
```
int[] arr = {1, 2, 3, 4};
for (int index = 0; index < arr.length; index++) {
int i = arr[index];
arr[i] = 0;
}
for (int i : arr) {
System.out.println(i);
}
```
To be able to index the array, you need to use the traditional for loop, like this:
```
int[] arr = {1, 2, 3, 4};
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
for (int i : arr) {
System.out.println(i);
}
``` | ```
int []arr = {1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
```
Watch arr in the debugger.
```
1,2,3,4 (initially)
1,0,3,4 (after we change arr[arr[0]], or arr[1])
0,0,3,4 (after we change arr[arr[1]], or arr[0])
0,0,3,0 (after we change arr[arr[2]], or arr[3])
0,0,3,0 (after we change arr[arr[3]], or arr[0] (no change, actually)
``` | Inconsistent behavior on java's for-each | [
"",
"java",
"foreach",
""
] |
I'm starting to use more and more jquery. I'm working with dialogs, and each dialog (including javascript) is taking upwards of 20-30 lines of code. There's a few pages where I'll have over 5 dialogs. This gets ugly fast. I haven't even begun to get into sliding interfaces or calendar controls yet.
I have more of a PHP background... and in these situations i'd be moving things to an "include" file. I can see that working for items such as jquery-dialogs in ASP.NET, but when I start adding jquery features to actual ASP.NET form items.. that won't be an option (as far as I know).
How can I keep the extra javascript and extra floating divs from cluttering up my ASPX files too bad?
I'm prepared to partition the ASPX file into well documented, distinct sections... this just results in a very "tall" file. Any better solutions?
Thanks. | Let's see...
1. Since you are using jQuery, you must know the script src syntax already to include javascript files, so I assume this is not the problem :).
2. For those pesky crazy looking control ID that ASP.NET create...
cache them in a JavaScript global variable at the end of the page... like:
```
<script>
ControlIDs = {
SaveButton = '<%=SaveButton.ClientID%>',
BlahTextBox = '<%=BlahTextBox.ClientID%>'
}
</script>
```
And in your separate jQuery code file, do...
```
$(ControlIDs.SaveButton).Whatever()
```
3. Instead of using the ASP.NET control ID, maybe you want to try using the CSS Class Name as selector in jQuery to get to a particular control (treat class name as control Id), might not be an ideal idea, but it could work.
Any of these should allow you to do some degree of Javascript separation. | You could put the javascript code into separate js file(s). You then reference the js file(s) in your page. | ASP.NET - What is the best way to keep jquery from cluttering up my ASPX files? | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
I need to select one row, multiple rows or a cell in Ultragrid to copy from the grid. How can this be accomplish? | Your question isn't very specific, but if you want to get or set the selected row, you can use the .Selected property on the row. You can also use:
```
_yourGrid.DisplayLayout.ActiveRow = whateverRowYouWantSelected
```
For multiple selection, you can use
```
_yourGrid.DisplayLayout.SelectedRows
``` | select the "Feature Picker" of ultragrid designer dialog and expand the "Selection" node.
you should be able to configure the cell, row, column selection the way that you want. Also you can enable either single or multiple rows selection. | How can I select row or rows or cell in Infragistic UltraGrid? | [
"",
"c#",
"infragistics",
"ultrawingrid",
""
] |
Sample code:
```
function TestClass() {
this.init = function() {
this.updateHeader(); // <-- error line
};
this.updateHeader = function() {
console.log("Works");
};
};
var test = new TestClass();
$(document).ready(test.init);
```
When I run that in Firefox 3.5, Firebug gives me an error, saying that this.updateHeader is not a valid function. I'm a Java/PHP programmer and having some trouble understanding the Javascript OO-model. What am I doing wrong?
It does work if I replace the $(document).ready-line with simply test.init(), but I don't want that. | By passing the function `test.init` directly to the `ready()` function, you are registering `test.init` as a callback function. jQuery (which, judging from your syntax, you're using) will use the callback function that it is given and **apply it in the context of `document`**. This means that the `this` keyword will refer to the `document`.
What you should do to avoid this, as suggested, is use an anonymous function (closure) that will call the function you are referring to:
```
$(document).ready(function() {
test.init();
});
```
Using the `function() { }` syntax to define closures to be set as callback functions is a common pattern in Javascript. | Supplying test.init to the document ready function is really feeding it a function pointer to the init function in test.
Essentially it is ripping out the init function and executing it in the scope of the document ready function.
If you ran it as $(document).ready(function () { test.init(); } ); (As Patrick stated) it will execute in the proper scope. | Javascript this does not point to right object | [
"",
"javascript",
"class",
"oop",
""
] |
I've been running into some problems concerning a SqlTransaction I'm using in my code. During my Googling I see many people using a using statement with a SqlTransaction.
What is the benefit and/or difference of using this type of statement with a SqlTransaction?
```
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
```
Currently my code looks like this:
```
SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"]);
cn.Open();
SqlTransaction tr = cn.BeginTransaction();
try
{
//some code
tr.Commit();
cn.Close();
}
catch(Exception ex)
{
tr.Rollback();
cn.Close();
throw ex;
}
```
What is the advantage of one way over the other? | A `using` statement should be used every time you create an instance of a class that implements `IDisposable` *within the scope of a block*. It ensures that the `Dispose()` method will be called on that instance, whether or not an exception is thrown.
In particular, your code only catches managed exceptions, then destroys the stack frame by throwing a new exception instead of rethrowing the existing one.
The correct way to do it is:
```
using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"])) {
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction()) {
//some code
tr.Commit();
}
}
```
Note that if your class has instance members of types that implement `IDisposable`, then your class must implement `IDisposable` itself, and dispose of those members during its own `Dispose()` call. | The reason for this is that the SqlTransaction object will roll back in its Dispose() method if it was not explicitly committed (e.g. if an exception is thrown). In other words, it has the same effect as your code, just a little bit cleaner. | Why use a using statement with a SqlTransaction? | [
"",
"c#",
"using-statement",
"sqltransaction",
"system.data",
"system.data.sqlclient",
""
] |
***Table1***
...
LogEntryID `*PrimaryKey*`
Value
ThresholdID - - - Link to the appropriate threshold being applied to this log entry.
...
***Table2***
...
ThresholdID `*PrimaryKey*`
Threshold
...
All fields are integers.
The "..." thingies are there to show that these tables hold a lot more imformation than just this. They are set up this way for a reason, and I can't change it at this point.
I need write a SQL statement to select every record from ***Table1*** where the Value field in that particular log record is less than the Threshold field in the linked record of ***Table2***.
I'm newish to SQL, so I know this is a basic question.
If anyone can show me how this SQL statement would be structured, it would be greatly appreciated. | ```
SELECT T1.*
FROM Table1 T1
JOIN Table2 T2 ON T2.ThresholdID = T1.ThresholdID
WHERE T2.Threshold > T1.Value
``` | ```
SELECT * FROM Table1
JOIN Table2
ON table1.ThresholdID = table2.ThresholdID --(assuming table 2 holds the same value to link them together)
WHERE
value < thresholdvalue
```
A 'JOIN' connects 2 tables based on the 'ON' clause (which can be multipart, using 'AND' and 'OR')
If you have 3 entries in table 2 which share table1's primary key (a one-to-many association) you will receive 3 rows in your result set.
for the tables below, for example:
```
Table 1:
Key Value
1 Hi
2 Bye
Table 2:
Table1Key 2nd_word
1 You
1 fellow
1 friend
2 now
```
this query:
SELECT \* FROM Table1
JOIN Table2
on table1.key = table2.table1key
gets this result set:
```
Key Value Table1Key 2nd_word
1 Hi 1 You
1 Hi 1 fellow
1 Hi 1 friend
2 Bye 2 now
```
Note that JOIN will only return results when there is a match in the 2nd table, it will not return a result if there is no match. You can LEFT JOIN for that (all fields from the second table will be NULL).
JOINs can also be strung together, the result from the previous JOIN is used in place of the original table. | How do I Write a SQL Query With a Condition Involving a Second Table? | [
"",
"sql",
"join",
"conditional-statements",
""
] |
```
update auditdata set TATCallType='12',TATCallUnit='1' from auditdata auditdata
inner join Auditdata_sms_12 a_sns
on auditdata.ID = a_sns.id
```
when I above query it takes more than 10 minutes to execute.
what wrong in this
`Auditdata.ID` is primary key..
if i run Update command is that also update the indexes???
is this reason of update getting is slow | Looking at your comment, main table contains less rows than temp table.
Try using EXISTS clause (or in some sense, reduce the comparison to less number of rows (i.e. 1500000)
```
update auditdata set TATCallType='12',TATCallUnit='1'
from auditdata auditdata
WHERE EXISTS
(SELECT id from Auditdata_sms_12 a_sns WHERE a_sns.id = auditdata.ID)
```
The idea is to limit the comparisons.
EDIT: AuditdataSMS12 should have the index on ID to be able to get the row quickly. That is the table you are actually looking up for a given ID. | There are a couple things at play here.
First, the SQL statement looks broken. The "FROM" clause in an update is designed to be used as a JOIN'd update. Since you're updating rows with hard-coded values, there's no need to do that.
Secondly, and more esoterically, if the indexes are all correct as you say they are, then perhaps you're dealing with a slow disk I/O for either the initial writes OR the transaction log area (undo in Oracle, logs in SQL Server, etc.).
As a sanity check I'd do two things. One, only update rows that do not already have the conditions set. Many DBMS products will happily perform physical disk I/O for a row that doesn't change (although many don't). Try it with the limit.
Two, apply the update in smaller batches. This can really help with log contention and with slower disks.
So, something like the following to initially try:
```
UPDATE auditdata
SET TATCallType = '12'
, TATCallUnit = '1'
FROM auditdata
WHERE TATCallType <> '12'
AND TATCallUnit <> '1'
AND EXISTS( SELECT *
FROM Auditdata_sms_12 a_sns
WHERE a_sns.id = auditdata.ID )
```
If you want to do batches, in SQL Server it's pretty easy:
```
SET ROWCOUNT 2000
UPDATE ...
(run continually in a loop via T-SQL or by hand until @@ROWCOUNT = 0)
SET ROWCOUNT 0
``` | Slow update (primary key) | [
"",
"sql",
"performance",
"primary-key",
"sql-update",
""
] |
(this is java) I have an oval, representing a unit. I want the colour of the oval to represent the unit's health. So a perfectly healthy unit will be all green. and with the unit's health decreasing the oval starts filling with red from the bottom. so, on 50% health the oval would be red in bottom half and green in the top half, and fully red when the unit's dead.
I'm sure the solution here must be obvious and trivial , but I just can't see it.
thanks a lot | You can draw a red oval in the background, then draw a green intersection of an oval and a rectangle, where the rectangle starts below the oval, then moves further to the top to reveal more of the red oval beneath.
You might like to read up on how to construct complex shapes out of primitives [here](http://v1.dione.zcu.cz/java/docs/tutorial/2d/advanced/complexshapes.html) | Override the paint method something like this:
```
public void paint(Graphics graphics)
{
super.paint(graphics);
Rectangle originalClipBounds = graphics.getClipBounds();
try
{
graphics.clipRect(100, 100, 100, 25);
graphics.setColor(Color.RED);
graphics.fillOval(100, 100, 100, 100);
}
finally
{
graphics.setClip(originalClipBounds);
}
try
{
graphics.clipRect(100, 125, 100, 75);
graphics.setColor(Color.BLUE);
graphics.fillOval(100, 100, 100, 100);
}
finally
{
graphics.setClip(originalClipBounds);
}
}
```
Might want to enhance it with some *double buffering* but you get the gist. | java graphics - a shape with two colours | [
"",
"java",
"graphics",
""
] |
Is it possible to change environment variables of current process?
More specifically in a python script I want to change `LD_LIBRARY_PATH` so that on import of a module 'x' which depends on some `xyz.so`, `xyz.so` is taken from my given path in LD\_LIBRARY\_PATH
is there any other way to dynamically change path from where library is loaded?
**Edit**: I think I need to mention that I have already tried thing like
os.environ["LD\_LIBRARY\_PATH"] = mypath
os.putenv('LD\_LIBRARY\_PATH', mypath)
but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD\_LIBRARY\_PATH
**Edit2**, so question is can we change environment or something so the library loader sees it and loads from there? | The reason
```
os.environ["LD_LIBRARY_PATH"] = ...
```
doesn't work is simple: this environment variable controls behavior of the dynamic loader (`ld-linux.so.2` on Linux, `ld.so.1` on Solaris), but the loader only looks at `LD_LIBRARY_PATH` once at process startup. Changing the value of `LD_LIBRARY_PATH` in the current process *after* that point has no effect (just as the answer to [this](https://stackoverflow.com/questions/856116/changing-ldlibrarypath-at-runtime-for-ctypes) question says).
You do have some options:
A. If you know that you are going to need `xyz.so` from `/some/path`, and control the execution of python script from the start, then simply set `LD_LIBRARY_PATH` to your liking (after checking that it is not already so set), and re-execute yourself. This is what `Java` does.
B. You can import `/some/path/xyz.so` via its absolute path *before* importing `x.so`. When you then import `x.so`, the loader will discover that it has already loaded `xyz.so`, and will use the already loaded module instead of searching for it again.
C. If you build `x.so` yourself, you can add `-Wl,-rpath=/some/path` to its link line, and then importing `x.so` will cause the loader to look for dependent modules in `/some/path`. | Based on the answer from Employed Russian, this is what works for me
```
oracle_libs = os.environ['ORACLE_HOME']+"/lib/"
rerun = True
if not 'LD_LIBRARY_PATH' in os.environ:
os.environ['LD_LIBRARY_PATH'] = ":"+oracle_libs
elif not oracle_libs in os.environ.get('LD_LIBRARY_PATH'):
os.environ['LD_LIBRARY_PATH'] += ":"+oracle_libs
else:
rerun = False
if rerun:
os.execve(os.path.realpath(__file__), sys.argv, os.environ)
``` | Change current process environment's LD_LIBRARY_PATH | [
"",
"python",
"shared-libraries",
"environment-variables",
""
] |
I have a table `user_name` with 3 fields, `id, Name, Email` (`id` is `auto_increment` field). I want to execute the following query in PHP, but its not returning any result.
```
INSERT INTO user_name (Name, Email) VALUES ('Example', 'example@xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';
```
When I am executing the above query in PHP as below then its not returning anything.
```
$_SQL="INSERT INTO user_name (Name,Email) VALUES ('Example', 'example@xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';";
$result_last_id = @mysql_query($_SQL);
$rs_insert = mysql_fetch_array($result_last_id);
$new_userid = $rs_insert['userid'];
```
Can anyone please tell me how to execute both queries into one. | Give a look to the [`mysql_insert_id()`](http://php.net/manual/en/function.mysql-insert-id.php) function.
```
mysql_query($insertStatementOnly);
$new_userid = mysql_insert_id();
``` | It appears you don't need to execute multiple queries, but I included how to do it below. What you want is the last inserted id, which you get from [`mysql_insert_id`](https://www.php.net/manual/en/function.mysql-insert-id.php).
### To execute multiple queries
From comments on documentation of [`mysql_query`](http://se.php.net/manual/en/function.mysql-query.php):
> The documentation claims that "multiple queries are not supported".
>
> However, multiple queries seem to be supported. You just have to pass flag 65536 as mysql\_connect's 5 parameter (client\_flags). This value is defined in /usr/include/mysql/mysql\_com.h:
> `#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */`
>
> Executed with multiple queries at once, the mysql\_query function will return a result only for the first query. The other queries will be executed as well, but you won't have a result for them.
Alternatively, have a look at the `mysqli` library, which has a [`multi_query` method](https://www.php.net/mysqli.multi-query). | How to execute SELECT and INSERT in single query with PHP/MYSQL? | [
"",
"php",
"mysql",
"logic",
"identity",
""
] |
I always come to a halt when creating classes. I'm fairly intermediate to architecture so bear with me. Here's my dilemma. I come to a point eventually in a class where I have to ask myself, "Does this method need parameters when I can just get what I need from the class's property or private backing field?".
Now for public methods, obviously you should most likely have parameters because someone's going to be consuming your class and using these methods whether they're in an instance class or static class. That debate is not about public methods because that is obvious to me. That if you have a public method(s) inside your class, even though lets say you can get one of the values you need from a property or private field in that class instead of requiring a param to that method and using the param, you should still require params and use the params or at least don't count them out when you can specify some params. At least this is how I view public methods because who knows how someone else might use that method and they need to know what needs to be passed and they need to pass the actual data to the method as they are outside your class.
The issue comes when for example I'm creating and using private methods or something of that sort. Lets say I create a custom control (.cs). Its job is to run a bunch of methods that I've broken out the logic for this control and create some strings of HTML to output to the browser. Well, I create a property that is public so that whoever is using this control can feed it a certain object. And that certain object is what half of the methods in my class use to help generate that HTML. Because it's a property, any of the methods in my custom class can use it. So it completely bypasses any need to create parameters in some of those methods because I can just get it form the property. But then I get to a point where I'm creating an awful lot of parameterless methods because I'm getting objects from the backing fields or combination of backing fields and properties. Or I might be just getting them from a few propewhen I am able to get what I need other ways inside this class? But then something says to you no, that's bad man, you do need parameters once in a while dude...at least a combo of parameters and using some backing fields or properties in your method, etc. but don't always discount parameters even if those params might be some internals passed to it (fields or properties). But then again if I'm gonna be passing internals as params where's the fine line between just accessing and using those fields or properties not through the method as params but directly inside the method itself.
But that bothers me because then I question why I need method parameters in cases where I can get the value elsewhere.
Can someone explain the fine line here and help me come to a conclusion on the line between using a lot of backing fields in your methods or properties rather than some params you specify in the methods..even though some of those params may still be passed a value from a backing field or property when another method calls it?
I hope this makes any inkling of sense but I can't be the only one who comes across this dilemma. Maybe I'm the only one who thinks about this sh\*\* and I over think I don't know. But the main problem I have personally with OOP is that there are so many damn ways to get what you need (constructor, property, backing field, method). | less coffee, fewer words ;-)
# to summarize
when to use parameters in methods?
# short answer
when the information needed is *not* available already in the object, in accordance with the Don't Repeat Yourself principle
parameterless methods are fine, there's no need to tell an object something that it already knows | Good answer by Steve.
Just to add in C# 4.0 you can use the feature of default parameter as well. This is useful in some cases, specially utility classes. I have a method like this in my OracleHelper class
```
ExecuteReaderNoParam(OracleConnection conn, string cmdText, OracleTransaction trans, CommmandType cmdType)
```
Most of the callers do not need to provide a transaction and commandtype. Using default parameters I can write the method as
```
ExecuteReaderNoParam(OracleConnection conn, string cmdText, OracleTransaction trans=null, CommmandType cmdType = CommandType.StoredProcedure)
```
The the caller can just call
```
OracleConnection connection = new OracleConnection(connectionString);
OracleHelper.ExecuteReaderNoParam(conn, "SP_GET_ALL_STATUS");
``` | Method Parameter Dilemma | [
"",
"c#",
""
] |
I'm trying to write to the event viewer in my c# code, but I'm getting the wonderful "Object reference not set to an instance of an object" message. I'd appreciate some help with this code, either what's wrong with it or even a better way to do it. Here's what I have for writing to the event log:
```
private void WriteToEventLog(string message)
{
string cs = "QualityDocHandler";
EventLog elog = new EventLog();
if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, cs);
}
elog.Source = cs;
elog.EnableRaisingEvents = true;
elog.WriteEntry(message);
}
```
And here's where I'm trying to call it:
```
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
try
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
catch (Exception e)
{
WriteToEventLog(e.ToString());
return null;
}
}
``` | The problem is probably that you are trying to create an event source in a log that doesn't exist. You need to specify the "Application" log.
Try changing it to:
```
if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, "Application");
EventLog.WriteEntry(cs, message, EventLogEntryType.Error);
```
Also: Inside of sharepoint, if the app is running as logged in user(via windows auth or delegation), the user won't have access to create the event source. If this is the case, one trick is to create the event using a ThreadPool thread, which when created, will have the security context of the user the App Pool is running as. | Here's how I implemented Event logging. I created a generic ILogger interface so I can swap in different logging mechanisms:
```
interface ILogger
{
void Debug(string text);
void Warn(string text);
void Error(string text);
void Error(string text, Exception ex);
}
```
My implementation class is very simple:
```
class EventLogger : ILogger
{
public void Debug(string text)
{
EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Information);
}
public void Warn(string text)
{
EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Warning);
}
public void Error(string text)
{
EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Error);
}
public void Error(string text, Exception ex)
{
Error(text);
Error(ex.StackTrace);
}
}
```
Note that I do not instantiate EventLog. To use my logger class I just have the following reference (you could have this returned by a static factory method):
```
private static readonly ILogger log = new EventLogger();
```
And the actual usage is like this:
```
try
{
// business logic
}
catch (Exception ex)
{
log.Error("Exception in MyMethodName()", ex);
}
``` | c# writing to the event viewer | [
"",
"c#",
"event-log",
""
] |
I have a table like this
```
<tr>
<td>No.</td>
<td>Username</td>
<td>Password</td>
<td>Valid Until</td>
<td>Delete</td>
<td>Edit</td>
</tr>
<tr>
<td>1</td>
<td id="1">
<div class="1u" style="display: none;">Username</div>
<input type="text" class="inputTxt" value="Username" style="display: block;"/>
</td>
<td id="1">
<div class="1p" style="display: none;">Password</div>
<input type="text" class="inputTxt" value="Password" style="display: block;"/></td>
<td>18 Jul 09</td>
<td><button value="1" class="deleteThis">x</button></td>
<td class="editRow">Edit</td>
</tr>
```
When edit is clicked i run this function this replaces the text with input field, so what i want is to cancel this back to text when somewhere else is click instead of save.
```
$('.editRow').click(function() {
var row = $(this).parent('tr');
row.find('.1u').slideUp('fast');
row.find('.1p').slideUp('fast');
row.find('.inputTxt').slideDown('fast');
}).blur(function() {
row.find('.inputTxt').slideUp('fast');
row.find('.1u').slideDown('fast');
row.find('.1p').slideDown('fast');
});
```
with this function text changes to input fields but input fields doesnt change back to text when i click somewhere else.
Thank You. | Just edited my function because the plugin didn't suite well for my application
```
$('.editRow').live('click', function() {
var row = $(this).parent('td').parent('tr');
row.find('.1u').slideUp('fast');
row.find('.1p').slideUp('fast');
row.find('.inputTxt').slideDown('fast');
$(this).parent('td').empty().append('<a href=# class=cancel>Cancel</a> / <a href=# class=save>Save</a>');
});
``` | There's a [nice plugin](http://www.appelsiini.net/projects/jeditable/default.html) for this | edit in place | [
"",
"javascript",
"jquery",
""
] |
When, if ever, can `delete` and `free` be used interchangeably in C++?
My concern is as follows: Say there is an incorrect mixup in the use of `malloc`/ `free` and
`new`/ `delete` (not to mention `new[]`/ `delete[]`). However `delete` and `free` doing the same thing;
Fortuitously so this goes uncaught in testing. Later this may lead to a crash in production.
How can I enforce some kind of check to prevent this? Can I be warned if the two are mixed up?
If not at compile time, perhaps some code instrumentation at run time? How would I approach
this?
The intention of this question is to find ways to **avoid** inadvertent mix up in the usages. | To answer the second question, if you control both `malloc`/`free` and `operator new`/`delete`, you can stash extra information to associate with pointers returned by both that tell you how they were allocated. When a pointer is passed to `free` or `operator delete`, check to see that it was allocated by the appropriate function. If not, assert or raise an exception or do whatever it is you do to report the mismatch.
Usually this is done by allocating extra memory, e.g., given `malloc(size)` or `operator new(size)`, you allocate `size + additional space` and shove extra information in there. | The easy way to not get them mixed up is never to use malloc(), then you will never be tempted to call free(). The infrastructure to create to avoid this problem is called "code review", though in this case a quick "grep malloc(" or "grep free(" on the codebase will probably suffice. | How to prevent inadvertently using delete and free interchangeably in C++? | [
"",
"c++",
"memory-management",
"free",
""
] |
Should it be possible for gc.get\_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?
If so how would I start trying to identify the cause for this object not being garbage collected?
Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get\_referrers().
**Edit: Solved**. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get\_referrers wasn't picking it up. | Yes: <http://docs.python.org/library/weakref.html>
A weak reference won't be keeping the object alive.
The get\_referrers() function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.
What makes you think the object isn't getting collected? Also, have you tried gc.collect()? | It might also be the case that a reference was leaked by a buggy C extension, IMHO you will not see the referer, yet still the refcount does not go down to 0. You might want to check the return value of `sys.getrefcount`. | Python object has no referrers but still accessible via a weakref? | [
"",
"python",
"garbage-collection",
"cpython",
""
] |
I have a thread to monitor serial port using select system call, the run function of the thread is as follows:
```
void <ProtocolClass>::run()
{
int fd = mPort->GetFileDescriptor();
fd_set readfs;
int maxfd=fd+1;
int res;
struct timeval Timeout;
Timeout.tv_usec=0;
Timeout.tv_sec=3;
//BYTE ack_message_frame[ACKNOWLEDGE_FRAME_SIZE];
while(true)
{
usleep(10);
FD_ZERO(&readfs);
FD_SET(fd,&readfs);
res=select(maxfd,&readfs,NULL,NULL,NULL);
if(res<0)
perror("\nselect failed");
else if( res==0)
puts("TIMEOUT");
else if(FD_ISSET(fd,&readfs))
{//IF INPUT RECEIVED
qDebug("************RECEIVED DATA****************");
FlushBuf();
qDebug("\nReading data into a read buffer");
int bytes_read=mPort->ReadPort(mBuf,1000);
mFrameReceived=false;
for(int i=0;i<bytes_read;i++)
{
qDebug("%x",mBuf[i]);
}
//if complete frame has been received, write the acknowledge message frame to the port.
if(bytes_read>0)
{
qDebug("\nAbout to Process Received bytes");
ProcessReceivedBytes(mBuf,bytes_read);
qDebug("\n Processed Received bytes");
if(mFrameReceived)
{
int no_bytes=mPort->WritePort(mAcknowledgeMessage,ACKNOWLEDGE_FRAME_SIZE);
}//if frame received
}//if bytes read > 0
} //if input received
}//end while
}
```
The problem is when I exit from this thread, using
```
delete <protocolclass>::instance();
```
the program crashes with a glibc error of malloc memory corruption. On checking the core with gdb it was found the when exiting the thread it was processing the data and thus the error. The destructor of the protocol class looks as follows:
```
<ProtocolClass>::~<ProtocolClass>()
{
delete [] mpTrackInfo; //delete data
wait();
mPort->ClosePort();
s_instance = NULL; //static instance of singleton
delete mPort;
}
```
Is this due to select? Do the semantics for destroying objects change when select is involved? Can someone suggest a clean way to destroy threads involving select call.
Thanks | I'm not sure what threading library you use, but you should probably signal the thread in one way or another that it should exit, rather than killing it.
The most simple way would be to keep a boolean that is set true when the thread should exit, and use a timeout on the select() call to check it periodically.
```
ProtocolClass::StopThread ()
{
kill_me = true;
// Wait for thread to die
Join();
}
ProtocolClass::run ()
{
struct timeval tv;
...
while (!kill_me) {
...
tv.tv_sec = 1;
tv.tv_usec = 0;
res = select (maxfd, &readfds, NULL, NULL, &tv);
if (res < 0) {
// Handle error
}
else if (res != 0) {
...
}
}
```
You could also set up a pipe and include it in readfds, and then just write something to it from another thread. That would avoid waking up every second and bring down the thread without delay.
Also, you should of course never use a boolean variable like that without some kind of lock, ... | Are the threads still looking at mpTrackInfo after you delete it?
Not seeing the code it is hard.
But Iwould think that the first thing the destructor should do is wait for any threads to die (preferably with some form of join() to make sure they are all accounted for). Once they are dead you can start cleaning up the data. | Closing a thread with select() system call statement? | [
"",
"c++",
"multithreading",
"qt",
""
] |
I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:
I want to read & write lines to new file:
```
ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
```
if i print this to the screen i get all my lines done nicely:
```
0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
```
If i write it to ofile i end up missing some 15 lines:
```
0,6100,948,8332
0,26100,568,8636
0,11130,555
```
I would appreciate if someone could point out to me what is it that i don´t understand?
Reg,
Jaani | You should be calling ofile.close() according to [python docs](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files).
I'm not sure that writes are fully flushed out to a file without an explicit close.
Also, as SilentGhost mentioned, check for empty lines in your input file.
And as mentioned by stefanw below, that "if.. break" statement isn't necessary in a for in. | ```
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
continue #break stops the loop, you should use continue
ofile.write(line)
``` | writeline problem in python | [
"",
"python",
""
] |
I'm working on some code that is normalizing a lot of data. At the end of processing, a number of key="value" pairs is written out to a file.
The "value" part could be anything, so at the point of output the values must have any embedded quotes escaped as \".
Right now, I'm using the following:
```
outstream << boost::regex_replace(src, rxquotesearch, quoterepl);
// (where rxquotesearch is boost::regex("\"") and quoterepl is "\\\\\"")
```
However, gprof shows I'm spending most of my execution time in this method, since I have to call it for every value for every line.
I'm curious if there is a faster way than this. I can't use std::replace since I'm replacing one character with two.
Thanks for any advice. | If speed is a concern you should use a hand-written function to do this. Notice the use of `reserve()` to try to keep memory (re)allocation to a minimum.
```
string escape_quotes(const string &before)
{
string after;
after.reserve(before.length() + 4);
for (string::size_type i = 0; i < before.length(); ++i) {
switch (before[i]) {
case '"':
case '\\':
after += '\\';
// Fall through.
default:
after += before[i];
}
}
return after;
}
``` | I would not take the source string and build a new output string at all.
I would iterate through the source string and print each character, if the character is a quote then just print a "\" before printing it. | Fastest quote-escaping implementation? | [
"",
"c++",
"string",
"replace",
"escaping",
""
] |
How does a virtual event work? How would you override it? How would that work? And in what cases would you do that?
Would it for example be an ok replacement for protected OnEvent methods? So that inheriting classes could just override the event and raise it directly? Or would that be wrong or just not work?
The MSDN says this about it:
> An event can be marked as a virtual event by using the virtual keyword. This enables derived classes to override the event behavior by using the override keyword. An event overriding a virtual event can also be sealed, which specifies that for derived classes it is no longer virtual.
But that didn't make me much wiser. The sealed stuff is obvious though.
***Note:*** I've seen the [How virtual events work in C# ?](https://stackoverflow.com/questions/714893/how-virtual-events-work-in-c) question, but it wasn't really about how virtual events work. Rather it was how that person got the result he got from using them. Tried to figure out what virtual events were from his example and the answers, but couldn't really make sense out of it. | A virtual event is simply one which *can* be overridden in a derived class.
Are you happy with the concept of a virtual property, with a getter and setter which can be overridden? If so, you can think of a virtual event in exactly the same way: instead of a getter and setter, there's an "add" operation and a "remove" operation. These can be virtual, so handled polymorphically. You implement them the same way you implement any other virtual/overridden member.
Example:
```
using System;
class Base
{
public virtual event EventHandler Foo
{
add
{
Console.WriteLine("Base Foo.add called");
}
remove
{
Console.WriteLine("Base Foo.remove called");
}
}
}
class Derived : Base
{
public override event EventHandler Foo
{
add
{
Console.WriteLine("Derived Foo.add called");
}
remove
{
Console.WriteLine("Derived Foo.remove called");
}
}
}
class Test
{
static void Main()
{
Base x = new Derived();
x.Foo += (sender, args) => {};
}
}
```
Note that the event itself is not responsible for what happens when it is raised - just the add/remove side. (In C#, anyway; the CLR itself has the notion of raising, but we'll ignore that for the moment.)
You may also want to read [my article on events](http://pobox.com/~skeet/csharp/events.html) if you're slightly hazy on the difference between an event and a delegate.
Personally I find it *very* rare that I want a virtual event. | Also note that in C# a derived class is not able to fire the event purely defined in base class (no matter what modifier it has). So we either need have a new or overriding event for the derived class and in most cases an overriding one is preferred if the same event is meant to be fired. | C#: What are virtual events and how can they be used? | [
"",
"c#",
"events",
"inheritance",
"virtual",
""
] |
Below query is showing error
Please help :
```
DoCmd.RunSQL ("insert into tbltesting (IsDiff)values ('Yes') where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'")
``` | I'm going to guess that empid and testid are numeric, and you're setting them off like they're strings in the SQL statement. Remove the single-quotes that you've wrapped around your field references.
```
DoCmd.RunSQL (" Update tbltesting set IsDiff ='Yes' where empid= " & Me.txtEmpId.Value & " and testid= " & Me.txtAutoNumber.Value & ";")
``` | Well, one problem is that your query is vulnerable to sql injection. Never never **NEVER** concatenate values from user inputs directly into a query string. Instead, use an ADO.Command object along with real query parameters or parameterized SQL executed with DAO or similar.
[Here](https://stackoverflow.com/questions/1125380/dlookup-problem/1125874#1125874) is an example. | vba sql problem | [
"",
"sql",
"ms-access",
"vba",
""
] |
I am teaching myself, from online tutorials, how to write games in Java. I am using Java Applets to create a Pong game. each paddle is controlled from different keys for 1v1 competition. this works fine if both users are hitting the keys at different times. but when one key is being held down and then another key is held down(ex: holding down on the arrow key, then user 2 holds the 'S' key), the second key overrides the first and the first paddle will stop moving. i'm guessing that i need to use threads but i don't know much about them and i am having trouble understanding how to use/implement them. how would i go about handling the case when two (or more) keys are being held down?
Bonus: like i said i don't know much about threads - i'm assuming i also need one for the ball/puck to be moving around while all else is going on. is the right and if so how do i put a thread on something that takes no input?
Thanks for you help,
DJ | What you usually do is to remember the state of every keypress.
You keep an array of your actions(or an array of all the keys if you want too). A keyDown event results in e.g.
```
boolean actions[12];...
...
public boolean keyDown( Event e, int key ) {
if (key == 'a') {
actions[ACTION_LEFT] = true;
}
..
}
```
And you'll need to catch the keyup event and set the actions to false when the keys are released.
In the movement logic you can just check the states of the keypresses
```
if(actions[ACTION_LEFT] == true)
moveLeft();
if(actions[ACTION_RIGTH] == true)
moveRight();
``` | Usually instead of threads, games use something called the game loop (google it).
<http://en.wikipedia.org/wiki/Game_programming>
The basic idea is
```
Loop
Get all inputs
Get game clock
Update state based on clock and inputs
Update Display
Limit frame rate if you need to
```
Anyway -- instead of getting keyboard events -- you check the keyboard's state at certain points. This code seems to do it for Java
<http://www.gamedev.net/reference/articles/article2439.asp>
It uses events to set variables you look at in your loop. | How do I handle multiple key presses in a Java Applet? | [
"",
"java",
"multithreading",
""
] |
I was curious if anyone knew of a way of monitoring a .Net application's runtime info (what method is being called and such)
and injecting extra code to be run on certain methods from a separate running process.
say i have two applications:
app1.exe that for simplicity's sake could be
```
class Program
{
static void Main(string[] args)
{
while(true){
Somefunc();
}
}
static void Somefunc()
{
Console.WriteLine("Hello World");
}
}
```
and I have a second application that I wish to be able to detect when Somefunc() from application 1 is running and inject its own code,
```
class Program
{
static void Main(string[] args)
{
while(true){
if(App1.SomeFuncIsCalled)
InjectCode();
}
}
static void InjectCode()
{
App1.Console.WriteLine("Hello World Injected");
}
}
```
So The result would be Application one would show
```
Hello World
Hello World Injected
```
I understand its not going to be this simple ( By a long shot )
but I have no idea if it's even possible and if it is where to even start.
Any suggestions ?
I've seen similar done in java, But never in c#.
EDIT:
To clarify, the usage of this would be to add a plugin system to a .Net based game that I do not have access to the source code of. | It might be worth looking into Mono.Cecil for code injection. It won't work online the way you described in your question, but I believe it may do what you want offline (be able to find a given method, add code to it, and write out the modified assembly).
<http://www.codeproject.com/KB/dotnet/MonoCecilChapter1.aspx> | You need to use the [`Profiling API`](http://msdn.microsoft.com/en-us/magazine/cc300553.aspx) to make the second program profile the first one. You can then be notified of any method calls. | How to Inject code in c# method calls from a separate app | [
"",
"c#",
".net",
"aop",
"code-injection",
"runtimemodification",
""
] |
I have been research this all day and I cannot find a solution. I understand the problem of using subclasses and how the compiler wont know what the class will actually be because of the possibility of setting setting it to something else before calling add. I have look everywhere and I still don't know how to fix this problem. I have an abstract class that is a file wrapper. the file wrapper has an arraylist of sheetwrappers. I want the concrete class of excelfile to be able to add excelsheets to its arraylist but I keep getting this error:
The method add(capture#2-of ? extends SheetWrapper) in the type ArrayList is not applicable for the arguments (ExcelSheet)
Here is the necessary code. Only the parts that are involved in the error are pasted here.ExcelSheet is also an abstract class. Any help would be very very appreciated.Thanks!
```
public abstract class FileWrapper {
protected ArrayList<? extends SheetWrapper> sheets;
public class ExcelFile extends FileWrapper {
this.sheets = new ArrayList<ExcelSheet>();
for(int i = 0; i < wb.getNumberOfSheets(); i++)
{
if(ParserTools.isLegitSheet(wb.getSheetAt(i)))
{
this.sheets.add(new ExcelSheet(null)); //ERROR HERE
}
}
``` | Well, you declared a variable as an "`ArrayList` of some elements that extend `SheetWrapper`". This means that you cannot add an instance of `ExcelSheet` to it, since it could actually be an `ArrayList` of some other type that extends `SheetWrapper`.
More precisely speaking, `add()` is not covariant.
If all your code is actually in the same place, then just fill your list *before* assigning it:
```
ArrayList<ExcelSheet> sheets = new ArrayList<ExcelSheet>();
for(int i = 0; i < wb.getNumberOfSheets(); i++)
{
if(ParserTools.isLegitSheet(wb.getSheetAt(i)))
{
sheets.add(new ExcelSheet(null)); //ERROR HERE
}
}
this.sheets = sheets;
```
If you need to do it from different parts of code, just lift that local to be another private or protected field (e.g. `excelSheets`) alongside the inherited `sheets`, and use that. | See the [GenericsFAQ](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#What%20is%20the%20difference%20between%20various%20multi-level%20instantiations?). You want simply:
```
protected List<SheetWrapper> sheets;
```
Note that using the interface type "List" is preferable to the concrete implementation class "ArrayList" for a variable declaration (unless specific methods are needed from that class). | Generic Class Problems! | [
"",
"java",
"generics",
""
] |
Why is the ( i < UniqueWords.Count ) expression valid in the for loop, but returns "CS0019 Operator '<' cannot be applied to operands of type 'int' and 'method group'" error when placed in my if? They are both string arrays, previously declared.
```
for (int i = 0;i<UniqueWords.Count;i++){
Occurrences[i] = Words.Where(x => x.Equals(UniqueWords[i])).Count();
Keywords[i] = UniqueWords[i];
if (i<UniqueURLs.Count) {rURLs[i] = UniqueURLs[i];}
}
```
EDITED to add declarations:
```
List<string> Words = new List<string>();
List<string> URLs = new List<string>();
```
//elements added like so. . . .
```
Words.Add (referringWords); //these are strings
URLs.Add (referringURL);
UniqueWords = Words.Distinct().ToList();
UniqueURLs = URLs.Distinct().ToList();
```
**SOLVED. thank you, parentheses were needed for method .Count() I still do not fully understand why they are not always necessary.**
Jon Skeet, thanks, I guess I don't understand what exactly the declarations are either then? You wanted the actual values assigned? They are pulled from an external source, but are strings.
**I get it! Thanks. (the ()'s at least.)** | don't forget your parens:
```
UniqueWords.Count()
``` | Are you absolutely *sure* they're both string arrays?
Are you sure one isn't a string array, and the other an `IEnumerable<string>`? That would certainly explain it. (The method group in question would be the `Enumerable.Count()` extension method.) If this is the case, you won't then be able to use the indexer within the block, either.
If that's not it, please remove any extraneous code but include the declarations so that we have a short but *complete* program to test against.
In fact, given your edit, they *can't* be declared as string arrays - because you're assigning `List<string>` values to them. I suspect you'll find that `UniqueWords` is declared as `List<string>` or `IList<string>`, but `UniqueURLs` is declared as `IEnumerable<string>`. This may be implicit if you're using `var` though. Hover over the variable name to find out the type - and if `var` is being more of a curse than a blessing, go back to explicitly typing your variables. | "<" operator error | [
"",
"c#",
"operators",
"loops",
"compare",
"method-group",
""
] |
i want to compare xml document. some are 50k+. i'm comparing the OuterXml. is this efficient? is there more effient way? | Depends on what kind of comparison you want.
For instance, if your intention is to just compare the content within two files and get a true/false status , then I would suggest using XmlReader for each of the two files that you want to compare and then parse the nodes. The moment you encounter a difference you can stop parsing.
This is different from using XML document where you have to read the entire document into memory, get the string representation and compare the strings.(For smaller file sizes it does not matter)
Two xml documents could be semantically equivalent, but structure might be different.(In which case your comparison has to be smarter).
If you intend to modify the source document, in case comparison fails/succeeds, then DOM way is preferred (XmlDocument class and its API). | Just comparing the textual representation of your XML will not yield valid results - check this out:
```
<node x="1" y="2" />
```
and
```
<node y="2" x="1" />
```
are identical as far as XML processing goes (order of attributes on a node is irrelevant), but when you compare nothing but text, you'll flag it as a difference.
Microsoft used to have a [XmlDiff](http://msdn.microsoft.com/en-us/library/aa302295.aspx) tool on GotDotNet, but I'm not sure if that's still available somewhere.....
**UPDATE**
XmlDiff seems to be still available - check out this [download link](http://www.microsoft.com/downloads/details.aspx?FamilyID=3471df57-0c08-46b4-894d-f569aa7f7892&DisplayLang=en), as well as this "[Using the XML Diff and Patch Tool in your application](http://msdn.microsoft.com/en-us/library/aa302294.aspx)" link on MSDN.
Marc | Comparing XmlDocument | [
"",
"c#",
"xml",
""
] |
This question is related to [Array of pairs of 3 bit elements](https://stackoverflow.com/questions/1053242/array-of-pairs-of-3-bit-elements)
This array has 52 pairs (about 40 bytes), and I want to find the first pair before the specified one that has it's values different from 0 (used pair).
The obvious solution would be to check each pair < than this one (scan from right to left), but this seems to be very inefficient if there are many unused pairs (set to 0).
This image may explain better the situation:

Pairs 0, 1 and 51 are used.
I want to find the first used pair before 51 (which is 1 here).
I tried tricks like
```
if(*((int *)&array[arrayPos]) == 0) {
arrayPos -= sizeof(int);
pairPos -= ???
}
```
The problem here is that subtracting from *pairPos* is not that simple, because of the 6 bits/pair, so I ended with a lookup table based on some relations between *pairPos* and *arrayPos*, and all this made the solution perform like the trivial one.
Is there any way to make this lookup faster ? Another problem is that there is only 1 unused byte... maybe I can make space for another 4. If there were at least 7 I could use a bitmap of the array and it would be much faster to skip over unused pairs. | The best solution I found was:
1. make the items 1 byte (not 6 bits than before) - thanks Skizz
2. use a bitmap to see which item is the nearest on the left. This was much faster than going back with the technique described by djna.
The speed improvements are impressive:
in one test case, from 13s it's now 6.5s
in another one, from 7.4s to 3.6s
The performance has doubled :D
Thanks again for your answers! | Can you say anything about the adjacent byte values that represent an empty pair?
I want to propose looking at the bytes rather than the bits.
Any given byte if it is to be the left hand contributer of a pair of empty 6 bits chars must fit a particular bit mask whose value depends upon his postion. ?? ?? 00 00 or ?? 00 00 00 or whatever. You can consider each byte in turn for their candidacy as a left most byte. A simple lookup table of which mask to use is possible.
Hence we don't actually have to pull out the 6bit chars before considering them.
Can we do better, having discarded a byte as a candidate, can we now skip the one to left?
In the case where our mask was 00 00 00 00 if that fails then the our neighbour to the left, yes if the first bit is set.
Does that actually make things any faster? | Finding the nearest used index before a specified index in an array (Fast) | [
"",
"c++",
"optimization",
"memory",
"performance",
""
] |
Ok, you guys were quick and helpful last time so I'm going back to the well ;)
Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.
I've got my date value being stored in my Memory class:
```
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
```
and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:
```
memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
```
But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.
EDIT: FULL SOURCE BELOW
```
import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
``` | ```
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
```
I think that you are either getting import errors for memory or your are getting an import error for datetime
if Memory is in another .py file, e.g otherpyfile.py, you will need to do `from otherpyfile import Memory` and then use it that way
if its a datetime issue then you will need to `import datetime`. Your first answer had a mismatch of quotes so sorted that. I sorted your middle one so that if you import datetime
```
memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20'")
memories = Memory.all().filter("date=", datetime.datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
memories = Memory.all().filter("date=", self.request.get('date'))
```
The appengine error screen isn't always helpful so have a look at the logs that are being thrown in the command prompt. If you see that error it might be worth dumping the short stacktrace it does so I can try help you further. | You're trying to use GQL syntax with non-GQL Query objects. Your options are:
1. Use the Query object and pass in a datetime.date object: `q = Memory.all().filter("date =", datetime.date.today())`
2. Use a GqlQuery and use the DATE syntax: `q = db.GqlQuery("SELECT * FROM Memory WHERE date = DATE(2007, 07, 20)")`
3. Use a GqlQuery and pass in a datetime.date object: `q = db.GqlQuery("SELECT * FROM Memory WHERE date = :1", datetime.date.today())` | GQL Query on date equality in Python | [
"",
"python",
"google-app-engine",
""
] |
I'm using the jquery autocomplete plugin from pengoworks: <http://www.pengoworks.com/workshop/jquery/autocomplete_docs.txt>
In the function called upon an entry being selected, I want to find out the name (id) of the input element. (Because the callback is going to be used for multiple autocompletes.)
Code looks like this:
```
myCallback = function(o) {
// I want to refer to "myInput" here - but how?
}
setup = function() {
$('#myInput').autocomplete('blah.php', {onItemSelect: myCallback});
}
``` | ```
myCallback = function(li, $input) {
// I need to refer to the appropriate "myXxxInput" here
alert($input.attr('id'));
}
setup = function() {
setupInput($('#myFirstInput'));
setupInput($('#mySecondInput'));
}
function setupInput($input) {
$input.autocomplete('blah.php', {onItemSelect: function(li) {
myCallback(li, $input);} });
}
```
Thanks to Dylan Verheul (an author of the autocomplete) for this solution | Try to pass the id of the in the extraParams to the server side:
```
$('#myInput').autocomplete('blah.php', {onItemSelect: myCallback}, extraParams: {name: $(this).attr('id')} );
```
or by adding some id to the blah.php?id=someid.
and then in the results array to send it back to the callback function. | How do I find the id of a jquery autocomplete input from within the onItemSelect callback? | [
"",
"javascript",
"jquery",
"autocomplete",
""
] |
Is there a library of generic collection algorithms for .NET? I would like to be able to write something like this:
```
IList<T> items = GetItemsFromSomeWhere();
Algorithms<T>.Sort(items);
//
// ....
//
T item = GetItemSomwHow();
int i = Algorithms<T>.IndexOf(items, item);
```
Note, that `items` is not `List<T>`, otherwise I could simply use the `List<T>.Sort` and `List<T>.BinarySearch` methods.
Of course, I can implement them myself, I just do not want to reinvent the wheel.
I would also like the implementation to be efficient.
P.S.
Please, do not advise on which collections to use. I am perfectly aware of the `Array` or `List<T>` abilities. What I need is a library of algorithms to work on any `IList<T>` based collection.
**EDIT:**
Found what I needed - see my own answer. | After doing some research I have found the [PowerCollections](http://www.codeplex.com/PowerCollections) library from `Wintellect`.
Aside from supplying various collections it provides a static `Algorithms` class with quite a few algorithms, including `BinarySearch<T>` and `SortInPlace<T>`, which expect **any** `IList<T>`. | [`System.Linq.Enumerable` class](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx) does a bunch of good stuff. Admittedly, it does miss some stuff but it's applicable nevertheless. | Generic collection algorithms in C# | [
"",
"c#",
".net",
"algorithm",
"generics",
""
] |
I have a map which displays some info. By default, labels on the map are turned off. There is an image button which has a turned-off image associated with it when you the labels are off and a turned-on image associated with it when you turn the labels on. I have the code working, but I wanted a better reason as to why it works this way. Here is a snippet of code.
If I declare a class-level boolean variable showLabels like:
```
private bool showLabels = false;
```
and then have the following code:
```
if(showLabels == false)
{
showLabels = true;
imgShowLabels.ImageUrl = "label-on.png";
}
else
{
showLabels = false;
imgShowLabels.ImageUrl = "label-off.png";
}
```
When I run it, the map comes up with the labels not shown by default. When I click on the Show Labels button, the variable showLabels becomes true and the image is changed to label-on.png, but when I click it again, the showLabels variable is reset to false, so nothing happens.
So what I did was change it from:
```
private bool showLabels = false;
```
to
```
private static bool showLabels = false;
```
and it is working this way.
Is this the correct way to handle this type of scenario?
In the class level, I put the property:
```
public bool ShowLabels
{
get { return (bool)ViewState["ShowLabels"]; }
set { ViewState["ShowLabels"] = value; }
}
```
In the if(!Page.IsPostBack), I am setting ShowLabels to false;
Then in my if statement, I am doing:
```
if(ShowLabels == false)
{
ShowLabels = true;
imgShowLabels.ImageUrl = "label-on.png";
}
else
{
ShowLabels = false;
imgShowLabels.ImageUrl = "label-off.png";
}
```
But ShowLabels is always false, I thought by setting the ViewState through the property ShowLabels, it would retain its value. | Remember, each and every time you do a postback (for any reason, including just to process server events) you are working with a *brand new instance* of your page class. The old one is dead and gone- it was eligible for disposable as soon as the page was last rendered to the browser.
It "works" when you change it to static because static variables aren't associated with any particular instance. However, I suspect you'll be surprised when you start testing that in a wider environment. Since *all* users of the page for that site are in the same AppDomain, they'll all be setting the *same* showLabels variable.
To fix this, you need to store this variable somewhere that persists for just that user. Options include ViewState, Session, a database, or some other long-term storage mechanism. My preference leans toward the database (perhaps using the ASP.Net Personalization provider with sql server), because users will likely want you to remember this every time they come to your site.
---
How 'bout:
```
ShowLabels = !ShowLabels;
imgShowLabels.ImageUrl = string.Format("label-{0}.png", (ShowLabels)?"on":"off");
``` | Joel hit the nail on the head, but I would add that what you should probably do is put the functionality on the client so to make sure your static variable isn't cleaned up unexpectedly.
I would do something like:
```
<a href="[YourPageHere.aspx]?showLabel=[togglethisvalue]>Show Labels</a>
```
For Webforms. Then you can process that as a query variable. This way you're gauranteed to have the right value. There are a ton of other ways to do this on the client side. I'm using the query variable approach for simplicity, but this might not work the more robust your pages become. | Simple question about how static variables work in ASP.NET? | [
"",
"c#",
"asp.net",
""
] |
Here's the deal: I have an Android application that needs to call a web service every X seconds (currently 60 seconds). This application has multiple tabs and these tabs all need to interact with the data themselves. One is a MapView, one is a ListView and then the third is irrelevant but will need to also get some global data eventually. The issue is that I want my main activity to have a thread that runs in the background, gets the results and then instructs both child activities in the TabHost to update themselves with the latest data. Also, when the user clicks on the tabs and the onCreate/onResume activities fire, I would also like to force a redraw by getting the latest data from the main activity. I'm really at a loss here. I've tried this with a service and some ghetto static methods to pass an instance of the Activities to the Service to call specific functions to update their views whenever the timer fired, but the slowdowns were pretty bad and the code was just ugly ugly ugly. Any suggestions?
edit: So I implemented it as a timer-driven thread in the tabhost activity and then I have timer-driven threads in each child activity that then grab the data (in a synchronized fashion) and update their map/list. It's much faster but still feels slightly hack-ish, especially the part where I'm calling a custom function in the parent activity like so:
```
((MainActivity)getParent()).getNearbyMatches();
```
This adds an element of strong coupling that I'm not entirely thrilled with, but from a performance standpoint it's much better than it was. I appreciate the answers that have already been given and will do a bit of research on the content provider front but I'm not sure I want to go back to the service model. | So I've found what I believe is the answer: [The Application Class](http://developer.android.com/reference/android/app/Application.html). You can extend this class to keep track of global application state.
In the `AndroidManifest.xml` file you can reference your fully qualified custom class in the `android:name` attribute and it will be instantiated when the app fires up.
Any Activity can then call `"getApplication()"` and it will return the instance of your custom Application class, which you can then tailor to taste. | Why are you updating all the children activities every time new data is available? That sounds inefficient to me. Update only the activity that is currently visible.
One possible way to do this is through a [custom content provider](http://developer.android.com/guide/topics/providers/content-providers.html). Let your service update the data source to your activities and get the current visible activity to listen to changes on this content. So basically, your register to the content provider when OnResume is called and unregister when OnPause is called.
**As a rule of thumb never store static references of an Activity!!** You'll end up with ugly leaks. If it is a must for your application then at least use [WeakReferences](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/WeakReference.html) | Best way to accomplish inter-activity communication in an Android TabHost application | [
"",
"java",
"android",
"ipc",
""
] |
I have several Div tags on a page which are dynamic, i.e. depending on certain criteria they are either visible to the user or not. I want to add them to the page's view state so that upon postback they are not hidden again, how do I do this? | I would just use [ASP.NET panels](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.aspx) instead of divs if you are going the viewstate route. They render as div's so they would be exactly what you want. | ```
ViewState["divAVisible"] = true;
ViewState["divBVisible"] = false;
```
Then within Page\_Load:
```
if (ViewState.ContainsKey("divAVisible"))
divA.Visible = ViewState["divAvisible"]
...
```
The divA is defined as Panel
Alternatively, you can put something like:
```
<div id="divA" runat="server">...</div>
```
in your aspx and then it will become an instance of HtmlControl generated by VS. | ViewState, div tags | [
"",
"c#",
".net",
"html",
""
] |
I need to implement a tool that runs programs from SQL Server database when a DB record matches some condition. Is there a way to do it? | I would be careful with xp\_cmdshell because it can create quite a security hole. Check out this article from
<http://www.databasejournal.com/features/mssql/article.php/3372131/Using-xpcmdshell.htm>
If the service account has local administration rights then you can use this procedure to perform any windows operating system command.
Check out this similar question I asked some time ago. After some research I decided the security risk was too great for a production DB server. Your situation might be different and xp\_cmdshell might be the answer.
[SQL Server xp\_cmdshell](https://stackoverflow.com/questions/288084/sql-server-xpcmdshell) | xp\_cmdshell is a security problem, and also a design problem (making SQL Server run other apps is not really a happy circumstance, even if it can be forced to do so). And please, please don't take the trigger suggestion - that's the worst idea. What I would do first is modify, or create a wrapper for, the program you want to run, such that it polls the database for qualifying rows, and then works with them. If necessary make a table in the db to act as a queue for the rows to be processed, or a column to indicate rows where the process is complete. | How to run a program from SQL? | [
"",
"sql",
"sql-server-2008",
""
] |
I've added x64 configuration to my C++ project to compile 64-bit version of my app. Everything looks fine, but compiler gives the following warning:
```
`cl : Command line warning D9002 : ignoring unknown option '/arch:SSE2'`
```
Is there SSE2 optimization really not available for 64-bit projects? | Seems to be all 64-bit processors has SSE2. Since compiler option always switched on by default no need to switch it on manually.
From [Wikipedia](http://en.wikipedia.org/wiki/X86-64):
> **SSE instructions**: The original AMD64 architecture adopted Intel's SSE and SSE2 as core instructions. SSE3 instructions were added in April 2005. SSE2 replaces the x87 instruction set's IEEE 80-bit precision with the choice of either IEEE 32-bit or 64-bit floating-point mathematics. This provides floating-point operations compatible with many other modern CPUs. The SSE and SSE2 instructions have also been extended to operate on the eight new XMM registers. SSE and SSE2 are available in 32-bit mode in modern x86 processors; however, if they're used in 32-bit programs, those programs will only work on systems with processors that have the feature. This is not an issue in 64-bit programs, ***as all AMD64 processors have SSE and SSE2, so using SSE and SSE2 instructions instead of x87 instructions does not reduce the set of machines on which x64 programs can be run.*** SSE and SSE2 are generally faster than, and duplicate most of the features of the traditional x87 instructions, MMX, and 3DNow!. | The compiler option /arch:AVX will not work on old CPUs hence you need to ensure your CPU supports it. I ran into this issues when I had to re-compile the 1.12 tensorflow package for my old Xeon CPU which does not support.
I have switched on /arch:SSE2 (as Kirill) posted above but getting exactly same issue. The Microsoft compiler issues a warning (INFO) that this option will be ignored.
```
Command line warning D9002 : ignoring unknown option '/arch:SSE2'
```
From the Microsoft documentation my understanding is that this option is only available on x86 and that does not make sense to me either.
However on MSDN says:
```
/arch:SSE and /arch:SSE2 are only available when you compile for the x86 platform.
```
and that SSE is used on x64 anyways. Hence I just removed the option now. | SSE2 option in Visual C++ (x64) | [
"",
"c++",
"visual-studio-2008",
"optimization",
"64-bit",
"sse2",
""
] |
I've seen this technique for calling a Javascript function based on the value of a string variable.
```
function foo() {
alert('foo');
}
var test = 'foo';
window[test](); //This calls foo()
```
Is this the accepted way to do it or is there a better way? Any cross-browser issues to worry about? | Looks fine to me. I would probably create a simple helper function like following:
```
function runFunction(name, arguments)
{
var fn = window[name];
if(typeof fn !== 'function')
return;
fn.apply(window, arguments);
}
//If you have following function
function foo(msg)
{
alert(msg);
}
//You can call it like
runFunction('foo', ['test']); //alerts test.
``` | I personally wouldn't bother even with a helper function
```
window[someKey]('test')
```
would be fine.
However I wouldn't general maintain a set of possible functions to call at the global scope anyway. Hence I would use a more general pattern:-
```
obj[someKey]('test')
```
where obj may be `this`, a property of this or variable from a closure. | Ways to call a Javascript function using the value of a string variable? | [
"",
"javascript",
"function",
""
] |
This is my query as it is now. I want to add another column to the result checking if the ItemID is equal to any value in another table column (BuildComponents.ComponentID). Eg. writing 'Y' if its there and 'N' if its not. I do not want this to affect what rows are returned. I am using MS SQL 2005. The logic would be something like this:
if(ItemID is in (select ComponentID from BuildComponents)
return 'Y'
else
return 'N'
```
SELECT
'Item' AS type,
i.ItemID,
i.ItemNumber AS prodid,
i.ItemName AS 'desc',
i.SellUnitMeasure AS unit,
i.SellUnitQuantity AS quantity,
i.VATExclusiveStandardCost AS pricein,
i.BaseSellingPrice AS priceout,
v1.VATPercentageRate AS vatRateIn,
1 AS vatTypeIn,
v1.VATCode AS VATCodeIn,
v1.VATCodeDescription AS VATCodeDescriptionIn,
v2.VATPercentageRate AS vatRateOut,
2 AS vatTypeOut,
v2.VATCode AS VATCodeOut,
v2.VATCodeDescription AS VATCodeDescriptionOut,
i.IsInactive AS inactive,
s.CardRecordID AS VendID,
i.SupplierItemNumber AS VendCode,
i.VATExclusiveStandardCost AS VendInPrice,
i.ItemDescription AS ProductNote,
i.CustomField1,
i.CustomField2,
i.CustomField3,
cl1.CustomListText AS CustomField4,
cl1.CustomListName AS CustomField4Name,
cl2.CustomListText AS CustomField5,
cl2.CustomListName AS CustomField5Name,
cl3.CustomListText AS CustomField6,
cl3.CustomListName AS CustomField6Name,
'' AS QuantityOnHand,
'' AS LocationName,
i.PriceIsInclusive,
i.ItemIsStocked,
ISNULL(l1.LocationName, ISNULL(l2.LocationName, 'Default Warehouse')) AS DefaultLocation,
i.PositiveAverageCost as cost
FROM Items i
LEFT JOIN ItemLocations il ON il.ItemID = i.ItemID AND il.ItemID IS NULL
LEFT JOIN VATCodes v2 ON v2.VATCodeID = i.SellVATCodeID
LEFT JOIN VATCodes v1 ON v1.VATCodeID = i.BuyVATCodeID
LEFT JOIN Suppliers s ON s.SupplierID = i.PrimarySupplierID
LEFT JOIN CustomLists cl1 ON cl1.CustomListID = i.CustomList1ID
LEFT JOIN CustomLists cl2 ON cl2.CustomListID = i.CustomList2ID
LEFT JOIN CustomLists cl3 ON cl3.CustomListID = i.CustomList3ID
LEFT JOIN Locations l1 ON l1.LocationID = i.DefaultSellLocationID
LEFT JOIN Locations l2 ON l2.LocationID = 1
``` | The way to do this is to left join to the target table, and if the column is null then it is 'N', else 'Y' with a case statement.
However, if ComponentID is not unique in BuildComponents you may get more results than you expected, so you need a distinct subquery to stop that from happening.
To your join list add
```
LEFT JOIN (SELECT DISTINCT ComponentID FROM BuildComponents) BC ON BC.ComponentID = i.ItemID
```
To your select fields, you need to add another column,
```
CASE WHEN BC.ComponentID IS NULL THEN 'N' ELSE 'Y' END as MyColName
``` | ```
case when exists (select ComponentID from BuildComponents where ComponentID = i.ItemID) then 'Y' else 'N' end
``` | SQL, returning logic of value being in another query to field | [
"",
"sql",
"sql-server-2005",
""
] |
Can the following code cause a memory leak? Would using a StringBuffer actually improve memory usage?
A little background: A coworker has been pushing his theories on memory leaks, and this is code he has identified as being problem code (without doing any sort of profiling), which he claims can cause a memory leak. I disagree with this, so I thought I'd put it to some other developers to get a third party opinion.
```
List partCollection = new ArrayList()
String partKeyID = null;
String sPartNbr = null;
String partDescription = null;
while(rsPartRes.next())
{
partKeyID = rsPartRes.getString("PART_KEY_ID");
sPartNbr = rsPartRes.getString("PART_NBR");
partDescription = rsPartRes.getString("PART_DESC");
SomeValueObject someValueObject = new SomeValueObject();
someValueObject.setPartKeyID(partKeyID);
someValueObject.setSPartNbr(sPartNbr);
someValueObject.setPartDescription(partDescription);
partCollection.add(someValueObject);
}
```
Assume that rsPartRes is a ResultSet in this code which could contain 100+ records. Basically, his concern is that because we are looping through this result set and not using a StringBuffer (which, in this case, I'm not even sure HOW you would use one), that it could be causing memory leaks. Is there ANY case that anyone sees here where this could possibly cause memory leaks or performance issues...? | As far as I can tell, there is no need to use a `StringBuffer` here.
The only reason to use a `StringBuffer` to increase performance would be when you are concatenating `String`s over and over.
```
String result = "";
while (condition) {
result += somethingElse;
}
```
or (`StringBuilder` is a better replacement for `StringBuffer` these days)
```
StringBuilder result = new StringBuilder();
while (condition) {
result.append(somethingElse);
}
```
The second piece of code performs much better. | No, that won't cause a memory leak. However, it would be cleaner to declare the variables inside the loop:
```
List partCollection = new ArrayList();
while(rsPartRes.next())
{
String partKeyID = rsPartRes.getString("PART_KEY_ID");
String sPartNbr = rsPartRes.getString("PART_NBR");
String partDescription = rsPartRes.getString("PART_DESC");
SomeValueObject someValueObject = new SomeValueObject();
someValueObject.setPartKeyID(partKeyID);
someValueObject.setSPartNbr(sPartNbr);
someValueObject.setPartDescription(partDescription);
partCollection.add(someValueObject);
}
```
It's not even obvious why you need those variables at all:
```
while(rsPartRes.next())
{
SomeValueObject someValueObject = new SomeValueObject();
someValueObject.setPartKeyID(rsPartRes.getString("PART_KEY_ID"));
someValueObject.setSPartNbr(rsPartRes.getString("PART_NBR"));
someValueObject.setPartDescription(rsPartRes.getString("PART_DESC"));
partCollection.add(someValueObject);
}
```
(It would also be nicer to use generics, but that's a different matter...)
How was your colleague planning to use `StringBuffer`? There's no string manipulation going on here... | Possible memory leak due to not using StringBuffer? | [
"",
"java",
"memory-management",
"jdbc",
"memory-leaks",
"resultset",
""
] |
There are a ton of PHP frameworks out there (i.e. Zend, Seagull, Symfony, CodeIgniter, CakePHP, Yii, Prado) that do a great job of implementing important pieces of a scalable/maintainable website, and I almost always pick one to start building client websites.
As of recently, I've started getting tired of providing constant development services to clients, and I'm looking at the possibility of writing more full-featured commercial scripts that can be resold over and over again in the hopes of finding that magical "recurring revenue stream" that you always hear about in fairy tales. Please note that I'm not talking about building extensions/plugins to CMS systems like Drupal or Joomla, but full blown website scripts.
So here's my multi-part question:
1. Is there any reason why I couldn't resell a script built on one of these frameworks as a full-blown turn-key solution (especially if the framework's licensing is something very flexible, like the BSD license)?
2. If not, why aren't others doing the same thing?
3. Have you ever seen a commercial PHP script that is based on a well-known open source framework?
I've wondered this for years, and no one I ask has ever really come up with a good explanation. It just seems like it is taboo to do so, and no one really knows why? I've seen commercial scripts that use third party libraries (i.e. jQuery, PHPmailer, etc), but never have I seen one built entirely on an application framework. | It really seems that a lot of people have missed the true nature of the question and even taken it as far as language debates (those never end well).
> Is there any reason why I couldn't resell a script built on one of these frameworks as a full-blown turn-key solution (especially if the framework's licensing is something very flexible, like the BSD license)?
Assuming the framework license permits it then there's no reason you couldn't do this. You had mentioned Zend Framework so you may be interested in looking at [Magento](http://www.magentocommerce.com/product/enterprise-edition). While they offer a free community edition they also have a paid edition that works with the Zend Framework as well.
I recently worked with a file upload script that was offered commercially and it happened to be built on codeigniter (name escapes me at the moment).
> If not, why aren't others doing the same thing?
My personal opinion is that it's a mix of quite a few factors really. The web based market for on premise applications (as apposed to SaaS) is already flooded with options and is starting to shrink in size. This makes less demand for an application that you would actually see the framework behind (with SaaS you most likely will never know what framework if any is being used).
A lot of the existing large players in the PHP market have been around for a while and already have their own code base that they have created and are familiar with. When you've spent years building your own libraries it's hard to justify moving to another framework.
A lot of the smaller players rarely educate themselves in proper application design and usually stick to procedural code. The big OOP features that exist in PHP today didn't come along until the 5.0 release. Mind you that was around 5 years ago but a lot of your programmers had started on their PHP tutorials and learning adventures before PHP5 was widely available and accepted on standard hosting accounts. As such most of our modern frameworks were not available CakePHP as an example didn't start until 2005. Zend framework wasn't around until 2007. These are all relatively new dates and I wouldn't expect to see a lot of commercial applications moving to them until the current generation of programmers that can write quality commercial applications age a bit (again just my opinion). | I have to heartily disagree with back2dos..
1. PHP's a solid, incredibly well used programming language for developing web apps. It can, of course, be used for commercial development and millions of people (me included) do just that. I'm not sure PHP bashing is really relevant here.
2. True, PHP is not compiled but if you really care about this you can use Zend Guard which can encrypt code. Personally I've always found open source code a plus point. Clients like to know they can get at the code if they really need to, it offers some reassurance.
3. There are lots of OS PHP apps, some great, some awful. Find a niche (like any business), something that has real demand, and develop for that.
So I think you're fine to develop commercial apps/scripts. Just make sure you give them decent support and documentation. You'll find people appreciate that and are willing to pay for it.
Finally on the point of your question, I agree they stand a much better chance of being used if they are based on an open source framework since you'll be opening yourself up to wider market. Zend Framework, as you may know, has a pretty open license which says you can sell anything you develop with it. | Selling a Script Built on a PHP Framework | [
"",
"php",
"zend-framework",
"cakephp",
"scripting",
"codeigniter",
""
] |
In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
Is there a way to do this in Python? | ```
import sys
sys._getframe(number)
```
The number being 0 for the current frame and 1 for the frame up and so on up.
The best introduction I have found to frames in python is [here](http://farmdev.com/src/secrets/framehack/index.html)
However, look at the inspect module as it does most common things you want to do with frames. | The best answer would be to use the [inspect](https://docs.python.org/3/library/inspect.html#inspect.currentframe) module; not a private function in `sys`.
```
import inspect
current_frame = inspect.currentframe()
``` | In Python, how do I obtain the current frame? | [
"",
"python",
""
] |
If you run the code below it actually executes the finally after every call to the goto:
```
int i = 0;
Found:
i++;
try
{
throw new Exception();
}
catch (Exception)
{
goto Found;
}
finally
{
Console.Write("{0}\t", i);
}
```
Why? | Why do you expect it to not execute?
If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block [most of the time](https://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try-catch-finally-if-an-unhandled).
Instead of goto, consider 'return'.
```
//imagine this try/catch/finally block is inside a function with return type of bool.
try
{
throw new Exception();
}
catch (Exception)
{
return false; //Let's say you put a return here, finally block still executes.
}
finally
{
Console.WriteLine("I am in finally!");
}
``` | The following text comes from the *C# Language Specification* ([8.9.3 The goto statement](http://msdn.microsoft.com/en-us/library/aa664758(VS.71).aspx))
---
A goto statement is executed as follows:
* If the goto statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all intervening try statements have been executed.
* Control is transferred to the target of the goto statement. | Why does this "finally" execute? | [
"",
"c#",
"exception",
"goto",
"try-catch-finally",
""
] |
How do I redirect verbose garbage collection output to a file? Sun’s website shows an example for Unix but it doesn't work for Windows. | From the output of `java -X`:
```
-Xloggc:<file> log GC status to a file with time stamps
```
Documented [here](http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html):
> **-Xloggc:*filename***
>
> Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of `-verbose:gc` with the time elapsed since the first GC event preceding each logged event. The `-Xloggc` option overrides `-verbose:gc` if both are given with the same `java` command.
>
> Example:
>
> ```
> -Xloggc:garbage-collection.log
> ```
So the output looks something like this:
```
0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]
``` | If in addition you want to pipe the output to a separate file, you can do:
On a **Sun JVM:**
```
-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps
```
ON an **IBM JVM:**
```
-Xverbosegclog:C:\whereever\jvm.log
``` | How to redirect verbose garbage collection output to a file? | [
"",
"garbage-collection",
"java",
"java-5",
""
] |
I'm trying to run a PHP script which has pg\_connect($connection\_string) and it just crashes my PHP script. I'm running it off of xampp on my computer, here are some facts:
* If I put exit("test"); immediately above the pg\_connect statement, it successfully displays the word "test" and terminates the script, so I know that my installation of xampp is working.
* Using phpinfo() I can see that the postgresql extension is indeed loaded.
* I can connect to the database server from pgadmin, so it's not a firewall issue or anything like that.
* If I remove this exit statement, the pg\_connect statement just hangs. There is no warning displayed or logged, and it never even gets past the function call. I even have:
$db\_crm = pg\_connect($connection\_str);
if (!$db\_crm) die("connection failed");
And "connection failed" is never even displayed. My browser just shows "this page cannot be displayed",after timing out.
What in the world could be causing this? | Here it is guys:
I have no reason why, but adding sslmode=disable to the end of my connection string made it work. What reason would it have to crash? I am on a windows machine and phpinfo() says OpenSSL is enabled.. | It's doubtful that the call is crashing PHP. More likely is that for some reason, the call is hanging for some reason and PHP's max execution time is being exceeded. [You can try extending the time limit](https://www.php.net/manual/en/function.set-time-limit.php) before making the pg\_connect() call to see if it eventually comes back with something. | pg_connect crashes my php script | [
"",
"php",
"postgresql",
""
] |
Just wondering if it is possible to figure out who has read files from a Windows share (using .NET ideally but win32 native will do)?
What I'm try to do is create something like [awstats](http://awstats.sourceforge.net/) for a windows share so I can see who is accessing what and which are the most popular files.
I'm not interested in changes - I just want to log access (with time) along with ip / hostname and what file. | this is possible using WMI... below the sample c# snippet used to identify whose accessing the shares currenlty
```
using System.Management;
ManagementObjectSearcher search =
new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_ConnectionShare");
foreach (ManagementObject MO in search.Get())
{
string antecedent = MO["antecedent"].ToString();
ManagementObject share = new ManagementObject(antecedent);
string dependent = MO["dependent"].ToString();
ManagementObject server = new ManagementObject(dependent);
string userName = server["UserName"].ToString();
string compname = server["ComputerName"].ToString();
string sharename = server["ShareName"].ToString();
}
```
Am not sure about the core file event listners for WMI. But you can nicely integrate this into the NoramlFileSystemWatcher. And trigger the above code if there is a change detected in the network path. | You want [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx). Build a program that uses it and logs changes. | Is it possible to programatically log access to a windows share (SMB share) using the .Net framework? | [
"",
"c#",
".net",
"windows",
"winapi",
""
] |
I am developing an .aspx page which will ultimately launch an applet after the user clicks on a button (I am using the `<applet>` tag). So, I would like to detect if java is enabled/installed on the user's browser.
I am using navigator.javaEnabled() method. However, even though this is working fine on IE7, it is returning inconsistent results on Firefox 3.0.12 (don't know about different browsers), sometimes saying that java is enabled (which it is), and then after launching the applet and coming back out of the applet to this page again, it will report false. If I close firefox and return to the applet launching page, navigator.javaEnabled() will report true again (correctly).
Is there anything that is determining this inconsistent behaviour or is navigator.javaEnabled() not the best way to do the java applet check?
Thanks in advance. | Make in your applet a method
```
public boolean isRunning() { return true; }
```
Now create an applet:
```
<applet src=".../yourapplet.jar" id="someId">
```
And now wrap this code in some helper function
```
try {
var x = document.getElementById('someId').isRunning()
return x;
} catch(e) {
return false;
}
```
Why this works? If applet runs it will return true. If applet doesn't run or Java is not supported you'll get an exception, so you'll get false. | You could also try using the object tag.
With it you can determine what version of java is installed and prompt the user to download it if it does not exist.
This is a sample object tag taken from an app that I work on, JRE complications required us to run on 1.4.2\_03 for compatibility with other applications.
```
<object classid="clsid:CAFEEFAC-0014-0002-0003-ABCDEFFEDCBA" id="MyApplet"
name="MyApplet" width="4" height="4"
codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2_03-windows-i586.cab#Version=1,4,2,03">
```
The classid specifies the version of Java you want to load, you can set this to a specific JRE, a specific family i.e. 1.4.X or whatever the latest version is.
The codebase controls where the user is directed if they do not meet what the classid is set to.
Note that if a client has 1.5 or higher installed you cannot reference an older JRE due to security constraints, You can override this via a registry setting in windows but I would not recommend it.
I believe the security is setup so you can only reference an older JRE in the same family.
i.e. user has 1.6.0.10 you can reference 1.6.0.1 but cannot go to anything in 1.5.X
Though I think I remember seeing a security dialog pop up after 1.6.0.11 where as before it would just default deny the request. | Determine whether client browser has java installed and can launch applets | [
"",
"java",
"firefox",
"applet",
"navigator",
""
] |
I've added validation checks in my controller that modify the `ModelState` if the validation fails.
For example:
```
private bool ValidateMoney(string raw, string name, decimal min, decimal max) {
try {
var dec = Convert.ToDecimal(raw);
if (dec < min) {
throw new ArgumentOutOfRangeException(name + " must be >= " + min);
}
else if (dec > max) {
throw new ArgumentOutOfRangeException(name + " must be <= " + max);
}
}
catch (Exception ex) {
ModelState.AddModelError(name, ex.GetUserMessage());
}
return ModelState.IsValid;
}
```
However, I never know value to pass for the `key` parameter in `ModelState.AddModelError`. (In the example, I just set it to my UI display name.)
What is the parameter for and how should I use it? | The Key is used by the ValidationMessage HTML Helper to know the exact error message to display.
Example:
```
<%=Html.TextBox("Name") %> <br />
<%=Html.ValidationMessage("Name") %>
```
the ValidationMessage helper will display the message that has the key "Name" in the ModelState dictionary. | The `key` parameter can be used to associate the validation error with a form field, and thus control where the message appears on-screen. It can be used with both HtmlHelper-type inputs and with simple HTML inputs.
If you've used `@Html.TextBoxFor` (or similar) and a `@Html.ValidationMessageFor`, you can get the key's value from the HTML `name` of the field being validated (use Inspect Element).
If you've just used an HTML `<input>`, you can add a validation placeholder using `@Html.ValidationMessage("AKeyIMadeUp")`, and get a message to appear in it like this: `ModelState.AddModelError("AKeyIMadeUp", "The value you entered is no good");`. | What is the point of the key parameter in ModelState.AddModelError in ASP.NET MVC? | [
"",
"c#",
".net",
"asp.net-mvc",
""
] |
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:
```
var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
```
In Python, I would imagine something like this:
```
foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
```
The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax `foo.bar`. The created object should also implement structural comparison *by component names* (not by position, as tuples do).
In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired `foo["bar"]` syntax to access components.
[namedtuple](http://docs.python.org/library/collections.html?highlight=namedtuples#namedtuple-factory-function-for-tuples-with-named-fields) isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:
```
def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
```
I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.
## [EDIT]
Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:
```
type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
```
Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't). | The pythonic way would be to use a `dict`:
```
>>> foo = dict(x=1, y=2)
>>> bar = dict(y=2, x=1)
>>> foo == bar
True
```
Meets all your requirements except that you still have to do `foo['x']` instead of `foo.x`.
If that's a problem, you could easily define a class such as:
```
class Bunch(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __eq__(self, other):
return self.__dict__ == other.__dict__
```
Or, a nice and short one
```
class Bunch(dict):
__getattr__, __setattr__ = dict.get, dict.__setitem__
```
(but note that this second one has problems as Alex points out in his comment!) | Looks like Python 3.3 has added exactly this thing in the form of [`types.SimpleNamespace`](http://docs.python.org/3/library/types.html#types.SimpleNamespace) class. | Does Python have anonymous classes? | [
"",
"python",
""
] |
What is a brief introduction to lexical scoping? | I understand them through examples. :)
First, *lexical scope* (also called *static scope*), in C-like syntax:
```
void fun()
{
int x = 5;
void fun2()
{
printf("%d", x);
}
}
```
Every inner level can access its outer levels.
There is another way, called *dynamic scope* used by the first implementation of [Lisp](https://en.wikipedia.org/wiki/Lisp_%28programming_language%29), again in a C-like syntax:
```
void fun()
{
printf("%d", x);
}
void dummy1()
{
int x = 5;
fun();
}
void dummy2()
{
int x = 10;
fun();
}
```
Here `fun` can either access `x` in `dummy1` or `dummy2`, or any `x` in any function that call `fun` with `x` declared in it.
```
dummy1();
```
will print 5,
```
dummy2();
```
will print 10.
The first one is called static because it can be deduced at compile-time, and the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.
I find static scoping easier for the eye. Most languages went this way eventually, even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.
As an example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example. If we write something like this:
```
if(/* some condition */)
dummy1();
else
dummy2();
```
The call chain depends on a run time condition. If it is true, then the call chain looks like:
```
dummy1 --> fun()
```
If the condition is false:
```
dummy2 --> fun()
```
The outer scope of `fun` in both cases is the caller *plus the caller of the caller and so on*.
Just to mention that the C language does not allow nested functions nor dynamic scoping. | Lets try the shortest possible definition:
**Lexical Scoping** defines how variable names are resolved in nested functions: **inner functions contain the scope of parent functions even if the parent function has returned**.
That is all there is to it! | What is lexical scope? | [
"",
"javascript",
"scoping",
"lexical-scope",
""
] |
I'm building a list of hashes that represent root to node paths in a tree. My functions work but they are incredibly slow over large tree structures - is there a better way? I've tried building the list in one function but I get unique hashes where I don't want them.
```
public ArrayList<Integer> makePathList(AbstractTree<String> tree){
StringBuilder buffer = new StringBuilder();
ArrayList<Integer> pl = new ArrayList<Integer>();
ArrayList<StringBuilder> paths = getPaths(tree, buffer);
for(StringBuilder sb : paths){
pl.add(sb.toString().hashCode());
}
return pl;
}
public ArrayList<StringBuilder> getPaths(AbstractTree<String> tree, StringBuilder parent){
ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
parent.append("/");
parent.append(tree.getNodeName());
list.add(new StringBuilder(parent));
if (!tree.isLeaf()){
int i = 0;
Iterator<AbstractTree<String>> child = tree.getChildren().iterator();
while (i < tree.getChildren().size()){
list.addAll(getPaths(child.next(), new StringBuilder(parent)));
i++;
}
}
return list;
}
```
UPDATE:
Marcin's suggestion to make the hash during tree traversal gives the wrong answer, but perhaps that is the way I have done it?
```
public ArrayList<Integer> getPaths(AbstractTree<String> tree, StringBuilder parent){
ArrayList<Integer> list = new ArrayList<Integer>();
parent.append("/");
parent.append(tree.getNodeName());
list.add(new StringBuilder(parent).toString().hashCode());
if (!tree.isLeaf()){
int i = 0;
Iterator<AbstractTree<String>> child = tree.getChildren().iterator();
while (i < tree.getChildren().size()){
list.addAll(getPaths(child.next(), new StringBuilder(parent)));
i++;
}
}
return list;
}
``` | I think your main problem is the amount of duplicate data you are producing: for every single leaf of the tree, you will make a copy of the entire path leading up to that leaf and compute the hash for that path. i.e. if you have 50,000 leaves under one top-level node, then the path name of that node will be copied 50,000 times and its hash computed 50,000 times.
If you could organize your data so that shared path prefixes are reused as references between leaves and hash calculations for these prefixes are cached and reused, you could drastically reduce the actual amount of work to be done. | I think complexity is still the same. No matter if you use a inline creation of hashes (O(n^2)) or doing it after recursion (O(n^2 + n) = O(n^2)).
The only opportunity to find a fast way is to do some of the work at another place. e.g. you can hash the path while inserting a node and only gather all hashes at another point. | Slow building list of paths | [
"",
"java",
"optimization",
"hash",
"recursion",
"tree",
""
] |
I have a `JTable` and I need to be able to reorder the columns. However I want the first column to not be able to be re-ordered. I used the following to enable reordering:
```
table.getTableHeader().setReorderingAllowed(true);
```
The columns can now be reordered including the first column which I don't want. Is there any way to lock the first column?
I have seen some solutions that use two tables with the first column being in a separate table, but maybe there's a better/simpler way. | I think that you need to override the `columnMoved()` method in `TableColumnModelListener`. the `TableColumnModelEvent` class has a `getFromIndex()` method that you should be able to look at to determine if it's your fixed column, and then you should be able to cancel the event.
Hope that helps. A | This is the solution that I used to prevent the 1st column from being re-ordered
```
private int columnValue = -1;
private int columnNewValue = -1;
tblResults.getColumnModel().addColumnModelListener(new TableColumnModelListener()
{
public void columnAdded(TableColumnModelEvent e) {}
public void columnMarginChanged(ChangeEvent e) {}
public void columnMoved(TableColumnModelEvent e)
{
if (columnValue == -1)
columnValue = e.getFromIndex();
columnNewValue = e.getToIndex();
}
public void columnRemoved(TableColumnModelEvent e) {}
public void columnSelectionChanged(ListSelectionEvent e) {}
});
tblResults.getTableHeader().addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
if (columnValue != -1 && (columnValue == 0 || columnNewValue == 0))
tblResults.moveColumn(columnNewValue, columnValue);
columnValue = -1;
columnNewValue = -1;
}
});
```
Cheers, | How to keep a single column from being reordered in a JTable? | [
"",
"java",
"swing",
"jtable",
""
] |
What is the alternative if I need to use a reference, and the data I am passing I cannot change the type of, hence I cannot really store a pointer to it?
### Code:
```
#include <map>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string test;
pair<string, string> p=pair<string, string>("Foo","Bar");
map<pair<string, string>, string&> m;
m[make_pair("aa","bb")]=test;
return 0;
}
```
### Error:
> $ g++ MapPair.cpp
> /usr/include/c++/3.2.3/bits/stl\_map.h:
> In instantiation of
> `std::map<std::pair<std::string,
> std::string>, std::string&,
> std::less<std::pair<std::string,
> std::string> >,
> std::allocator<std::pair<const
> std::pair<std::string, std::string>,
> std::string&> > >': MapPair.cpp:15:
> instantiated from here
> /usr/include/c++/3.2.3/bits/stl_map.h:221:
> forming reference to reference type`std::string&' MapPair.cpp: In
> function `int main()': MapPair.cpp:16:
> no match for`std::map, std::string&,
> std::less >,
> std::allocator,
> std::string&> > >& [std::pair]' operator
> /usr/include/c++/3.2.3/bits/stl\_pair.h:
> At global scope:
> /usr/include/c++/3.2.3/bits/stl\_pair.h:
> In instantiation of `std::pair<const
> std::pair<std::string, std::string>,
> std::string&>':
> /usr/include/c++/3.2.3/bits/stl_tree.h:122:
> instantiated from`std::\_Rb\_tree\_node
What am I doing wrong to cause this errror? | You cannot store references. References are just [aliases to another variable](https://isocpp.org/wiki/faq/references).
The map needs a copy of the string to store:
```
map<pair<string, string>, string> m;
```
The reason you are getting that particular error is because somewhere in map, it's going to do an operation on the `mapped_type` which in your case is `string&`. One of those operations (like in `operator[]`, for example) will return a reference to the `mapped_type`:
```
mapped_type& operator[](const key_type&)
```
Which, with your `mapped_type`, would be:
```
string&& operator[](const key_type& _Keyval)
```
And you cannot have a reference to a reference:
> Standard 8.3.4:
>
> There shall be no references to references, no arrays of references, and no pointers to references.
---
On a side note, I would recommend you use `typedef`'s so your code is easier to read:
```
int main()
{
typedef pair<string, string> StringPair;
typedef map<StringPair, string> StringPairMap;
string test;
StringPair p("Foo","Bar");
StringPairMap m;
m[make_pair("aa","bb")] = test;
return 0;
```
} | The previous answers here are outdated. Today we have `std::reference_wrapper` as part of the C++11 standard:
```
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string test;
pair<string, string> p = pair<string, string>("Foo", "Bar");
map<pair<string, string>, reference_wrapper<string>> m;
m[make_pair("aa", "bb")] = test;
return 0;
}
```
A std::reference\_wrapper will convert implicitly to a reference to its internal type, but this doesn't work in some contexts, in which case you call `.get()` for access.
<http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper> | Why do I get an error in "forming reference to reference type" map? | [
"",
"c++",
"stl",
""
] |
Heres a class executing PreparedStatements on a Connection.
```
public class doSomething {
private PreparedStatement ps;
public setPS (Connection conn) throws SQLException {
String sql = "select * from table where id = ?";
ps = conn.prepareStatement(sql);
}
public void runSomething(String var){
ps.setString(1,var);
ResultSet rs = ps.executeQuery();
...
}
}
```
I call
```
doSomethingInstance.setPS(conn);
doSomethingInstance.runSomething(var);
```
from another class and this throws and exception at the
```
ResultSet rs = ps.executeQuery();
```
The exception is SQLException: JZ0S4: Cannot execute an empty (zero-length) query. on a Prepared Statement. I cant understand why. Does anyone see what Iam doing wrong here?
Thanks! | This issue has been fixed folks. There was a problem with the database permissions. Catching and printing the stacktrace on
```
ResultSet rs = ps.executeQuery();
```
indicated that the table being accessed by the query was not found. I still have to figure out why the SQLException: JZ0S4: Cannot execute an empty (zero-length) query is being thrown.
Thanks for your time and consideration.
Rohan | Go back and copy the code straight from your source file, then edit your question. You have a potential ambiguity: Your first fragment calls the prepared statement "preparedStatement", then you change to "prepareStatement" (without the "d"). Having a clean look at your source code will make isolating the problem easier. Do you have two variables or did you mistype your example?
[later...]
Thanks for updating your code. I'm not seeing an obvious problem with it. Have you stepped through it with a debugger (e.g., in Eclipse) to ensure that the two methods are being called as expected? | SQLException: JZ0S4: Cannot execute an empty (zero-length) query. on a Prepared Statement | [
"",
"java",
"sqlexception",
"prepared-statement",
""
] |
For a program with an OO front-end and a SQL back-end, can one have each parent class map to its own table and each child class map to it's own table, then use joins in queries to allow returning all the child class's attributes? If so, is it advisable? | It is very possible and reasonably widespread. It also works well when you have minimal sub-classing, and the business logic maps easily to the objects being used. However, with only a little extensability in the mapping layer, you can easily create objects that are combinations of several tables, perhaps even doing sub-classes. (I've written such layers and take care to make such hooks possible.)
It is advisable to always use a data mapping layer because you do not want excessive SQL littering your code. OTOH, if your class structure is more heirarchical rather than relational, you might look at an OO database (I hear PostGreSQL can do that) and a suitable mapping layer. | Sure, you can do that with an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) tool like [Hibernate](https://www.hibernate.org/343.html) or [Entity Framework](http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx). As to whether it's advisable, that's a religious question -- I try not to answer those. :) | Objects mapping to tables | [
"",
"sql",
"oop",
""
] |
I am very new to JavaScript and making only my first attempts to learn.
As a small exercise, I am trying to do something simple.
Pretty much I am trying to reposition button that I have on page load.
What do I do wrong?
I would appreciate some help.
My code is bellow:
```
<style type="text/css">
.mybutton{
position:absolute;
}
</style>
```
JavaScript:
```
<script type="text/javascript">
window.onload=function(){
var mytestdiv = document.getElementById("testdiv");
var mytestbutton = document.getElementById("testdiv").childNodes()[0];
var y = mytestdiv.offsetWidth;
var x = mytestdiv.offsetHeight;
mytestbutton.style.right = x;
mytestbutton.style.top = y;
}
</script>
```
And my very simple html:
```
<body>
<div id="testdiv" style="width:500px;border:solid #000000">
<input type="submit" id="myButton" value="TestMe">
</div>
</body>
```
**Edit:**
The error I am getting in firebug is:
> mytestbutton.style is undefined | When setting position with CSS you need to specify what measurement you are using... try this:
```
mytestbutton.style.right = x + "px";
mytestbutton.style.top = y + "px";
```
EDIT:
Also, you have `.mybutton` when it should be `#mybutton`. `.` refers to classes and `#` refers to `ID`s.
And finally `.childNodes` is not a function its a property so you don't need the `()`, plus you have whitespace so you need to either remove it or use `.childNodes[1]` instead of `.childNodes[0]`.
```
var mytestbutton = document.getElementById("testdiv").childNodes[1];
```
Alternatively, you could just go
```
var mytestbutton = document.getElementById("myButton");
``` | There are a couple of problems here. Firstly, the following won't work:
```
document.getElementById("testdiv").childNodes()[0]
```
`childNodes` is not function, but an array-like object. It should be like the following:
```
document.getElementById("testdiv").childNodes[0]
```
However, that won't do what you want either - as the first node in `testdiv` is a text node (consisting of a number of space characters). You probably want this:
```
document.getElementById("testdiv").childnodes[1]
```
but the simplest solution is this:
```
document.getElementById("myButton")
```
Secondly, as mentioned in another answer, you need to specify units when assigning CSS styles to an object. | Reposition button with simple JavaScript | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
Consider this scenario with the following assumptions:
* The database is used for a non-critical webapp.
* Query speed is of vital importance.
* The read/write patterns are roughly >95 % reads and <5 % writes.
* The database is backuped up daily using mysqldump.
* The is no need for transactions or advanced crash recovery. If the database crashes I'll simply import last night's mysqldump. This is good enough in this scenario.
* No need for full-text searching.
Pros of MyISAM under said assumptions:
* It's very fast (with one exception - see below).
* It's light-weight and has an easy-to-understand mapping between database/table to physical files in file system (.MYD/.MYI/.frm).
* Easy backup (mysqldump).
All-in-all I'm very happy with MyISAM with one major exception. MyISAM has one major shortcoming under said assumptions and that is table level locking. When UPDATEs are running towards a frequently read table all reads are blocked. Needless to say this causes major performance problems which must be solved.
My questions are:
1. Is there some way to get rid of table level locking without switching away from MyISAM?
2. If I must switch to InnoDB - how do I configure InnoDB so that it behaves as similar to MyISAM as possible (think no transactions, logical file structure, etc.). How do I configure a InnoDB to be "just like MyISAM but without table level locking"? | 1. No, MyISAM means table level locking.
2. You can't get it "just like", but you can get it "a lot more like" by turning on the `innodb_file_per_table` option. InnoDB will still store critical information in its system-level data file, however, and you can't do things like casually rename a database by renaming the directory it lives in like you can with MyISAM. | Have you actually taken performance metrics using myisam and innodb tables? In my experience the differences in speed is not really that much when you consider all the ACID benefits you get from innodb. Just the table locking alone will affect speed such that innodb would be overall faster.
Also notice that myisam is much faster on inserts, not so much on selects. You are inserting only 5% of the time... do the math.
You can always do mysqldump using an innodb, so your backup rocess is the same. | Choice of MySQL table type for non-critical webapp data (MyISAM vs. InnoDB) | [
"",
"sql",
"mysql",
"database",
"optimization",
""
] |
The `CheckBox` control exposes both boolean `Checked` and `System.Windows.Forms.CheckState` enum `CheckState` properties, which allow you to set the control to either checked, unchecked, or mixed state (`Indeterminate` enum value).
I want to set a `ListView` item's state to `Indeterminate`, but only the `Checked` property seems to be available. So, is there a way to set it to mixed, possibly by window messaging or similar tricks? | Well, you can use the following workaround:
1. Create state ImageList with 3 states (you can take create images using [CheckBoxRenderer](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkboxrenderer.aspx))
2. Assign this image list to list view
3. Then you need to handle OnMouseDown (or OnMouseClick) and OnKeyDown events and shift state images for needed list item
Of course you also need to write several helper methods to get checked state, etc. But in general this solution is relatively easy to implement.
Actually internal ListView implementation do the same, but this logic is hidden inside comctl32.dll. | [ObjectListView](http://www.codeproject.com/KB/list/objectlistview.aspx) (an open source wrapper around .NET WinForms ListView) supports check boxes with mixed state.
Have a look at the Simple tab of the demo to see them in action.
(Having done the work, I have to say that it is **not** as easy as arbiter suggests) | Is it possible to set a checked listview item to mixed state? | [
"",
"c#",
".net",
"listview",
"checkbox",
"checkedlistbox",
""
] |
We currently have check printing fully implemented and in the field for a POS application. It runs on Windows, implemented in C# and uses POS for .Net.
We are having an issue where cashiers are too eager and pull out the check a second or so before it is finished franking.
If the check is pulled out during the printing process, we cannot get the printer to stop accepting checks. The slip LED indicator blinks and will take checks until a call to BeginRemoval() and EndRemoval() are called successfully which cannot happen unless you put a check in for it to spit right back out.
I was wondering if there is a way to disable the printer from wanting a check when no check is present. I assume there is merely a method we are not calling correctly.
Specifically the issue is if you call BeginInsertion() and EndInsertion(), both succeed, and the check is removed before the application can call BeginRemoval()/EndRemoval().
Does anyone have a working example in C#, C++, VB or any language for that matter? I need an example of inserting a check, printing, waiting for removal that handles errors properly.
\*UPDATE: I forwarded this issue to Epson, and asked for an example app. They have not been able to produce one, but pointed me to a DirectIO() call that supposedly works on the TM-H6000 series to cancel a slip insert. I have not gotten this to work, however. Hopefully we will figure it out and post the fix.
\*UPDATE 2: Epson replied with some DirectIO() operations that will supposedlly fix the issue. However, I keep getting ErrorCode.Illegal when trying to call DirectIO(). Anyone have an example of using DirectIO() that works on a legacy device?
The code that should work:
```
_printer.DirectIO(121, 0, null); //121 is a constant for EPSON_DI_HARDWARE_RESET
```
UPDATE 3: BOUNTY! | A combination of the following fixed the issue:
* Better screen prompts and animations for the user (as well as better training)
* Discovered this store had an older version of OPOS (we upgraded them)
* We removed transactional printing from the check printing process (although we still use it on receipts)
OPOS in general can be pretty dumb, I recommend trying different versions. We tried the newest (version 2.6) and it was worse, but the EPSON OPOS ADK 2.5 SP 10 seems the most stable in our environment. | If I were you I'd just install a plastic cover on the printer so they can't grab the check so quickly. :) | POS for .Net Check Printing | [
"",
"c#",
".net",
"point-of-sale",
"opos",
"pos-for-.net",
""
] |
What is this language construct called?
In Python I can say:
```
def a(b,c): return b+c
a(*[4,5])
```
and get 9. Likewise in Ruby:
```
def a(b,c) b+c end
a(*[4,5])
```
What is this called, when one passes a single array to a function which otherwise requires multiple arguments?
What is the name of the `*` operator?
What other languages support this cool feature? | The Python docs call this [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). It's a pretty handy feature. In Python, you can also use a double asterisk (\*\*) to unpack a dictionary (hash) into keyword arguments. They also work in reverse. I can define a function like this:
```
def sum(*args):
result = 0
for a in args:
result += a
return result
sum(1,2)
sum(9,5,7,8)
sum(1.7,2.3,8.9,3.4)
```
To pack all arguments into an arbitrarily sized list. | In ruby, it is often called "splat".
Also in ruby, you can use it to mean 'all of the other elements in the list'.
```
a, *rest = [1,2,3,4,5,6]
a # => 1
rest # => [2, 3, 4, 5, 6]
```
It can also appear on either side of the assignment operator:
```
a = d, *e
```
In this usage, it is a bit like scheme's cdr, although it needn't be all but the head of the list. | Name this python/ruby language construct (using array values to satisfy function parameters) | [
"",
"python",
"ruby",
"syntax",
"language-features",
""
] |
I want to remove everything (including the comma) from the first comma of a string in PHP.
For example,
```
$print = "50 days,7 hours";
```
should become
```
50 days
``` | Here's one way:
```
$print = preg_replace('/^([^,]*).*$/', '$1', $print);
```
Another:
```
list($print) = explode(',', $print);
```
Or:
```
$print = explode(',', $print)[0];
``` | This should work for you:
```
$r = (strstr($print, ',') ? substr($print, 0, strpos($print, ',')) : $print);
# $r contains everything before the comma, and the entire string if no comma is present
``` | Remove everything from the first occurrence of a character to the end of a string in PHP | [
"",
"php",
"replace",
"substring",
"extract",
""
] |
What is it about the way strings are implemented that makes them so expensive to manipulate?
Is it impossible to make a "cheap" string implementation?
or am I completely wrong in my understanding?
Thanks | Which language?
Strings are typically immutable, meaning that any change to the data results in a new copy of the string being created. This can have a performance impact with large strings.
This is an important feature, however, because it allows for optimizations such as interning. Interning reduces the size of text data by pointing identical strings to the same copy of data.
If you are concerned about performance with strings, use a StringBuilder (available in C# and Java) or another construct that works with mutable text data.
If you are working with a large amount of text data and need a powerful string solution while still saving space, [look into using ropes](http://en.wikipedia.org/wiki/Rope_(computer_science)). | The problem with strings is that they are not primitive types. They are arrays.
Therefore, they suffer the same speed and memory problems as arrays(with a few optimizations, perhaps).
Now, "cheap" implementations would require lots of stuff: concatenation, indexOf, etc.
There are many ways to do this. You *can* improve the implementation, but there are some limits. Because strings are not "natural" for computers, they need more memory and are slower to manipulate... ALWAYS. You'll never get a string concatenation algorithm faster than any decent integer sum algorithm. | Why are strings notoriously expensive | [
"",
"c#",
"string",
""
] |
Is there an easy way to count the lines of code you have written for your django project?
Edit: The shell stuff is cool, but how about on Windows? | Yep:
```
shell]$ find /my/source -name "*.py" -type f -exec cat {} + | wc -l
```
Job's a good 'un. | You might want to look at [CLOC](http://cloc.sourceforge.net/) -- it's not Django specific but it supports Python. It can show you lines counts for actual code, comments, blank lines, etc. | Count lines of code in a Django Project | [
"",
"python",
"django",
""
] |
I have a download script that processes my downloads:
`download.php?file=file_refrence_here`
How can I prevent someone from putting a link on their site such as:
<http://www.mysite.com/download.php?the_file_refrence>
Apparently `$_SERVER[HTTP_REFER]` is not secure.
Although I am just worried about general linking not people smart enough to change their header strings. | One way would be to include a time-limited hash which is validated before you allow the download. A distributed link then only has a small window of time in which it can be used.
For example
```
$file="foo.mp3";
$salt="youpeskykids";
$expiry=time()+3600;
$hash=md5($salt.$file.$expiry);
$url="download.php?file=$file&e=$expiry&h=$hash";
```
Now, when you process such a request, you can recalculate the hash and check that the presented hash is equal: this ensures that whoever made the URL knows the salt, which one hopes is just your site. If the hash is valid, then you can trust the expiry time, and if it hasn't expired, allow the download.
You could include other things in the hash too if you like, like IP address and user-agent, if you wanted to have more confidence that the user-agent which requested the download link is the one which actually does the download. | You cannot prevent someone from linking to your page as you cannot prevent someone to write the word *sunflower* on a sheet of paper.
But if you want to prevent that following such a link will result in downloading that resource, you would need to authenticate the request in some way. This could be done by generating random, temporary valid authentication tokens that only your page can create. | preventing outside linking to a page | [
"",
"php",
"header",
""
] |
Is there a native machine code compiler for JavaScript?
I'm not talking about a VM.
If it doesn't exist can it be done?
I am wondering if it can be compiled to binary due to the dynamic nature of the language. | As far as I know, there are no static compilers for JavaScript. It is certainly theoretically possible; however, a static compilation of JavaScript would need a very heavyweight runtime to support all of its features (such as dynamic typing and eval). As a small aside, when presented with the need to statically compile Python (another dynamic language), the [PyPy](http://codespeak.net/pypy/dist/pypy/doc/ "PyPy") developers ended up creating a language which was a very restricted subset of Python (called RPython), void of some of Python's more dynamic features, that was capable of being statically compiled.
If you're asking this for the purpose of creating a standalone executable from JavaScript code, I'm sure there must be wrappers which essentially would create an executable containing your script and an embedded JavaScript VM (sadly, I don't know any offhand). | It's definitely doable, although the only way I know how to do it at the moment is a two step process...
1. Compile the javascript to Java using [Mozilla Rhino JSC](https://developer.mozilla.org/en/Rhino_JavaScript_Compiler).
2. Compile the resulting java class file to executable using something like [GNU's GCJ](http://gcc.gnu.org/java/).
Why would you want to, though? What advantage do you expect to find? | Is there a native machine code compiler for JavaScript? | [
"",
"javascript",
"compilation",
"native",
"native-code",
""
] |
I am trying to implement a List class using pointers and am trying to implement a function LOCATE(T x) where T is for the template and returns the first position of the element x if found, else returns last position + 1.
My functions code is
```
template<class T>
int List<T>::locate(T n) const
{
int size = end();
Node<T> * p = head_;
for (int i = 0; i < size; i++)
{
if (p->data() == n) // fails on this line
return i;
p = p->link();
}
return size; // if no match found
}
```
I initialise my list with T as string as
```
List<string> myList;
```
but I get an error message
'bool std::operator ==(const std::istreambuf\_iterator<\_Elem,\_Traits> &,const std::istreambuf\_iterator<\_Elem,\_Traits> &)' : could not deduce template argument for 'const std::istreambuf\_iterator<\_Elem,\_Traits> &' from 'std::string
Why is the error coming up even though the '==' operator is defined for the string class?
'
The code for Node is
```
template<typename T>
class Node
{
public:
// Constructors
Node();
Node(T d, Node<T> * l = NULL);
//Inspectors
T data() const;
Node<T> * link() const;
// Mutators
void data(T d); // assigns new value to Node
void link(Node<T> * l); // points this Node to a different one
// Destructor
~Node();
private:
Node<T> * link_;
T data_;
};
template<typename T>
T Node<T>::data() const
{
return data_;
}
template<typename T>
Node<T>* Node<T>::link() const
{
return link_;
}
```
The calling code is
```
List<string> test;
test.add("abc");
cout << test.locate("abc") << endl;
``` | Try :
```
if( n.compare(p->data()) == 0 )
```
[string::compare documentation](http://www.cplusplus.com/reference/string/string/compare/)
As the comments below have noted, operator== should work. Please double check that you have
```
#include <string>
using std::string;
``` | Without getting neck-deep in your code, I notice several problems.
Firstly,
```
locate(T n)
```
should be
```
locate(const T& n)
```
This saves a possible copy of n
And to ask a stupid question, are you sure you've done:
```
#include <string>
``` | use operators in templates in c++ | [
"",
"c++",
"pointers",
"linked-list",
""
] |
Is there an elegant way to use Services *across* or *between* OSGi containers?
*Is it even possible?*
For instance, lets say I have a service interface on my local machine. What methodologies/technologies can I use to get that service interface accessible through a remote OSGi container's BundleContext? | There is a RFC called Remote Services (formerly Distributed OSGi) that does exactly what you are trying to achieve. The RFC is almost completed, and there are already 2 implementations provided respectively by Apache CXF and Eclipse ECF.
Both the implementations allows to do transparent remoting of an OSGi service. You just have to define the OSGi service as usual, and add some configuration parameters to make it a remote service.
Check:
<http://cxf.apache.org/distributed-osgi.html> | It is possible, but there are no libraries (afaik) that will do this for you. I've rolled my own for my current job. OSGi runtime on client and server, RMI is the transport. I've had to make HEAVY use of Proxy objects.
Register a service in the server's OSGi runtime (Equinox). I have a listener that watches all services looking for a property/attribute indicating this service should be exported (made remote), something like "remotable=true". It's easy to filter using the ServiceTracker. Over RMI I instruct the client to create a Proxy object with the service interface. All calls to this proxy object are generically send back over RMI (a call like execService serviceid, method name, var args params) and then invoked on the REAL service.
I've left out some of the low level details, but you can probably sort it out. If you can stray away from RMI, you may want to look into [Riena](http://www.eclipse.org/riena/) (there may even be a way to write an RMI transport for Riena, I just haven't bothered to try) | Remoting and OSGi | [
"",
"java",
"jakarta-ee",
"remoting",
"osgi",
"equinox",
""
] |
So, what I intended to do is to fetch a list of entries/posts with their category and user details, AND each of its total published comments. (entries, categories, users, and comments are separate tables)
This query below fetches the records fine, but it seems to skip those entries with no comments. As far as I can see, the JOINs are good (LEFT JOIN on the comments table), and the query is correct. What did I miss ?
```
SELECT entries.entry_id, entries.title, entries.content,
entries.preview_image, entries.preview_thumbnail, entries.slug,
entries.view_count, entries.posted_on, entry_categories.title AS category_title,
entry_categories.slug AS category_slug, entry_categories.parent AS category_parent,
entry_categories.can_comment AS can_comment, entry_categories.can_rate AS can_rate,
users.user_id, users.group_id, users.username, users.first_name, users.last_name,
users.avatar_small, users.avatar_big, users.score AS user_score,
COUNT(entry_comments.comment_id) AS comment_count
FROM (entries)
JOIN entry_categories ON entries.category = entry_categories.category_id
JOIN users ON entries.user_id = users.user_id
LEFT JOIN entry_comments ON entries.entry_id = entry_comments.entry_id
WHERE `entries`.`publish` = 'Y'
AND `entry_comments`.`publish` = 'Y'
AND `entry_comments`.`deleted_at` IS NULL
AND `category` = 5
GROUP BY entries.entry_id, entries.title, entries.content,
entries.preview_image, entries.preview_thumbnail, entries.slug,
entries.view_count, entries.posted_on, category_title, category_slug,
category_parent, can_comment, can_rate, users.user_id, users.group_id,
users.username, users.first_name, users.last_name, users.avatar_big,
users.avatar_small, user_score
ORDER BY posted_on desc
```
edit: I am using MySQL 5.0 | Well, you're doing a left join on entry\_comments, with conditions:
```
`entry_comments`.`publish` = 'Y'
`entry_comments`.`deleted_at` IS NULL
```
For the entries with no comments, these conditions are false.
I guess this should solve the problem:
```
WHERE `entries`.`publish` = 'Y'
AND (
(`entry_comments`.`publish` = 'Y'
AND `entry_comments`.`deleted_at` IS NULL)
OR
`entry_comments`.`id` IS NULL
)
AND `category` = 5
```
In the OR condition, I put `entry_comments`.`id`, assuming this is the primary key of the entry\_comments table, so you should replace it with the real primary key of entry\_comments. | It's because you are setting a filter on columns in the `entry_comments` table. Replace the first with:
```
AND IFNULL(`entry_comments`.`publish`, 'Y') = 'Y'
```
Because your other filter on this table is an `IS NULL` one, this is all you need to do to allow the unmatched rows from the LEFT JOIN through. | SQL help: COUNT aggregate, list of entries and its comment count | [
"",
"sql",
"mysql",
""
] |
I been reading on asp.net mvc learning site about JavaScript injection and man it is an eye opener.
I never even realized/thought about someone using JavaScript to do some weird ass injection attacks.
It however left me with some unanswered questions.
First
When do you use html.encode? Like do you use it only when you are going to display information that that user or some other user had submitted?
Or do I use it for everything. Like say I have form that a user submits, this information will never be displayed to any of the users, should I be still using html.encode?
How would I do it like I am not sure how to put inside say and Html.TextBox() the html.encode tag.
Second
What happens say I have on my site a rich html editor. The user is allowed to use it and make things bold and whatever. Now I want to display information back to the user through a label. I can't Html.Encode it since then all the bold and stuff will not be rendered.
Yet I can't leave it like it is since what would stop a user to add some Javascript attack?
So what would I do? Use Regex to filter out all tags?
Third
There is also another tag you can use called "AntiforgeryToken" when would you use this one?
Thanks
Edit
Almost everyone says use a "White List" and "Black List" how would I write this list and compare it to incoming values(examples in C# would be nice)? | Good question!
1. For the first answer, I would consider looking [here](https://stackoverflow.com/questions/53728/will-html-encoding-prevent-all-kinds-of-xss-attacks) at a previous asked question. As the answer discusses, using HTML Encode will not protect you completely against all XSS attacks. To help with this, you should consider using the [Microsoft Web Protection Library](http://www.codeplex.com/AntiXSS) ([AntiXSS](http://nuget.org/packages/AntiXSS) in particular), available from Microsoft.
2. As has already been mentioned, using a list of allowed tags is the best thing to do, leaving others to be stripped out.
3. The AntiforgeryToken token works to prevent request forgery (CSRF) because it gives the user a cookie which is validated against the rendered form field when the page is posted. There's no reason that I am aware of that means that you can't use this in all of your forms. | Use HTML Encode for any data being displayed that has been submitted by a user. You don't need to use it when submitting into the database otherwise you would get odd data like: Simon '&' Sons. Really I don't see the harm to use it on any content written to the page dynamically.
Use a list of allowed tags and discard everything else for your HTML editor. As people said, use a whitelist.
The third one is meant to prevent a *[Cross-site request forgery](http://www.codinghorror.com/blog/archives/001171.html)* attack. You use this to stop people being able to do a POST using a 'stolen' cookie from the user. So you may require a authenticated cookie before accepting a post but a malicious user could take that cookie when a user visits their site and then submit a form to your site claiming to be them.
See here for more:
<http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx>
How to use it:
<http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/> | Questions about Javascript injection | [
"",
"javascript",
"asp.net-mvc",
"javascript-injection",
""
] |
I wanna validate a phone number.
My condition is that I want mimimum 7 numbers in the given string, ignoring separators, X, parantheses.
Actually I want to achieve this function in regex:
```
Func<string, bool> Validate = s => s.ToCharArray().Where(char.IsDigit).Count() >= 7;
Func<string, bool> RegexValidate = s => System.Text.RegularExpressions.Regex.IsMatch(s, @"regex pattern should come here.")
string x = "asda 1234567 sdfasdf";
string y = "asda sdfa 123456 sdfasdf";
bool xx = Validate(x); //true
bool yy = Validate(y); //false
```
The purpose of my need is I want to include this regex in an asp:RegularExpressionValidator | Seven or more digits, mixed with any number of any other kind of character? That doesn't seem like a very useful requirement, but here you go:
```
^\D*(?:\d\D*){7,}$
``` | ```
(?:\d.*){7,}
```
* `(?:...)` - group the contained pattern into an atomic unit
* `\d` - match a digit
* `.*` match 0 or more of any character
* `{7,}` match 7 or more of the preceeding pattern
If the only separators you want to ignore are spaces, dashes, parentheses, and the character 'X', then use this instead:
```
(?:\d[- ()X]*){7,}
```
* `[...]` creates a character class, matching any one of the contained characters
The difference being, for example, that the first regex will match `"a1b2c3d4e5f6g7h"`, and the second one won't.
As Gregor points out in the comments, the choice of regex depends on what function you're using it with. Some functions expect a regex to match the entire string, in which case you should add an extra `.*` in front to match any padding before the 7 digits. Some only expect a regex to match part of a string (which is what I expected in my examples).
According to the [documentation for `IsMatch()`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.ismatch.aspx) it only "indicates whether the regular expression finds a match in the input string," not requires it to match the entire string, so you shouldn't need to modify my examples for them to work. | I need a regex that validates for minimum 7 digits in the given string | [
"",
"c#",
".net",
"regex",
"validation",
""
] |
I am currently writing a music blog. The administrator posts a new article every 2-3 days. Once the administrator posts an article, a mass email will be sent to around 5000 subscribers immediately.
What is the best way to implement the mass mail feature?
Does the following function work?
```
function massmail()
{
$content = '...';
foreach ($recipients as $r) {
$_content = $content . '<img src="http://xxx/trackOpenRate.php?id='.$r.'">';
mail($r, 'subject', $_content);
}
}
```
Another question: If all 5000 subscribers are using Yahoo Mail, will Yahoo treat it as a DDOS attack and block the IP address of my SMTP server? | First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without [specifying extra headers](https://www.php.net/manual/en/function.mail.php)
I'll suggest you take a look at [SwiftMailer](http://swiftmailer.org/), which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam). | I would insert all the emails into a database (sort of like a queue), then process them one at a time as you have done in your code (if you want to use swiftmailer or phpmailer etc, you can do that too.)
After each mail is sent, update the database to record the date/time it was sent.
By putting them in the database first you have
1. a record of who you sent it to
2. if your script times out or fails and you have to run it again, then you won't end up sending the same email out to people twice
3. you can run the send process from a cron job and do a batch at a time, so that your mail server is not overwhelmed, and keep track of what has been sent
Keep in mind, how to automate bounced emails or invalid emails so they can automatically removed from your list.
If you are sending that many emails you are bound to get a few bounces. | Sending mass email using PHP | [
"",
"php",
"email",
"bulk",
"massmail",
""
] |
I have 2 Forms (Form1 and Form2) and a class (Class1). Form1 contains a button (Button1) and Form2 contains a RichTextBox (textBox1) When I press Button1 on Form1, I want the method (DoSomethingWithText) to be called. I keep getting "NullReferenceException - Object reference not set to an instance of an object". Here is a code example:
Form1:
```
namespace Test1
{
public partial class Form1 : Form
{
Form2 frm2;
Class1 cl;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frm2 = new Form2();
cl.DoSomethingWithText();
frm2.Show()
}
}
}
```
Class1:
```
namespace Test1
{
class Class1
{
Test1.Form2 f2;
public void DoSomethingWithText()
{
f2.richTextBox1.Text = "Blah blah blah";
}
}
}
```
How can I call this method from within a class? Any help is greatly appreciated. | You have to instantiate `c1` and `f2`. Try this:
```
public partial class Form1 : Form
{
Form2 frm2;
Class1 cl;
public Form1()
{
c1 = new Class1();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frm2 = new Form2();
cl.DoSomethingWithText(frm2);
frm2.Show();
}
}
class Class1
{
public void DoSomethingWithText(Test1.Form2 form)
{
form.richTextBox1.Text = "Blah blah blah";
}
}
```
***UPDATE***
As Keith has pointed out, because you're instantiating a new version of `Form2`, the rich textbox will never show the blah blah blah code. I've updated the sample to fix this. | You haven't instantiated an instance of Class1 before you've tried to use it
You'd need to do:
```
private void button1_Click(object sender, EventArgs e)
{
c1 = new Class1();
frm2 = new Form2();
cl.DoSomethingWithText(frm2);
frm2.Show();
}
```
Not I've also added in the passing of frm2 in to the DoSomethingWithText method for it to then use (else you'd end up with another similar exception as f2 hasn't been instantiated in that class. | Calling a method from within a Class | [
"",
"c#",
"class",
"methods",
"nullreferenceexception",
""
] |
I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.
I've got the model of:
```
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
```
and then create an instance with:
```
memory = Memory()
memory.author = users.get_current_user()
memory.content = self.request.get('content')
```
But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21
I've tried:
```
memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d')
memory.date = db.DateProperty(self.request.get('date'))
memory.date = self.request.get('date') (wishful thinking I guess)
```
and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:
> : No
> module named \_multiprocessing
> args = ('No module named \_multiprocessing',)
> message = 'No module named \_multiprocessing'
I have no idea what to make of that.
I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not.
What am I missing on something that would seem to be so simple. | perhaps you are using the wrong class? I'm not sure what type your model should take
but try:
```
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d')
```
I use a datetime object in MySQL with MySQLdb (and a datetime field)
...likewise you can try
```
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
```
(notice the [obj].date() at the end) | You were right with strptime:
```
>>> dt = time.strptime('2009-07-21', '%Y-%m-%d')
>>> dt
time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec
=0, tm_wday=1, tm_yday=202, tm_isdst=-1)
>>>
```
You got struct that can be used by other functions. For example display date in M/D/Y convention:
```
>>> time.strftime('%m/%d/%Y', dt)
'07/21/2009'
```
Another example (import datetime module):
```
>>> dt = datetime.datetime.strptime('2009-07-21', '%Y-%m-%d')
>>> td = datetime.timedelta(days=20)
>>> dt+td
datetime.datetime(2009, 8, 10, 0, 0)
``` | Creating DateTime from user inputted date | [
"",
"python",
"datetime",
""
] |
How to get a value from previous result row of a SELECT statement
If we have a table called cardevent and has rows [ID(int) , Value(Money) ] and we have some rows in it, for example
```
ID --Value
1------70
1------90
2------100
2------150
2------300
3------150
3------200
3-----250
3-----280
```
so on...
How to make one Query that get each row ID,Value and the previous Row Value in which data appear as follow
```
ID --- Value ---Prev_Value
1 ----- 70 ---------- 0
1 ----- 90 ---------- 70
2 ----- 100 -------- 90
2 ------150 -------- 100
2 ------300 -------- 150
3 ----- 150 -------- 300
3 ----- 200 -------- 150
3 ---- 250 -------- 200
3 ---- 280 -------- 250
```
so on.
i make the following query but it's so bad in performance in huge amount of data
```
SELECT cardevent.ID, cardevent.Value,
(SELECT F1.Value
FROM cardevent as F1
where F1.ID = (SELECT Max(F2.ID)
FROM cardevent as F2
WHERE F2.ID < cardevent.ID)
) AS Prev_Value
FROM cardevent
```
So can anyone help me to get the best solution for such a problem ? | This one should work fine for both databases:
```
SELECT cardevent.ID, cardevent.Value,
(SELECT TOP 1 F1.Value
FROM cardevent as F1
WHERE F1.ID < cardevent.ID
ORDER BY F1.ID DESC
) AS Prev_Value
FROM cardevent
```
**Update:** Assuming that ID is not unique, but that the combination of ID and Value is unique (you must specify what imposes your ordering on the table, so one knows what is *the previous row*), you must use this query:
```
select cardevent.ID, cardevent.Value,
(select TOP 1 F1.Value from cardevent as F1
where (F1.ID < cardevent.ID) or (F1.ID = cardevent.ID and F1.Value < cardevent.Value)
order by F1.ID DESC, F1.Value DESC
) AS Prev_Value
from cardevent
``` | Try something like this:
```
SELECT C.ID, C.Value, COALESCE(C1.Value, 0)
FROM cardevent C
LEFT JOIN cardevent C1
ON C1.Id = (SELECT MAX(id) FROM cardevent C2 where C2.Id < C.Id)
``` | HOW TO SELECT PREVIOUS ROW VALUE? | [
"",
"sql",
"ms-access",
""
] |
i want to replace html text that closed by tag
start\_ticker
code....
end\_ticker
i don't success
my code is
```
$string_html = preg_replace('/<!-- start_ticker -->.*<!-- end_ticker -->/i',"bla bla",$string_html);
``` | By default "." doesn't match newlines - you can add the "s" (DOTALL) modifier to change this.
I suspect that's your problem.
```
$string_html = preg_replace('/<!-- start_ticker -->.*<!-- end_ticker -->/is',"bla bla",$string_html);
``` | You can solve that problem even without using regular expressions:
```
$start = '<!-- start_ticker -->';
$end = '<!-- end_ticker -->';
$replacement = 'blabla';
$posStart = stripos($str, $start);
if ($posStart !== false) {
$posEnd = stripos($str, $end, $posStart);
if ($posEnd !== false) {
$str = substr($str, 0, $posStart) . $replacement . substr($str, $posEnd + strlen($end));
}
}
``` | help with preg_replace | [
"",
"php",
"preg-replace",
""
] |
I have been using Turbogears 1 for prototyping small sites for the last couple of years and it is getting a little long in the tooth. Any suggestions on making the call between upgrading to Turbogears 2 or switching to something like Django? I'm torn between the familiarity of the TG community who are pretty responsive and do pretty good documentation vs the far larger community using Django. I am quite tempted by the built-in CMS features and the Google AppEngine support.
Any advice? | I have experience with both Django and TG1.1.
IMO, TurboGears strong point is it's ORM: SQLAlchemy. I prefer TurboGears when the database side of things is non-trivial.
Django's ORM is just not that flexible and powerful.
That being said, I prefer Django. If the database schema is a good fit with Django's ORM I would go with Django.
In my experience, it is simply less hassle to use Django compared with TurboGears. | TG2 is built on top of Pylons which has a fairly large community as well. TG got faster compared to TG1 and it includes a per-method (not just web pages) caching engine.
I think it's more AJAX-friendly than Django by the way pages can be easly published in HTML or JSON .
2011 update: after 3 years of bloated frameworks I'm an happy user of <http://bottlepy.org/> | Turbogears 2 vs Django - any advice on choosing replacement for Turbogears 1? | [
"",
"python",
"django",
"google-app-engine",
"turbogears",
"turbogears2",
""
] |
I was looking around for a tool to monitor the status of my software raid under Windows 2003 Server, but couldn't find anything suitable (i.e. not [grossly oversized](http://www.nagios.org/) or [needlessly complicated](http://www.monitorware.com/common/en/articles/software_raid_monitoring_windows_2003.php)). So I decided to just do it myself, it's nothing spectacularly difficult.
So how can I retrieve the status of the volumes programmatically? It's been a while since I fiddled with the Windows API and I couldn't find anything right off the bat using Google. I know I can use `diskpart /s` and parse its output, but that gets messy fairly quickly (although it does have some advantages).
Any pointers into the right direction are highly appreciated :) | The Win32 API is the (apparently only) way to go here, [Virtual Disk Service](http://msdn.microsoft.com/en-us/library/bb986750%28VS.85%29.aspx) is the magic word.
[Here](http://msdn.microsoft.com/en-us/library/aa383037%28VS.85%29.aspx) is a good example in C++ that will get you started. The number of different COM interfaces was pretty confusing for me at first, but the [How Virtual Disk Service Works](http://technet.microsoft.com/en-us/library/cc739923%28WS.10%29.aspx) article was of *great* help getting the big picture.
It's actually pretty easy. Despite never having done any serious C++ coding and never having even touched COM before, I was still able to get the basic functionality to work in a few hours. | Did you check WMI?
You can take a look [here](http://www.codeproject.com/KB/system/wmi.aspx) for a demo. | How can I retrieve information about disk volumes? | [
"",
"c#",
"windows",
""
] |
I have an associative array that I might need to access numerically (ie get the 5th key's value).
```
$data = array(
'one' => 'something',
'two' => 'else',
'three' => 'completely'
) ;
```
I need to be able to do:
```
$data['one']
```
and
```
$data[0]
```
to get the same value, 'something'.
My initial thought is to create a class wrapper that implements ArrayAccess with offsetGet() having code to see if the key is numeric and act accordingly, using array\_values:
```
class MixedArray implements ArrayAccess {
protected $_array = array();
public function __construct($data) {
$this->_array = $data;
}
public function offsetExists($offset) {
return isset($this->_array[$offset]);
}
public function offsetGet($offset) {
if (is_numeric($offset) || !isset($this->_array[$offset])) {
$values = array_values($this->_array) ;
if (!isset($values[$offset])) {
return false ;
}
return $values[$offset] ;
}
return $this->_array[$offset];
}
public function offsetSet($offset, $value) {
return $this->_array[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->_array[$offset]);
}
}
```
I am wondering if there isn't any built in way in PHP to do this. I'd much rather use native functions, but so far I haven't seen anything that does this.
Any ideas?
Thanks,
Fanis | i noticed you mentioned it is a readonly database result set
if you are using mysql then you could do something like this
```
$result = mysql_query($sql);
$data = mysql_fetch_array($result);
```
`mysql_fetch_array` returns an array with both associative and numeric keys
<http://nz.php.net/manual/en/function.mysql-fetch-array.php> | ```
how about this
$data = array(
'one' => 'something',
'two' => 'else',
'three' => 'completely'
) ;
then
$keys = array_keys($data);
Then
$key = $keys[$index_you_want];
Then
echo $data[$key];
``` | Array with associative values accessed numerically | [
"",
"php",
"associative-array",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.