Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What are some of the disadvantages of using an external JS file over including the JS as a part of the ASPX page?
I need to make an architectural decision and heard from coworkers that external JS does not play nice sometimes. | The only downside that I am aware of is the extra HTTP request needed. That downside goes away as soon as the Javascript is used by two pages or the page is reloaded by the same user. | One con is that the browser can't cache the JS if it's in the page. If you reference it externally the browser will cache that file and not re-download it every time you hit a page. With it embedded it'll just add to the file-size of every page.
Also maintainability is something to keep in mind. If it's common JS it'll be a bit more of a pain to make a change when you need to update X number of HTML files' script blocks instead of one JS file.
Personally I've never run into an issue with external files vs embedded. The only time I have JS in the HTML itself is when I have something to bind on document load specifically for that page. | Cons of external JavaScript file over inline JavaScript | [
"",
"asp.net",
"javascript",
""
] |
Is there a way to externalize HQL named queries to an external file. I have too many named queries and using `@NamedQueries` and `@NamedQuery` at the head of my entities classes is hurting.
Is there a way to externalize to several files? | You can put the queries into `package-info.java` class, in, say, root package of your domain objects. However, you must use Hibernate's own `@NamedQueries` and `@NamedQuery` annotations, rather than those from `javax.persistence`.
Example `package-info.java` file:
```
@org.hibernate.annotations.NamedQueries({
@org.hibernate.annotations.NamedQuery(
name = "foo.findAllUsers",
query="from Users")
})
package com.foo.domain;
```
Then, you have to add the package to your `AnnotationConfiguration`. I use Spring, so there it's a matter of setting `annonatedPackages` property:
```
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
...
</list>
</property>
<property name="annotatedPackages">
<list>
<value>com.foo.domain</value>
</list>
</property>
```
You can also put type and filter definitions in the same file as well. | I don't think that this is possible as Annotation attribute/property values must be available at compile time. Therefore, Strings cannot be externalized to a file that needs to be read in by some sort of process.
I tried to find if there was something that package-info.java might be able to provide, but could not find anything.
An alternative strategy for organization could be storing the queries as constants in a Class.
**In your entity class:**
```
@NamedQuery(name="plane.getAll", query=NamedQueries.PLANE_GET_ALL)
```
**Then define a class for your query constants:**
```
public class NamedQueries {
...
public static final String PLANE_GET_ALL = "select p from Plane p";
...
}
``` | How do I externalize named queries in a Hibernate annotations app? | [
"",
"java",
"hibernate",
"hql",
""
] |
With a COM interface method declared as this:
```
[ object,
uuid(....),
]
interface IFoo : IUnknown
{
HRESULT Foo([in, out] CACLSID * items);
}
```
With regards to marshalling, is the server allowed to reallocate the counted array? (I *think* it is, but I am not sure anymore)
Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.
**[edit]** please note that [CACLSID](http://msdn.microsoft.com/en-us/library/bb401564.aspx) is already an array, containing a count and a pointer. | I have not done COM for a very long time but is it even possible to allocate a new array? In that case should it not be `CACLSID ** items` ? | You should give the Count as the second parameter which indicates the space for so many number of elements, using this COM library marshals the elements | may COM server reallocate ([in, out] CACLSID * arg)? | [
"",
"c++",
"com",
"marshalling",
"midl",
""
] |
I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:
```
def read(self, filename):
fc = read_100_mb_file(filename)
self.process(fc)
def process(self, content):
# do some processing of file content
```
Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc?
When should I use garbage collection? I know about the gc module, but do I call it after I `del fc` for example?
**update**
p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows). | I'd suggest looking at the [presentation by David Beazley](http://www.dabeaz.com/generators/) on using generators in Python. This technique allows you to handle a lot of data, and do complex processing, quickly and without blowing up your memory use. IMO, the trick isn't holding a huge amount of data in memory as efficiently as possible; the trick is avoiding loading a huge amount of data into memory at the same time. | Before you start tearing your hair out over the garbage collector, you might be able to avoid that 100mb hit of loading the entire file into memory by using a memory-mapped file object. See the [mmap](http://docs.python.org/library/mmap.html) module. | memory use in large data-structures manipulation/processing | [
"",
"python",
"data-structures",
"memory-leaks",
"garbage-collection",
""
] |
What is a good strategy for dealing with generated code? One of our projects uses Apache CXF's *wsdl2java* tool to generate JAX-WS stubs for a set of wsdls. How should this code be dealt with?
There are two options that I can see:
1. Generate the stubs once and store them in version control. With this, you don't have to deal with IDE classpath issues since you have the source files right there in your tree (or nearby). However, you have a lot of extra clutter in version control in addition to the temptation for someone to monkey with the generated code
2. The stubs are generated every time at build time. This reverses the pros/cons for #1 in that the developer now has to deal run the build script and add the resulting jars to his/her classpath.
We went with #2 because the annoyance of classpath related issues seemed to outweigh the problems detailed in #1.
What are other people doing? Does anyone have any recommendations to streamline this process? | My attitude is that generated code should practically never be stored in version control. There has to be a compelling reason to do it. I typically create an ant task "build-for-eclipse" that builds all generated code. I run that, refresh the directory into which generated code is created, and voilà, I am fit to go.
The goal is that you have a "one-button" trivial task that any developer can do so they'll have all the source -- generated and not -- in their IDE, but that no *output* of anything is stored in source control. If it's the *output* of a generator, then by definition it's not *source*. :-)
This should safely meet everyone's needs. | I've tried it both ways, and settled on not storing generated code as a general rule. It can be a problem when there are slight, trivial differences, and it looks like there's a changed in revision control, and there really is nothing there of importance. Also, with #1, you can end up putting a lot of junk in your repositories, particularly in situations where the generated code is binary. Most repos don't store diffs of binary code, but complete copies.
Even in situations like yours, where the generated stuff is text, I tend not to store it, unless I absolutely must make a code change to it to get it to work. | How do you deal with generated code? | [
"",
"java",
""
] |
I am building an AI for an RTS game. (For the [Spring RTS engine](http://spring.clan-sy.com/), if anyone is interested.) The way I have set it up it consists mainly of a collection of Components that communicate by means of fired Events. Every component has a method handleEvent(Event) that receives events fired by the other components.
Event is an interface. A hierarchy exists, each subclass providing more detailed information on the the event they represent, which can be accessed by using the getter methods specific to that class. As an example, the class UnitGainedEvent implements the Event interface. This class has a subclass UnitFinishedEvent (which indicates construction of a unit or building is completed, for anyone that is curious.)
Not every component will be interested in all events, so I would like to let Components simply pick the events they are interested in and receive only those. Also, the set of possible events is extendable, so it is not a valid option to let Components have designated methods for each Event type. Initially I thought the visitor pattern might help me with this problem, but it fails because it also requires a fixed set of Event types. (I'm not 100% sure I understand the pattern correctly. Please do correct me if I'm wrong.)
So far, the only solution I have found is to implement each Component's handleEvent(Event) method something like this:
```
public int handleEvent(Event event)
{
if (event instanceof UnitGainedEvent)
{
UnitGainedEvent unitGainedEvent = (UnitGainedEvent) event;
// things to do if I lost a unit
}
else if (event instanceof UnitLostEvent)
{
UnitLostEvent unitLostEvent = (UnitLostEvent) event;
// things to do if I lost a unit
}
// etc.
}
```
However, I don't really like having to cast the events to the specific Event classes.
Now, remembering that method overloading can be used to invoke different methods depending on the runtime type of a parameter, I quickly came up with a brilliant solution, elegant as it was simple: I could create a base class with an empty implementation of handleEvent(Event), and simply have subclasses receive the events they are interested in by creating a method handleEvent(UnitGainedEvent unitGainedEvent), for example.
Wanting to make sure it would work I set up a quick test case:
```
public class Main
{
public static void main(String[] args)
{
handleEvent(new UnitGainedEvent(null));
}
public static void handleEvent(Event event)
{
System.out.println("Handling generic Event");
}
public static void handleEvent(UnitGainedEvent event)
{
System.out.println("Handling UnitGainedEvent");
}
}
```
And to my great satisfaction, this code actually prints 'Handling UnitGainedEvent.' So I set about implementing.
My Component base class looks like this:
(Well, not really. This is the Component class stripped of everything not relevant to the problem I'd like to demonstrate.)
```
public class Component
{
public void handleEvent(Event event)
{
System.out.println("Handling Event");
}
}
```
And this is an example of a subclass:
```
public class SomeComponent extends Component
{
public void handleEvent(UnitGainedEvent unitGainedEvent)
{
System.out.println("Handling UnitGainedEvent");
}
}
```
In order to test the setup, I use the following main class:
```
public class Main
{
public static void main(String[] args)
{
Component component = new SomeComponent();
component.handleEvent(new UnitGainedEvent(null));
}
}
```
So I run the code, and to my great surprise, the result is a neatly printed 'Handling Event.' Interestingly enough, if I change the type of the component variable to SomeComponent, it *does* print 'Handling UnitGainedEvent.'
For some reason or another, the system blindly invokes the Component class' handleEvent(Event) method, instead if the overloading SomeComponent's handleEvent(UnitGainedEvent).
(I would be interested in hearing Sun's reasoning behind this, thought it isn't really relevant to my question - not like they'll fix it just because a handful of people would find it a very useful feature.)
Scouring the net tells me that other people have run into the same problem. Very few people, from the minute amount of information I find, but people nonetheless, although I find more information on general method overloading and overriding than I ever wanted to know. However, in the end, I fail to find a solution.
Now, my (fairly obvious) question is, is there some way to get around this problem? Failing that, can anyone think of, or help me find, another solution that is equally convenient?
Edit: I can hardly believe I have answers after only ten minutes. I'm pleasantly surprised. :)
However, most of the answers so far suggest in one form or another that I make one seperate method for each possible Event type. Technically this is possible, but this would require me to go back into the code and add a new method every time someone comes up with a new Event type. Which I've learned is bad coding practice. (Plus, I already have some 20+ Event types, and I'm not even done yet.)
Instead, I would rather do use the solution involving casting, as described above. At least that way I can assure that unknown event types are simply ignored, leaving me free to only handle those events where I want to use them.
I'm really hoping for a solution that combines the best of both however. No casting, and no going back into my code for each event type.
Many thanks in advance,
Loid Thanead | Use reflection to get your desired effect. When you dispatch an event to a listener, look at its methods to find a best-match (what you were hoping the compiler would do for you).
You would obviously want to cache the invocation targets or else performance could get painful. | > So I run the code, and to my great
> surprise, the result is a neatly
> printed 'Handling Event.'
> Interestingly enough, if I change the
> type of the component variable to
> SomeComponent, it does print 'Handling
> UnitGainedEvent.' For some reason or
> another, the system blindly invokes
> the Component class'
> handleEvent(Event) method, instead if
> the overloading SomeComponent's
> handleEvent(UnitGainedEvent).
Overloading doesn't really work that way. You need to invoke the overloaded method on the subclass, not the superclass. Since you're referencing the Component type, Java doesn't know that you've overloaded the method in a subclass, it only knows if you've **overridden** it or not.
Do you really need the generic handleEvent(Event) class? Can you instead write handleEvent() methods for the specific Event subclasses without having a handler for the Event superclass? | Overloading a method of a superclass | [
"",
"java",
"polymorphism",
""
] |
What's the easiest way to build an applet that has a view with components that are bound to model data and update when the model is updated?
Ideally as little code as possible, preferable none/declarative :)
If a component type is needed for explanation, please consider a JLabel whose text is bound to a bean with a String getText() accessor - but if that's just plain dumb, please give me a better example!
Thanks! | unless your model is very small, data binding is not so easy:
<http://www.jgoodies.com/> examples: <http://www.java2s.com/Code/Java/Swing-Components/Data-Binding.htmjgoodies>
BeansBinding: <http://www.artima.com/forums/flat.jsp?forum=276&thread=213997> | I suggest avoiding `PropertyChangeEvent`s and anything beanish.
Make fine grained models: for instance, a model representing a piece of text (Document is difficult to use and heavyweight, but you can use adapters). You will also need to be able to model constraints (integer bounds for example) and derived models. Then your "real" "business" are can be composites, with no setters or event handling. Avoid duplicating data in the model.
With simple models available, wiring to components is easy. For instance to create a label wired to a text model, have a factory method that takes the text model and returns a new wired-up `JLabel`. | Java Applet - MVC - How to bind model to view? | [
"",
"java",
"model-view-controller",
"binding",
"model",
"view",
""
] |
I have few methods that returns different Generic Lists.
Exists in .net any class static method or whatever to convert any list into a datatable? The only thing that i can imagine is use Reflection to do this.
IF i have this:
```
List<Whatever> whatever = new List<Whatever>();
```
(This next code doesn't work of course, but i would like to have the possibility of:
```
DataTable dt = (DataTable) whatever;
``` | Here's a nice 2013 update using [FastMember](https://www.nuget.org/packages/FastMember/) from NuGet:
```
IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data)) {
table.Load(reader);
}
```
This uses FastMember's meta-programming API for maximum performance. If you want to restrict it to particular members (or enforce the order), then you can do that too:
```
IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description")) {
table.Load(reader);
}
```
Editor's *Dis*/**claimer:** FastMember is a Marc Gravell project. It's gold and full-on flies!
---
Yes, this is pretty much the exact opposite of [this](https://stackoverflow.com/questions/545328/asp-net-potential-memory-leaks-converting-datatable-to-lists/545429#545429) one; reflection would suffice - or if you need quicker, [`HyperDescriptor`](https://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces) in 2.0, or maybe `Expression` in 3.5. Actually, `HyperDescriptor` should be more than adequate.
For example:
```
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
```
Now with one line you can make this many many times faster than reflection (by enabling [`HyperDescriptor`](https://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces) for the object-type `T`).
---
Edit re performance query; here's a test rig with results:
```
Vanilla 27179
Hyper 6997
```
I suspect that the bottleneck has shifted from member-access to `DataTable` performance... I doubt you'll improve much on that...
Code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
public class MyData
{
public int A { get; set; }
public string B { get; set; }
public DateTime C { get; set; }
public decimal D { get; set; }
public string E { get; set; }
public int F { get; set; }
}
static class Program
{
static void RunTest(List<MyData> data, string caption)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
GC.WaitForFullGCComplete();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < 500; i++)
{
data.ToDataTable();
}
watch.Stop();
Console.WriteLine(caption + "\t" + watch.ElapsedMilliseconds);
}
static void Main()
{
List<MyData> foos = new List<MyData>();
for (int i = 0 ; i < 5000 ; i++ ){
foos.Add(new MyData
{ // just gibberish...
A = i,
B = i.ToString(),
C = DateTime.Now.AddSeconds(i),
D = i,
E = "hello",
F = i * 2
});
}
RunTest(foos, "Vanilla");
Hyper.ComponentModel.HyperTypeDescriptionProvider.Add(
typeof(MyData));
RunTest(foos, "Hyper");
Console.ReadLine(); // return to exit
}
}
``` | I had to modify Marc Gravell's sample code to handle nullable types and null values. I have included a working version below. Thanks Marc.
```
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
``` | Convert generic List/Enumerable to DataTable? | [
"",
"c#",
"list",
"generics",
"datatable",
""
] |
I have an XML parser that crashes on incomplete XML data. So XML data fed to it could be one of the following:
```
<one><two>twocontent</two</one>
<a/><b/> ( the parser treats it as two root elements )
```
Element attributes are also handled ( though not shown above ).
Now, the problem is when I read data from socket I get data in fragments. For example:
```
<one>one
content</two>
</one>
```
Thus, before sending the XML to the parser I have to construct a valid XML and send it.
What programming construct ( like iteration, recursion etc ) would be the best fit for this kind of scenario.
I am programming in C++.
Please help. | Are there multiple writers? Why isn't your parser validating the XML?
Use a tree, where every node represents an element and carries with it a dirty bit. The first occurrence of the node marks it as dirty i.e. you are expecting a closing tag, unless of course the node is of the form `<a/>`. Also, the first element, you encounter is the root.
When you hit a dirty node, keep pushing nodes in a stack, until you hit the closing tag, when you pop the contents. | Short answer: *You're doing it wrong.*
Your question confuses two separate issues:
1. **Parsing of data that is not well-formed XML *at all***, i.e. so-called tag soup.
Example: Files generated by programmers who do not understand XML or have lousy coding practices.
* It is not unfair to say: A file that is not well-formed XML is not an XML document at all. Every correct XML parser will reject it. Ideally you would work to correct the source of this data and make sure that proper XML is generated instead.
* Alternatively, use a tag soup parser, i.e. a parser that does error correction.
Useful tag soup parsers are often actually HTML parsers. [tidy](http://tidy.sourceforge.net/) has already been pointed out in another answer.
Make certain that you understand what correction steps such a parser actually performs, since there is no universal approach that could fix XML. Tidy in particular is very aggressive at "repairing" the data, more aggressive than real browsers and the HTML 5 spec, for example.
2. **XML parsing from a socket**, where data arrives chunk-by-chunk in a stream. In this situation, the XML document might be viewed as "infinite", with chunks being processed as the appear, long before a final end tag for the root element has been seen.
Example: XMPP is a protocol that works like this.
* The solution is to use a pull-based parser, for example the [XMLTextReader](http://www.xmlsoft.org/xmlreader.html) API in libxml2.
* If a tree-based data structure for the XML child elements being parser is required, you can build a tree structure for each such element that is being read, just not for the entire document. | XML Parsing Problem | [
"",
"c++",
"xml",
""
] |
I am a [Google Maps](https://en.wikipedia.org/wiki/Google_Maps) API (JavaScript) developer. I have noticed that Google uses a JavaScript [minifier](https://en.wikipedia.org/wiki/Minification_(programming)) that has the following features:
1. Shortens variables, properties, arguments, classes, function and method names, obfuscating the code (e.g., function1 → a, function2 → b, and function3 → c)
2. Some variables, classes, properties and methods can be marked to not be crunched, so its name remains the same as documented in the API manual.
3. It is rerun in each subversion of the API, like a build task, I noticed that because of the crunched names changes from one version to another.
I have not found a JavaScript minifier in the whole Internet with those features. Is there one? | Google has now opened up [the minifier](http://closure-compiler.appspot.com/home) they use, along with some other internal JavaScript goodies.
It's all under the name ["Closure Tools"](http://code.google.com/closure/) and [was announced](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html) earlier this month. | Here are the minifiers I know of:
Dean Edwards' [packer](http://dean.edwards.name/packer/); YUI [Compressor](http://developer.yahoo.com/yui/compressor/); [JSMIN](http://crockford.com/javascript/jsmin); and Dojo [compressor](http://dojotoolkit.org/docs/shrinksafe)
In addition to these, the [GWT compiler](http://code.google.com/webtoolkit/overview.html) does quite a bit to make efficient JavaScript files out of Java files. It wouldn't surprise me if that is what they use. | Which JavaScript minifier (cruncher) does the same things that the one Google uses for its JavaScript APIs? | [
"",
"javascript",
"obfuscation",
"minify",
""
] |
I'm making an interface to a DLL library, so i can use it with Java.
I need my native function to modify the value of a jlong parameter. Like the parameter was passed by reference.
My Java method must have the exact parameters as the native function MPUSBWrite shown down here.
Example of actual not working code:
The MPUSBWrite gets its 4th parameter as reference and modify itrs value.
I always get 0 when i read the pLength passed variable.
Java:
```
public static native boolean Write(long handle, byte[] pData, int dwLen, long pLength, int dwMilliseconds);
```
Native C++:
```
JNIEXPORT jboolean JNICALL Java_jPicUsb_iface_Write
(JNIEnv *env, jclass jc, jlong handle, jbyteArray pData, jint dwLen, jlong pLength, jint dwMilliseconds) {
jniByteArray b(env, pData);
DWORD res = MPUSBWrite((HANDLE)handle,b.getBytes(),dwLen,(PDWORD)pLength,dwMilliseconds);
if (res) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
```
Is there a way my C++ code modify the value of the pLength variable by reference? | No.
Your best option, if you truly need to do this, is to define your fourth parameter as a long[], and have your JNI code update the array element.
Actually, your best option would be to consider why you can't return the long from the method. | [SWIG](http://www.swig.org/) supports this functionality.
With SWIG you can update Java parameter values like pointers in C++. This is working for Object parameters very fine. You can put a Long object in to get it work.
With Swig you can write a layer between java and C++ where you can put the pointer value after a function call into the Java object. Swig also generates the Java classes, you have to us to call the C++ functions.
When the C++ function contains another C++ class as parameter, Swig generates this C++ class as Java object with getter,setter and all C++ functions you want to call.
For this functionality Swig has a special language you have to write in a VisualStudio project. but all this is described in the [Swig Manual](http://www.swig.org/Doc1.1/PDF/SWIGManual.pdf)
> SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages. SWIG is used with different types of languages including common scripting languages such as Perl, PHP, Python, Tcl and Ruby. The list of supported languages also includes non-scripting languages such as C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), Java, Lua, Modula-3, OCAML, Octave and R. | Passing pointer from java to native | [
"",
"java",
"parameters",
"reference",
"java-native-interface",
""
] |
What does this JavaScript do exactly?
```
parent.kill = 1;
```
This is used in a project I'm working on to do some sort of session expiration but I've never seen it before. It's loaded in an `iframe` so I'm assuming that it is targeting the DOM `document.window`. | The child iframe is setting the variable `kill` in the `parent` `window`'s global scope. What the `parent` does with that variable cannot be determined from just that line of javascript. | to piggy-back off @crescentfresh's answer, [here](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Reserved_Words) is a list of reserved keywords. | What does "kill" do in JavaScript? | [
"",
"javascript",
"dom",
"iframe",
"kill",
""
] |
Is it possible to seed the random number generator ([`Math.random`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random)) in JavaScript? | No, it is not possible to seed `Math.random()`, but it's fairly easy to write your own generator, or better yet, use an existing one.
Check out: [this related question](https://stackoverflow.com/questions/424292/how-to-create-my-own-javascript-random-number-generator-that-i-can-also-set-the-s).
Also, see David Bau's blog for [more information on seeding](http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html#more). | No, it is not possible to seed `Math.random()`. The [ECMAScript specification](https://tc39.es/ecma262/#sec-math.random) is intentionally vague on the subject, providing no means for seeding nor require that browsers even use the same algorithm. So such a function must be externally provided, which thankfully isn't too difficult.
I've implemented a number of good, short and fast **Pseudorandom number generator** (PRNG) functions in plain JavaScript. All of them can be seeded and provide high quality numbers. These are not intended for security purposes--if you need a seedable CSPRNG, look into [ISAAC](https://github.com/macmcmeans/isaacCSPRNG).
**First of all, take care to initialize your PRNGs properly.** To keep things simple, the generators below have no built-in seed generating procedure, but accept one or more 32-bit numbers as the initial *seed state* of the PRNG. Similar or sparse seeds (e.g. a simple seed of 1 and 2) have low entropy, and can cause correlations or other randomness quality issues, sometimes resulting in the output having similar properties (such as randomly generated levels being similar). To avoid this, it is best practice to initialize PRNGs with a well-distributed, high entropy seed and/or advancing past the first 15 or so numbers.
There are many ways to do this, but here are two methods. Firstly, [hash functions](https://en.wikipedia.org/wiki/Hash_function) are very good at generating seeds from short strings. A good hash function will generate very different results even when two strings are similar, so you don't have to put much thought into the string. Here's an example hash function:
```
function cyrb128(str) {
let h1 = 1779033703, h2 = 3144134277,
h3 = 1013904242, h4 = 2773480762;
for (let i = 0, k; i < str.length; i++) {
k = str.charCodeAt(i);
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
}
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
h1 ^= (h2 ^ h3 ^ h4), h2 ^= h1, h3 ^= h1, h4 ^= h1;
return [h1>>>0, h2>>>0, h3>>>0, h4>>>0];
}
// Side note: Only designed & tested for seed generation,
// may be suboptimal as a general 128-bit hash.
```
Calling `cyrb128` will produce a 128-bit hash value from a string which can be used to seed a PRNG. Here's how you might use it:
```
// Create cyrb128 state:
var seed = cyrb128("apples");
// Four 32-bit component hashes provide the seed for sfc32.
var rand = sfc32(seed[0], seed[1], seed[2], seed[3]);
// Or... only one 32-bit component hash is needed for splitmix32.
var rand = splitmix32(seed[0]);
// You can now generate repeatable sequences of random numbers:
rand(); // 0.8865117691457272
rand(); // 0.24518639338202775
```
*Note: If you want a slightly more robust 128-bit hash, consider [MurmurHash3\_x86\_128](https://github.com/bryc/code/blob/master/jshash/hashes/murmurhash3_128.js), it's more thorough, but intended for use with large arrays. Since this operates on byte arrays, strings require conversion using something like `Array.from("hello", c=>c.charCodeAt())`.*
Alternatively, simply choose some dummy data to pad the seed with, and advance the generator beforehand a few times (12-20 iterations) to mix the initial state thoroughly. This has the benefit of being simpler, and is often used in reference implementations of PRNGs, but it does limit the number of initial states:
```
var seed = 1337 ^ 0xDEADBEEF; // 32-bit seed with optional XOR value
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
var rand = sfc32(0x9E3779B9, 0x243F6A88, 0xB7E15162, seed);
for (var i = 0; i < 15; i++) rand();
```
Note: the output of these PRNG functions produce a positive 32-bit number (0 to 232-1) which is then converted to a floating-point number between 0-1 (0 inclusive, 1 exclusive) equivalent to `Math.random()`, if you want random numbers of a specific range, read [this article on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random). If you only want the raw bits, simply remove the final division operation.
JavaScript numbers can only represent whole integers up to 53-bit resolution. And when using bitwise operations, this is reduced to 32. Modern PRNGs in other languages often use 64-bit operations, which require shims when porting to JS that can *drastically* reduce performance. The algorithms here only use 32-bit operations, as it is directly compatible with JS.
> Now, onward to the the generators. *(I maintain the full list with references and license info [here](https://github.com/bryc/code/blob/master/jshash/PRNGs.md))*
---
### sfc32 (Simple Fast Counter)
**sfc32** is part of the [PractRand](http://pracrand.sourceforge.net/) random number testing suite (which it passes of course). sfc32 has a 128-bit state and is very fast in JS.
```
function sfc32(a, b, c, d) {
return function() {
a |= 0; b |= 0; c |= 0; d |= 0;
let t = (a + b | 0) + d | 0;
d = d + 1 | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
c = c + t | 0;
return (t >>> 0) / 4294967296;
}
}
const r = () => Math.random();
const now = Date.now();
const prng = sfc32(now * r(), now * r(), now * r(), now * r());
for(let i=0; i<10; i++) console.log(prng());
```
You may wonder what the `| 0` and `>>>= 0` are for. These are essentially 32-bit integer casts, used for performance optimizations. `Number` in JS are basically floats, but during bitwise operations, they switch into a 32-bit integer mode. This mode is processed faster by JS interpreters, but any multiplication or addition will cause it to switch back to a float, resulting in a performance hit.
### SplitMix32
A 32-bit state PRNG that was made by taking MurmurHash3's mixing function, adding a incrementor and tweaking the constants. It's potentially one of the best 32-bit PRNGs so far; even the author of Mulberry32 [considers it to be the better choice](https://gist.github.com/tommyettinger/46a874533244883189143505d203312c?permalink_comment_id=4365431#gistcomment-4365431). It's also just as fast.
```
function splitmix32(a) {
return function() {
a |= 0;
a = a + 0x9e3779b9 | 0;
let t = a ^ a >>> 16;
t = Math.imul(t, 0x21f0aaad);
t = t ^ t >>> 15;
t = Math.imul(t, 0x735a2d97);
return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
}
}
const prng = splitmix32(Date.now() * Math.random())
for(let i=0; i<10; i++) console.log(prng());
```
I would recommend this if you just need a simple but *good* PRNG and don't need billions of random numbers (see [Birthday problem](https://en.wikipedia.org/wiki/Birthday_problem)).
### Mulberry32
Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has acceptable quality randomness (author states it passes all tests of [gjrand](http://gjrand.sourceforge.net/) testing suite and has a full 232 period, but I haven't verified).
```
function mulberry32(a) {
return function() {
let t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
const prng = mulberry32(Date.now() * Math.random())
for(let i=0; i<10; i++) console.log(prng());
```
### xoshiro128\*\*
**xoshiro128\*\*** (Vigna & Blackman, 2018) is part of the [Xorshift](https://en.wikipedia.org/wiki/Xorshift) lineage (Vigna was also responsible for the Xorshift128+ algorithm powering most `Math.random` implementations under the hood). It is the fastest generator that offers a 128-bit state.
```
function xoshiro128ss(a, b, c, d) {
return function() {
let t = b << 9, r = b * 5;
r = (r << 7 | r >>> 25) * 9;
c ^= a;
d ^= b;
b ^= c;
a ^= d;
c ^= t;
d = d << 11 | d >>> 21;
return (r >>> 0) / 4294967296;
}
}
const r = () => Math.random();
const now = Date.now();
const prng = xoshiro128ss(now * r(), now * r(), now * r(), now * r());
for (let i = 0; i < 10; i++) console.log(prng());
```
The authors claim it passes randomness tests well ([albeit with caveats](http://prng.di.unimi.it/)). Other researchers have pointed out that it fails some tests in TestU01 (particularly LinearComp and BinaryRank). In practice, it should not cause issues when floats are used (such as in these implementations), but may cause issues if relying on the raw lowest order bit.
### JSF (Jenkins' Small Fast)
This is JSF or 'smallprng' by Bob Jenkins (2007), who also made [ISAAC](https://en.wikipedia.org/wiki/ISAAC_(cipher)) and [SpookyHash](https://en.wikipedia.org/wiki/Jenkins_hash_function#SpookyHash). It [passes](http://www.pcg-random.org/posts/bob-jenkins-small-prng-passes-practrand.html) PractRand tests and should be quite fast, although not as fast as sfc32.
```
function jsf32(a, b, c, d) {
return function() {
a |= 0; b |= 0; c |= 0; d |= 0;
let t = a - (b << 27 | b >>> 5) | 0;
a = b ^ (c << 17 | c >>> 15);
b = c + d | 0;
c = d + t | 0;
d = a + t | 0;
return (d >>> 0) / 4294967296;
}
}
const r = () => Math.random();
const now = Date.now();
const prng = jsf32(now * r(), now * r(), now * r(), now * r());
for (let i = 0; i < 10; i++) console.log(prng());
``` | Seeding the random number generator in Javascript | [
"",
"javascript",
"random",
"random-seed",
"seeding",
""
] |
I am working on an app that will need to handle very large numbers.
I checked out a few available LargeNumber classes and have found a few that I am happy with. I have a class for large integers and for large floating point numbers.
Since some of the numbers will be small and some large the question is whether it is worth checking the length of the number and if it is small use a regular C# int or double and if is is large use the other classes I have or if I am already using the Large Integer and Large Float classes I should just stick with them even for smaller numbers.
My consideration is purely performance. Will I save enough time on the math for the smaller numbers that it would be worthwhile to check each number after is is put in. | Really hard to tell - Depends on your 3rd party libraries :)
Best bet would be to use the System.Diagnostics.StopWatch class, do a gazzillion different calculations, time them and compare the results, I guess ..
[EDIT] - About the benchmarks, I'd do a series of benchmarks your largeInt-type to do the calculations on regular 32/64 bits numbers, and a series checking if the number can fit in the regular Int32/Int64 types (which they should), "downcasting" them to these types, and then run the same calculations using these types. From your question, this sounds like what you'll be doing if the built-in types are faster..
If your application is targetted for more people than yourself, try to run them on different machines (single core, multicore, 32bit, 64bit platforms), and if the platform seems to have a large impact in the time the calculations take, use some sort of strategy-pattern to do the calculations differently on different machines.
Good luck :) | I would expect that a decent large numbers library would be able to do this optimization on it's own... | Types for large numbers | [
"",
"c#",
"math",
"largenumber",
""
] |
I have a class
```
template <unsigned int N>
class StaticVector {
// stuff
};
```
How can I declare and define in this class a static factory method returning a StaticVector<3> object, sth like
```
StaticVector<3> create3dVec(double x1, double x2, double x2);
```
? | "How can I declare and define in this class"
In what class? You've defined a class template, not a class. You can't call a static function of a class template itself, you have to call a particular version of the static function that's part of a real class.
So, do you want the template (and hence all instantiations of it) to have a function returning a StaticVector<3>, or do you want one particular instantiation of that template to have a function returning a StaticVector<3>?
If the former:
```
template <unsigned int N>
struct SV {
int contents[N];
static SV<3> get3dVec(int x, int y, int z) {
SV<3> v;
v.contents[0] = x;
v.contents[1] = y;
v.contents[2] = z;
return v;
}
};
int main() {
SV<3> v = SV<1>::get3dVec(1,2,3);
}
```
works for me.
If the latter (you only want get3dVec to be a member of SV<3>, not of all SV<whatever>), then you want template specialisation:
```
template <unsigned int N>
struct SV {
int contents[N];
};
template<>
struct SV<3> {
int contents[3]; // must be re-declared in the specialization
static SV<3> get3dVec(int x, int y, int z) {
SV<3> v;
v.contents[0] = x;
v.contents[1] = y;
v.contents[2] = z;
return v;
}
};
int main() {
SV<3> v = SV<1>::get3dVec(1,2,3); // compile error
SV<3> v = SV<3>::get3dVec(1,2,3); // OK
}
```
If for no other reason than to make the calling code look nicer by omitting the basically irrelevant template parameter, I agree with Iraimbilanja that normally a free function (in a namespace if you're writing for re-use) would make more sense for this example.
C++ templates mean that you don't need static functions as much in C++ as you do in Java: if you want a "foo" function that does one thing for class Bar and another thing for class Baz, you can declare it as a function template with a template parameter that can be Bar or Baz (and which may or may not be inferred from function parameters), rather than making it a static function on each class. But if you do want it to be a static function, then you have to call it using a specific class, not just a template name. | First, i believe you originally mean to return
```
StaticVector<N>
```
Instead of always a specialization with N==3 . So, what you want to do is writing it like this:
```
template <unsigned int N>
class StaticVector {
public:
// because of the injected class-name, we can refer to us using
// StaticVector . That is, we don't need to name all template
// parameters like StaticVector<N>.
static StaticVector create3dVec(double x1, double x2, double x2) {
// create a new, empty, StaticVector
return StaticVector();
}
};
```
If you really want to always return a 3dVector, you would probably want to restrict it to N==3, so that for example `StaticVector<4>::create3dVec` doesn't work. You can do that using the technique described [**here**](https://stackoverflow.com/questions/347096/how-can-i-get-a-specialized-template-to-use-the-unspecialized-version-of-a-member/347107#347107).
If you want to have a function like `createVec` that works with any size, you probably want to replace the parameters with an array. You can do otherwise, but that's advanced and requires some macro tricks applied with boost::preprocessor. It's not worth it i think. The next C++ version will provide *variadic templates* for this purpose. Anyway,consider using something like this:
I think it would only complicate this unnecessarily here. A quick solution is to use a boost::fusion::vector instead, putting it into the class template instead of the version above:
```
static StaticVector createVec(double (&values)[N]) {
// create a new, empty, StaticVector, initializing it
// with the given array of N values.
return StaticVector();
}
```
You could use it with
```
double values[3] = {1, 2, 3};
StaticVector<3> v = StaticVector<3>::createVec(values);
```
Note that it accepts an array by reference. You can't give it a pointer. That is because it matches the use of parameters: You couldn't provide less or more arguments for the other way too. It will also protect you from cases like this:
```
// oops, values is a null pointer!
StaticVector<3> v = StaticVector<3>::createVec(values);
```
An array never can be a null pointer. Of course if you like, you can always change the array parameter to a pointer. It would just be my personal preference :) | Factory method returning an concrete instantiation of a C++ template class | [
"",
"c++",
"templates",
"factory",
""
] |
Is there any way to check if a array exists or has a value in a specific element?
I have this line of code
```
if (rummen[positionX, positionY].Levandesaker[0].alive == true)
```
And it works fine as long as it exists. But what I want to do is
```
if (rummen[positionX, positionY].Levandesaker != null)
{
if (rummen[positionX, positionY].Levandesaker[0].alive == true)
{
}
}
```
Does anyone know what Im after or can help me out with what im looking for? | ```
if (rummen[positionX, positionY].Levandesaker != null &&
rummen[positionX, positionY].Levandesaker.Count > 0)
{
if (rummen[positionX, positionY].Levandesaker[0].alive == true)
{
}
}
```
I'm not entirely sure which array you're talking about now that I think about it. Are you referring to Levandesaker or rummen? | I hope I interpreted this question right!
An array is of constant size, and contains a value for every index from 0 to the upper bound of the array.
So to check whether a position in the array exists, you can just make sure it's less than the upper bound. Something like this should cover absolutely every condition (assuming rummen itself is not null!):
```
// make sure rummen contains the [positionX, positionY] element
if(rummen.GetUpperBound(0) > positionX && rummen.GetUpperBound(1) > positionY)
{
if(rummen[positionX, positionY].Levandesaker != null)
{
// make sure Levandsaker contains at least one element
if(rummen[positionX, positionY].Levandsaker.Length > 0)
{
if(rummen[positionX, positionY].Levandesaker[0].alive == true)
{
}
}
}
}
```
EDIT: Sorry, fixed C#-specific syntax. Also added a check on Levandsaker for demonstration purposes. | How to check if an array exists in C#? | [
"",
"c#",
"arrays",
""
] |
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based. | Alright, so I ended up going with the code I wrote [here, on my website](http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/) [link is dead, view on archive.org](https://web.archive.org/web/20140531203736/http://www.evanfosmark.com:80/2009/01/cross-platform-file-locking-support-in-python/) ([also available on GitHub](https://github.com/dmfrey/FileLock)). I can use it in the following fashion:
```
from filelock import FileLock
with FileLock("myfile.txt.lock"):
# work with the file as it is now locked
print("Lock acquired.")
``` | The other solutions cite a lot of external code bases. If you would prefer to do it yourself, here is some code for a cross-platform solution that uses the respective file locking tools on Linux / DOS systems.
```
try:
# Posix based file locking (Linux, Ubuntu, MacOS, etc.)
# Only allows locking on writable files, might cause
# strange results for reading.
import fcntl, os
def lock_file(f):
if f.writable(): fcntl.lockf(f, fcntl.LOCK_EX)
def unlock_file(f):
if f.writable(): fcntl.lockf(f, fcntl.LOCK_UN)
except ModuleNotFoundError:
# Windows file locking
import msvcrt, os
def file_size(f):
return os.path.getsize( os.path.realpath(f.name) )
def lock_file(f):
msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))
def unlock_file(f):
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, file_size(f))
# Class for ensuring that all file operations are atomic, treat
# initialization like a standard call to 'open' that happens to be atomic.
# This file opener *must* be used in a "with" block.
class AtomicOpen:
# Open the file with arguments provided by user. Then acquire
# a lock on that file object (WARNING: Advisory locking).
def __init__(self, path, *args, **kwargs):
# Open the file and acquire a lock on the file before operating
self.file = open(path,*args, **kwargs)
# Lock the opened file
lock_file(self.file)
# Return the opened file object (knowing a lock has been obtained).
def __enter__(self, *args, **kwargs): return self.file
# Unlock the file and close the file object.
def __exit__(self, exc_type=None, exc_value=None, traceback=None):
# Flush to make sure all buffered contents are written to file.
self.file.flush()
os.fsync(self.file.fileno())
# Release the lock on the file.
unlock_file(self.file)
self.file.close()
# Handle exceptions that may have come up during execution, by
# default any exceptions are raised to the user.
if (exc_type != None): return False
else: return True
```
Now, `AtomicOpen` can be used in a `with` block where one would normally use an `open` statement.
**WARNINGS:**
* If running on Windows and Python crashes before **exit** is called, I'm not sure what the lock behavior would be.
* The locking provided here is advisory, not absolute. All potentially competing processes must use the "AtomicOpen" class.
* As of (Nov 9th, 2020) this code only locks *writable* files on Posix systems. At some point after the posting and before this date, it became illegal to use the `fcntl.lock` on read-only files. | Locking a file in Python | [
"",
"python",
"file-locking",
""
] |
If you have an array of Java objects which have a primitive type (for example Byte, Integer, Char, etc). Is there a neat way I can convert it into an array of the primitive type? In particular can this be done without having to create a new array and loop through the contents.
So for example, given
```
Integer[] array
```
what is the neatest way to convert this into
```
int[] intArray
```
Unfortunately, this is something we have to do quite frequently when interfacing between Hibernate and some third party libraries over which we have no control. It seems this would be a quite common operation so I would be surprised if there's no shortcut.
Thanks for your help! | Unfortunately, there's nothing in the Java platform that does this. Btw, you also need to explicitly handle `null` elements in the `Integer[]` array (what `int` are you going to use for those?). | Once again, [Apache Commons Lang](http://commons.apache.org/proper/commons-lang/) is your friend. They provide [ArrayUtils.toPrimitive()](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive(java.lang.Integer[])) which does exactly what you need. You can specify how you want to handle nulls. | Converting an array of objects to an array of their primitive types | [
"",
"java",
"arrays",
"primitive-types",
""
] |
I'm creating a `UserControl` consisting of a `TextBox` and a `ListView`. I want keyboard focus to remain with the `TextBox` as long as the control has keyboard focus (selection changes in the `ListView` shouldn't remove keyboard focus from the `TextBox`).
I've tried catching `GotKeyboardFocus` in the `ListView` and passing keyboard focus back to the `TextBox` using `Keyboard.Focus(),` but this seems to cancel any selection operation in the `ListView`. The below code shows the problem. Does anyone know how to achieve this functionality?
```
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBox x:Name="TextBox1" />
<ListView x:Name="ListBox1" Keyboard.GotKeyboardFocus="ListBox1_GotKeyboardFocus">
<ListViewItem Content="Able" />
<ListViewItem Content="Baker" />
<ListViewItem Content="Charlie" />
</ListView>
</StackPanel>
</Window>
```
---
```
using System.Windows;
using System.Windows.Input;
namespace WpfApplication5
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void ListBox1_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
Keyboard.Focus(TextBox1);
}
}
}
``` | It looks like it's possible to change focus in the MouseUp event. I think if you do it too early, like in the GotKeyboardFocus event, you'll steal focus before the listview can handle the event and select the chosen item.
```
<StackPanel>
<TextBox x:Name="TextBox1" />
<ListView x:Name="ListBox1" MouseUp="ListBox1_MouseUp">
<ListViewItem Content="Able" />
<ListViewItem Content="Baker" />
<ListViewItem Content="Charlie" />
</ListView>
</StackPanel>
private void ListBox1_MouseUp(object sender, MouseButtonEventArgs e)
{
TextBox1.Focus();
}
``` | Instead, have you considered just capturing keystrokes and putting those keystrokes into your TextBox?
```
<Window PreviewKeyDown="Window_PreviewKeyDown" >
<Grid>
<TextBox x:Name="TextBox1" />
<ListBox />
</Grid>
</Window>
```
Then in your window's code-behind:
```
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
TextBox1.Text += e.Key.ToString();
}
```
You'll have to do extra work for anything like special characters (backspace, etc), and obviously a Key handler for your "Enter" or "Post" operation, but it gives you the ability to just free-form type while the Window has focus and to properly handle the keystrokes as necessary. | WPF Maintain Keyboard Focus | [
"",
"c#",
"wpf",
"keyboard",
"focus",
""
] |
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:
```
int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
FinalizeAndExit();
```
and using the event to signal the thread it must terminate
or just handling the ThreadAbortException to finalize the thread...
```
try
{
// Main execution
}
catch(ThreadAbortException e)
{
// FinalizeAndExit();
}
finally
{
}
```
I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.
What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x? | Generally, the first method it preferrable.
It's hard (if not impossible) to write code that will always handle a ThreadAbortException gracefully. The exception can occur in the middle of whatever the thread happens to be doing, so some situations can be hard to handle.
For example, the exception can occur after you have created a FileStream object, but before the reference is assigned to a variable. That means that you have an object that should be disposed, but the only reference to it is lost on the stack somewhere... | If I can I try to avoid using Thread.Abort.
The problem with Thread.Abort is that it could happen in (almost) any line of the executing code and might cause some "interesting" behavior (read: bugs).
Intead I prefer to have a point of exit on my code that checks for an event or variable to see if it the thread should stop running and gracefully exit. | ThreadAbortException vs graceful event handle exit in C# | [
"",
"c#",
"multithreading",
"exception",
""
] |
I'm trying to use a custom maven wagon extension to deploy a jar to my own repository. Can I somehow configure in settings.xml that it recognizes the custom url scheme to be used with the specific wagon or do I have to always modify pom files to contain the wagon extension?
---
There doesn't need to be a base pom or any pom available when using the deploy-file. Settings.xml is the only place which is guaranteed to be there, but I can't figure out how to use it to define extensions. | OK, ok, a correction: you cannot define the `<build>` element inside a `<profile>` defined in `settings.xml`. You could activate the profile in `settings.xml`, but define it in your `base-pom`.
Sorry, the only other way I could think of (probably what are you looking for), is to copy the extension jar directly under `$M2_HOME/lib`. All `$M2_HOME/lib/*.jar` are put in the classpath, so this must virtually have the same effect as an `<extension>`.
The extension however is better, because you can more easily control which version of the extension is used (e.g. trough the base-pom).
OK just try copying the extension jar under
```
$M2_HOME/lib
``` | I don't know if the [comment above by Brian Fox](https://stackoverflow.com/questions/602511/maven-how-to-deploy-with-deploy-file-and-custom-wagon#comment650287_619123) is still valid in 2013. But in the end I had to create a minimal pom.xml in the directory where I tried to upload the artifact to enable the wagon build extension.
I had to add groupId, artifactId and version to the pom.xml so that Maven would not complain although I provided them to the deploy-file goal on the commandline (I guess deploy-file would only care about the commandline parameters though):
```
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>your-groupId</groupId>
<artifactId>your-artifactId</artifactId>
<version>your-version</version>
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>2.4</version>
</extension>
</extensions>
</build>
</project>
```
With this simple "pom.xml" in place I could execute the deploy-file finally using scp as the protocol:
```
mvn deploy:deploy-file -Durl=scp://shell.sourceforge.net:/home/project-web/... -DrepositoryId=repoId -Dfile=my-file.jar -DgroupId=your-groupId -DartifactId=your-artifactId -Dversion=your-version -Dpackaging=jar
``` | Maven: How to deploy with deploy-file and custom wagon | [
"",
"java",
"maven-2",
"maven-scm",
""
] |
How can I make a modal `JDialog` without buttons appear for the duration it takes a `Runnable` instance to complete and have that instance update a progress bar/message on that dialog?
Clearly spaghetti code might work, but I'm looking for a clean design if one exists. | You might want to look into [ProgressMonitor](http://docs.oracle.com/javase/6/docs/api/javax/swing/ProgressMonitor.html). It automatically pops up a dialog with a progress bar if the operation is taking a long time; see [How to Use Progress Monitors](http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html). | Look at the project described at the following URL:
<http://digilander.libero.it/carlmila/compmon/main.html>
It is a free Java library alternative to the Swing ProgressMonitor. | Progress Dialog in Swing | [
"",
"java",
"multithreading",
"swing",
""
] |
In C# I want to communicate to the calling method that the parameters passed to an object have caused its instantiation to fail.
```
// okay
Banana banana1 = new Banana("green");
// fail
Banana banana2 = new Banana("red");
```
Throw an exception? If so how? | ```
throw new ArgumentException("Reason", "param name");
``` | A lot (all?) of the answers are saying to throw an exception, but I'm sure I've seen official statements from the framework design team advising against throwing exceptions from constructors.
Note that the classes in the .NET framework that behave similarly to your "Banana" example (where only certain values are appropriate to instantiate the object with) don't use constructors, but instead use static factory methods. For example, [System.Net.WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx) has no public constructor, and instead uses a static [Create](http://msdn.microsoft.com/en-us/library/system.net.webrequest.create.aspx) method which can raise an exception if the supplied string is not a valid URI. *With some exceptions - see my update below.*
So for your code I would change Banana's constructor to protected, and introduce a method like this:
```
public static Banana Create(string color)
{
if (color != "green" && color != "yellow")
{
throw new ArgumentException("Color must be 'green' or 'yellow'",
"color");
}
return new Banana(color);
}
```
**Update**
Ok, it seems like it's not a *bad* idea to throw exceptions from a constructor. In fact, System.IO.FileStream does just that if you pass an invalid filename to its constructor. I guess the idea of using a static factory method is just one way of being more explicit about how you're creating the instance (for example, if the method above were called "FromColor"). | What is the best way to communicate that your constructor has failed in C#? | [
"",
"c#",
"exception",
"constructor",
""
] |
is it possible to clear all textboxes in HTML by calling a javascript function ? | ```
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
``` | ```
var fields = document.getElementsByTagName('input'),
length = fields.length;
while (length--) {
if (fields[length].type === 'text') { fields[length].value = ''; }
}
``` | Clear all HTML fields using javascript | [
"",
"javascript",
"html",
""
] |
I work on a web-application that is written in C#/ASP.NET. The original framers of this application chose to use encrypted query strings and `Viewstate` to control the 'security' and 'state' of the application.
Having come from a GET/POST world before this, I don't have a good basis for understanding why people would go through the trouble of encrypting query strings, when using POST for sensitive data (along with SSL) would achieve a similar level of security.
My question is: What are the advantages and disadvantages of using Encrypted Query Strings in ASP.NET? Is there a documented 'best practice' for this?
---
**Edit**: People tend to focus on `Viewstate` in this question. **Don't**. Viewstate was mentioned only to give you a better idea to ascertain how 'state' was managed, since that is tangentially related to URLs. I never said `Viewstate` was encrypted. There really are two issues: 1) The Use of `Viewstate`, and 2) the Use of encrypted query strings. This question is focused on the latter. I hope that helps to clear up the focus of the question. | A reason why you might do something like this is to prevent tampering with the URL to get access to data other than your own. For example, if you have the url:
```
http://foo.com/user.aspx?user_id=123
```
it wouldn't be hard for me (or anyone) to change that to:
```
http://foo.com/user.aspx?user_id=124
```
If your data access strategy relies entirely on what's in the querystring, that could allow unauthorized access to data.
This approach does serve that purpose correctly, but a more robust way to get there is to actively check authorization within the application, and never rely exclusively on the URL for authentication and / or authorization purposes.
Note that this has nothing to do with SSL - that ensures privacy between the browser and server, but you can be under a perfectly secure connection and still tamper with the URL. | Well, arguably it allows you to distribute a url for the page, but a better approach here might be something involving a guid as an opaque identifier to a permalink... perhaps it is useful for scripting purposes?
If it is between pages on the same app, then a POST over SSL would indeed seem to make more sense. Can you ask the original designers? Read the design documents? | Why Encrypt Query Strings in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
""
] |
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?
example:
```
Select * from Table where RecordID in (RecordIDList)
```
I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable. | You could use `String.Join`. Try something like this:
```
String query = "select * from table where RecordId in ({0});";
String formatted = String.Format(query, String.Join(",", list.ToArray()));
```
As a side note this will not protect you against SQL injection - hopefully this example will point you in the right direction. | I've only done what your trying to do with a comma separated list
```
Select * from Table where RecordID in (1,2,34,45,76,34,457,34)
```
or where the results come from a separate select
```
Select * from Table where RecordID in (select recordId from otherTable where afieldtype=1)
```
I'm pretty sure you can't achieve what you're after.... | SQL Select where values in List<string> | [
"",
".net",
"sql",
"ado.net",
""
] |
I am trying to compile the code from here: <http://www.brackeen.com/javagamebook/#download> (Chapter 6) and am having trouble. I don't understand how `java.util.logging.Logger` and log4j work together, but that seems to be the issue. The errors I get are all on the `log.error()` or `log.warn()` method calls.
Here is the output from NetBeans:
```
init:
deps-clean:
Deleting directory C:\JB\NetBeansProjects\WRServer\build
Deleting directory C:\JB\NetBeansProjects\WRServer\dist
clean:
init:
deps-jar:
Created dir: C:\JB\NetBeansProjects\WRServer\build\classes
Compiling 23 source files to C:\JB\NetBeansProjects\WRServer\build\classes
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:110: cannot find symbol
symbol : method error(java.lang.String,java.lang.Exception)
location: class java.util.logging.Logger
log.error("error initializing ServerSocket", e);
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:152: cannot find symbol
symbol : method warn(java.lang.String)
location: class java.util.logging.Logger
log.warn("error during serverSocket select(): " + ioe.getMessage());
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:155: cannot find symbol
symbol : method error(java.lang.String,java.lang.Exception)
location: class java.util.logging.Logger
log.error("exception in run()", e);
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:187: cannot find symbol
symbol : method error(java.lang.String)
location: class java.util.logging.Logger
log.error("no gamecontroller for gameNameHash: " + gameNameHash);
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:203: cannot find symbol
symbol : method error(java.lang.String)
location: class java.util.logging.Logger
log.error("error getting GameController directory");
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:223: cannot find symbol
symbol : method warn(java.lang.String)
location: class java.util.logging.Logger
log.warn("class file does not extend GameController: " + file);
^
C:\JB\NetBeansProjects\WRServer\src\com\hypefiend\javagamebook\server\GameServer.java:238: cannot find symbol
symbol : method error(java.lang.String,java.lang.Exception)
location: class java.util.logging.Logger
log.error("Error instantiating GameController from file: " + file, e);
^
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
7 errors
BUILD FAILED (total time: 0 seconds)
```
Here is the code straight from the book. I have not tried to edit it yet.
```
package com.hypefiend.javagamebook.server;
import com.hypefiend.javagamebook.common.*;
import com.hypefiend.javagamebook.server.controller.*;
import java.nio.channels.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.util.logging.Logger;
import org.apache.log4j.*;
/**
* GameServer.java
*
* The heart of the framework, GameServer accepts
* incoming client connections and hands them off to
* the SelectAndRead class.
* GameServer also keeps track of the connected players
* and the GameControllers.
*
* @author <a href="mailto:bret@hypefiend.com">bret barker</a>
* @version 1.0
*/
public class GameServer extends Thread {
/** log4j Logger */
private Logger log = Logger.getLogger("GameServer");
/** ServerSocketChannel for accepting client connections */
private ServerSocketChannel sSockChan;
/** selector for multiplexing ServerSocketChannels */
private Selector selector;
/** GameControllers keyed by GameName */
private Hashtable gameControllers;
/** classname prefix used for dynamically loading GameControllers */
private static final String CONTROLLER_CLASS_PREFIX =
"com.hypefiend.javagamebook.server.controller.";
/** players keyed by playerId */
private static Hashtable playersByPlayerId;
/** players keyed by sessionId */
private static Hashtable playersBySessionId;
private boolean running;
private SelectAndRead selectAndRead;
private EventWriter eventWriter;
private static long nextSessionId = 0;
/**
* main.
* setup log4j and fireup the GameServer
*/
public static void main(String args[]) {
BasicConfigurator.configure();
GameServer gs = new GameServer();
gs.start();
}
/**
* constructor, just initialize our hashtables
*/
public GameServer() {
gameControllers = new Hashtable();
playersByPlayerId = new Hashtable();
playersBySessionId = new Hashtable();
}
/**
* init the GameServer, startup our workers, etc.
*/
public void init() {
log.info("GameServer initializing");
loadGameControllers();
initServerSocket();
selectAndRead = new SelectAndRead(this);
selectAndRead.start();
eventWriter = new EventWriter(this, Globals.EVENT_WRITER_WORKERS);
}
/**
* GameServer specific initialization, bind to the server port,
* setup the Selector, etc.
*/
private void initServerSocket() {
try {
// open a non-blocking server socket channel
sSockChan = ServerSocketChannel.open();
sSockChan.configureBlocking(false);
// bind to localhost on designated port
InetAddress addr = InetAddress.getLocalHost();
log.info("binding to address: " + addr.getHostAddress());
sSockChan.socket().bind(new InetSocketAddress(addr, Globals.PORT));
// get a selector
selector = Selector.open();
// register the channel with the selector to handle accepts
SelectionKey acceptKey = sSockChan.register(selector, SelectionKey.OP_ACCEPT);
}
catch (Exception e) {
log.error("error initializing ServerSocket", e);
System.exit(1);
}
}
/**
* Here's the meat, loop over the select() call to
* accept socket connections and hand them off to SelectAndRead
*/
public void run() {
init();
log.info("******** GameServer running ********");
running = true;
int numReady = 0;
while (running) {
// note, since we only have one ServerSocket to listen to,
// we don't need a Selector here, but we set it up for
// later additions such as listening on another port
// for administrative uses.
try {
// blocking select, will return when we get a new connection
selector.select();
// fetch the keys
Set readyKeys = selector.selectedKeys();
// run through the keys and process
Iterator i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
SocketChannel clientChannel = ssChannel.accept();
// add to the list in SelectAndRead for processing
selectAndRead.addNewClient(clientChannel);
log.info("got connection from: " + clientChannel.socket().getInetAddress());
}
}
catch (IOException ioe) {
log.warn("error during serverSocket select(): " + ioe.getMessage());
}
catch (Exception e) {
log.error("exception in run()", e);
}
}
}
/**
* shutdown the GameServer
*/
public void shutdown() {
selector.wakeup();
}
/**
* Return the next available sessionId
*/
public synchronized String nextSessionId() {
return "" + nextSessionId++;
}
/**
* finds the GameController for a given GameName
*/
public GameController getGameController(String gameName) {
return getGameControllerByHash(gameName.hashCode());
}
/**
* finds the GameController for a given GameName hash code
*/
public GameController getGameControllerByHash(int gameNameHash) {
GameController gc = (GameController) gameControllers.get("" + gameNameHash);
if (gc == null)
log.error("no gamecontroller for gameNameHash: " + gameNameHash);
return gc;
}
/**
* Dynamically loads GameControllers
*/
private void loadGameControllers() {
log.info("loading GameControllers");
// grab all class files in the same directory as GameController
String baseClass = "com/hypefiend/javagamebook/server/controller/GameController.class";
File f = new File( this.getClass( ).getClassLoader().getResource(baseClass).getPath());
File[] files = f.getParentFile().listFiles( );
if (files == null) {
log.error("error getting GameController directory");
return;
}
for( int i = 0; ( i < files.length); i++) {
String file = files[i].getName( );
if (file.indexOf( ".class") == -1)
continue;
if (file.equals("GameController.class"))
continue;
try {
// grab the class
String controllerClassName = CONTROLLER_CLASS_PREFIX + file.substring(0, file.indexOf(".class"));
log.info("loading class: " + controllerClassName);
Class cl = Class.forName(controllerClassName);
// make sure it extends GameController
if (!GameController.class.isAssignableFrom(cl)) {
log.warn("class file does not extend GameController: " + file);
continue;
}
// get an instance and initialize
GameController gc = (GameController) cl.newInstance();
String gameName = gc.getGameName();
gc.init(this, getGameConfig(gameName));
// add to our controllers hash
gameControllers.put("" + gameName.hashCode(), gc);
log.info("loaded controller for gameName: " + gameName + ", hash: " + gameName.hashCode());
}
catch (Exception e) {
log.error("Error instantiating GameController from file: " + file, e);
}
}
}
/**
* pass the event on to the EventWriter
*/
public void writeEvent(GameEvent e) {
eventWriter.handleEvent(e);
}
/**
* returns the GameConfig object for the given gameName
*/
public GameConfig getGameConfig(String gameName) {
// todo: implement getGameConfig()
return null;
}
/**
* fetches the Player for a given playerId
*/
public static Player getPlayerById( String id) {
return (Player) playersByPlayerId.get(id);
}
/**
* fetches the Player for a given sessionId
*/
public static Player getPlayerBySessionId(String id) {
return (Player) playersBySessionId.get(id);
}
/**
* add a player to our lists
*/
public static void addPlayer(Player p) {
playersByPlayerId.put(p.getPlayerId(), p);
playersBySessionId.put(p.getSessionId(), p);
}
/**
* remove a player from our lists
*/
public static void removePlayer(Player p) {
playersByPlayerId.remove(p.getPlayerId());
playersBySessionId.remove(p.getPlayerId());
}
}// GameServer
``` | The import of java.util.logging.Logger in your class seems to cause the problem (the compiler tries to compile against that one, altough it seems the intention was to use the log4j Logger class).
Try to remove the java.util.logging.Logger from the imports and recompile.
EDIT:
Well, I just checked the original GameServer.java from the ZIP file linked in the page linked in the question. it does NOT contain any import of java.util.logging.Logger there. My guess is thus:
* You do not have log4j on the classpath of your project
* You or your IDE tried to somehow organize the imports automatically. This ended up adding java.util.logging.Logger to the imports because no other class of that name was found in project's classpath.
So, add log4j to the classpath first, then remove the java.util.logging.Logger from the imports. | [`java.util.logging.Logger`](http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html) does not have a `warn()` method (although it does have a `warning()` method).
However, [`org.apache.log4j.Logger`](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html) does indeed have a method named `warn()`.
Are you sure you are importing the correct classes? | java.util.logging.Logger and log4j | [
"",
"java",
"logging",
"netbeans",
"log4j",
""
] |
I want to get the string name (const char\*) of a template type. Unfortunately I don't have access to RTTI.
```
template< typename T >
struct SomeClass
{
const char* GetClassName() const { return /* magic goes here */; }
}
```
So
```
SomeClass<int> sc;
sc.GetClassName(); // returns "int"
```
Is this possible? I can't find a way and am about to give up. Thanks for the help. | No and it will not work reliable with typeid either. It will give you some internal string that depends on the compiler implementation. Something like "int", but also "i" is common for `int`.
By the way, if what you want is to only compare whether two types are the same, you don't need to convert them to a string first. You can just do
```
template<typename A, typename B>
struct is_same { enum { value = false }; };
template<typename A>
struct is_same<A, A> { enum { value = true }; };
```
And then do
```
if(is_same<T, U>::value) { ... }
```
Boost already has such a template, and the next C++ Standard will have `std::is_same` too.
## Manual registration of types
You can specialize on the types like this:
```
template<typename>
struct to_string {
// optionally, add other information, like the size
// of the string.
static char const* value() { return "unknown"; }
};
#define DEF_TYPE(X) \
template<> struct to_string<X> { \
static char const* value() { return #X; } \
}
DEF_TYPE(int); DEF_TYPE(bool); DEF_TYPE(char); ...
```
So, you can use it like
```
char const *s = to_string<T>::value();
```
Of course, you can also get rid of the primary template definition (and keep only the forward declaration) if you want to get a compile time error if the type is not known. I just included it here for completion.
I used static data-members of char const\* previously, but they cause some intricate problems, like questions where to put declarations of them, and so on. Class specializations like above solve the issue easily.
## Automatic, depending on GCC
Another approach is to rely on compiler internals. In GCC, the following gives me reasonable results:
```
template<typename T>
std::string print_T() {
return __PRETTY_FUNCTION__;
}
```
Returning for `std::string`.
> `std::string print_T() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]`
Some `substr` magic intermixed with `find` will give you the string representation you look for. | **The really easy solution:** Just pass a string object to the constructor of SomeClass that says what the type is.
Example:
```
#define TO_STRING(type) #type
SomeClass<int> s(TO_STRING(int));
```
Simply store it and display it in the implementation of GetClassName.
**Slightly more complicated solution, but still pretty easy:**
```
#define DEC_SOMECLASS(T, name) SomeClass<T> name; name.sType = #T;
template< typename T >
struct SomeClass
{
const char* GetClassName() const { return sType.c_str(); }
std::string sType;
};
int main(int argc, char **argv)
{
DEC_SOMECLASS(int, s);
const char *p = s.GetClassName();
return 0;
}
```
**Template non type solution:**
You could also make your own type ids and have a function to convert to and from the ID and the string representation.
Then you can pass the ID when you declare the type as a template non-type parameter:
```
template< typename T, int TYPEID>
struct SomeClass
{
const char* GetClassName() const { return GetTypeIDString(TYPEID); }
};
...
SomeClass<std::string, STRING_ID> s1;
SomeClass<int, INT_ID> s2;
``` | Is it possible to get a char* name from a template type in C++ | [
"",
"c++",
"string",
"templates",
"typeid",
""
] |
I understand that a stream is a representation of a sequence of bytes. Each stream provides means for reading and writing bytes to its given backing store. But what is the point of the stream? Why isn't the backing store itself what we interact with?
For whatever reason this concept just isn't clicking for me. I've read a bunch of articles, but I think I need an analogy or something. | The word "stream" has been chosen because it represents (in real life) a very similar meaning to what we want to convey when we use it.
Let's forget about the backing store for a little, and start thinking about the analogy to a water stream. You receive a continuous flow of data, just like water continuously flows in a river. You don't necessarily know where the data is coming from, and most often you don't need to; be it from a file, a socket, or any other source, it doesn't (shouldn't) really matter. This is very similar to receiving a stream of water, whereby you don't need to know where it is coming from; be it from a lake, a fountain, or any other source, it doesn't (shouldn't) really matter.
That said, once you start thinking that you only care about getting the data you need, regardless of where it comes from, the abstractions other people talked about become clearer. You start thinking that you can wrap streams, and your methods will still work perfectly. For example, you could do this:
```
int ReadInt(StreamReader reader) { return Int32.Parse(reader.ReadLine()); }
// in another method:
Stream fileStream = new FileStream("My Data.dat");
Stream zipStream = new ZipDecompressorStream(fileStream);
Stream decryptedStream = new DecryptionStream(zipStream);
StreamReader reader = new StreamReader(decryptedStream);
int x = ReadInt(reader);
```
As you see, it becomes very easy to change your input source without changing your processing logic. For example, to read your data from a network socket instead of a file:
```
Stream stream = new NetworkStream(mySocket);
StreamReader reader = new StreamReader(stream);
int x = ReadInt(reader);
```
As easy as it can be. And the beauty continues, as you can use any kind of input source, as long as you can build a stream "wrapper" for it. You could even do this:
```
public class RandomNumbersStreamReader : StreamReader {
private Random random = new Random();
public String ReadLine() { return random.Next().ToString(); }
}
// and to call it:
int x = ReadInt(new RandomNumbersStreamReader());
```
See? As long as your method doesn't care what the input source is, you can customize your source in various ways. The abstraction allows you to decouple input from processing logic in a very elegant way.
Note that the stream we created ourselves does not have a backing store, but it still serves our purposes perfectly.
So, to summarize, a stream is just a source of input, hiding away (abstracting) another source. As long as you don't break the abstraction, your code will be very flexible. | A stream represents a sequence of objects (usually bytes, but not necessarily so), which can be accessed in sequential order. Typical operations on a stream:
* read one byte. Next time you read, you'll get the next byte, and so on.
* read several bytes from the stream into an array
* seek (move your current position in the stream, so that next time you read you get bytes from the new position)
* write one byte
* write several bytes from an array into the stream
* skip bytes from the stream (this is like read, but you ignore the data. Or if you prefer it's like seek but can only go forwards.)
* push back bytes into an input stream (this is like "undo" for read - you shove a few bytes back up the stream, so that next time you read that's what you'll see. It's occasionally useful for parsers, as is:
* peek (look at bytes without reading them, so that they're still there in the stream to be read later)
A particular stream might support reading (in which case it is an "input stream"), writing ("output stream") or both. Not all streams are seekable.
Push back is fairly rare, but you can always add it to a stream by wrapping the real input stream in another input stream that holds an internal buffer. Reads come from the buffer, and if you push back then data is placed in the buffer. If there's nothing in the buffer then the push back stream reads from the real stream. This is a simple example of a "stream adaptor": it sits on the "end" of an input stream, it is an input stream itself, and it does something extra that the original stream didn't.
Stream is a useful abstraction because it can describe files (which are really arrays, hence seek is straightforward) but also terminal input/output (which is not seekable unless buffered), sockets, serial ports, etc. So you can write code which says either "I want some data, and I don't care where it comes from or how it got here", or "I'll produce some data, and it's entirely up to my caller what happens to it". The former takes an input stream parameter, the latter takes an output stream parameter.
Best analogy I can think of is that a stream is a conveyor belt coming towards you or leading away from you (or sometimes both). You take stuff off an input stream, you put stuff on an output stream. Some conveyors you can think of as coming out of a hole in the wall - they aren't seekable, reading or writing is a one-time-only deal. Some conveyors are laid out in front of you, and you can move along choosing whereabouts in the stream you want to read/write - that's seeking.
As IRBMe says, though, it's best to think of a stream in terms of the operations it offers (which vary from implementation to implementation, but have a lot in common) rather than by a physical analogy. Streams are "things you can read or write". When you start connecting up stream adaptors, you can think of them as a box with a conveyor in, and a conveyor out, that you connect to other streams and then the box performs some transformation on the data (zipping it, or changing UNIX linefeeds to DOS ones, or whatever). Pipes are another thorough test of the metaphor: that's where you create a pair of streams such that anything you write into one can be read out of the other. Think wormholes :-) | Can you explain the concept of streams? | [
"",
"java",
".net",
"stream",
"language-agnostic",
"iostream",
""
] |
We are using Rhino Mocks to perform some unit testing and need to mock two interfaces. Only one interface is implemented on the object and the other is implemented dynamically using an aspect-oriented approach. Is there an easy way to combine the two interfaces dynamically so that a mock can be created and the methods stubbed for both interfaces? | A mock with multiple interfaces using Rhino Mocks can be generated like so:
```
var mocker = new MockRepository();
var mock = mocker.CreateMultiMock<IPrimaryInterface>(typeof(IFoo), typeof(IBar));
mocker.ReplayAll();
``` | Using Rhino Mocks
```
var mock = MockRepository.GenerateMock<IFirst, ISecond>();
mock.Stub(m => m.FirstProperty).PropertyBehavior();
((ISecond)mock).Stub(k=> k.SecondProperty).PropertyBehavior();
```
Found and used the information from <http://www.richard-banks.org/2010/08/mocking-comparison-part-11-multiple.html> | How do I combine two interfaces when creating mocks? | [
"",
"c#",
".net",
"rhino-mocks",
""
] |
i have variable `$result` that contains this
```
Country: USA City: NY Latitude: 32.2667 Longitude: 71.9167
```
How do I parse it so I can get the out put like this:
```
Country=USA&City=NY&Latitude=32.2667&Longitude=71.9167
``` | A quick hack
```
str_replace(array(': ', ' '), array('=', '&'), $string);
``` | ```
str_replace(' ', '&', str_replace(': ', '=', $string));
```
It may work as you want. | Parsing in PHP | [
"",
"php",
"parsing",
""
] |
I have a column of numbers stored as chars. When I do a ORDER BY for this column I get the following:
100
131
200
21
30
31000
etc.
How can I order these chars numerically? Do I need to convert something or is there already an SQL command or function for this?
Thank You. | Try this:
```
ORDER BY CAST(thecolumn AS int)
``` | This Worked for me:
```
ORDER BY ABS(column_name)
``` | SQL ORDER chars numerically | [
"",
"sql",
"char",
"type-conversion",
"sql-order-by",
"numerical",
""
] |
I have a dropdown that triggers an ajax call when its changed:
```
$('.travel-to').change(function(){
$.ajax({
type: "GET",
url: "/inc/rates/rates-viewer.php",
data: "shtech=y&c_name="+escape($(this).val()),
success: function(html){
$(".rates-viewer").html(html);
$(".rates-viewer tr.numbers td").css({ opacity: 0 }).fadeTo("slow",1);
}
});
});
```
My problem is, in Firefox, using the up/down cursor keys to cycle through the dropdown options, doesn't trigger the js `onChange()` event. It's ok in IE.
How can I make Firefox see the up/down cursors as an `onChange`? Can I do an either/or on the event, to make either an `onChange` or a keypress trigger the same thing?
Thanks. | You're actually taking advantage of a bug in IE. Firefox supports onChange correctly, as it's not supposed to fire until the browser loses focus of the select field. (I [answered a question](https://stackoverflow.com/questions/580281/redirect-automatically-when-selecting-an-item-from-a-select-drop-down-list/580317#580317) yesterday about this very issue, in fact.) It's actually kind of dangerous to use onChange with a select, especially because there's no way for keyboard only users to skip some options. (On top of that, the mouse wheel *seems* to spin by multiple answers, but it actually fires onChange for each entry it passes by on IE.)
If you really want the event to fire whenever someone presses up or down, I would hook into the onKeyPress or onKeyDown events to fire whenever the "up" or "down" key is pressed. | better option is use `.on()` to bind function as multiple events
```
$("#member").on("change keyup", function(){
-----
});
``` | jQuery change() on <select> and firefox | [
"",
"javascript",
"jquery",
"firefox",
"drop-down-menu",
""
] |
Good design dictates only writing each function once. In PHP I'm doing this by using include files (like Utils.php and Authenticate.php), with the PHP command include\_once. However I haven't been able to find any standards or best practices for PHP include files. What would you at StackOverflow suggest?
I'm looking for:
* Naming Standards
* Code Standards
* Design Patterns
* Suggestions for defining return types of common functions
(now I'm just using associative arrays). | One convention I like to use is to put each class in its own file named ClassName.class.php and then set up the [autoloader](http://ca.php.net/manual/en/language.oop5.autoload.php) to include the class files. Or sometimes I'll put them all in a classes/ subdirectory and just name them ClassName.php. Depends on how many class vs. non-class includes I'm expecting.
If you organize your utility functions into classes and make them static methods instead, you can get away with writing only a single [require\_once()](http://ca.php.net/manual/en/function.require-once.php) in your top level files. This approach may or may not be appropriate for your code or coding style.
As for return types, I try to follow the conventions used in the built-in functions. Return a type appropriate to the request, or return false on failure. Just make sure you use the [=== operator](http://ca.php.net/manual/en/language.operators.comparison.php) when checking for false in the results.
The fact that you're concerned about conventions suggests you're already on the right track. If you are familiar with any other OOP language like Java, C++, C#, etc., then you'll find you can follow a lot of the same conventions thanks to the [OOP goodness in PHP5](http://ca.php.net/manual/en/language.oop5.php). | Whatever naming convention you end up using (I prefer to take cues from either Java or C# wherever possible) make sure if you use include files for functions that they do not actually execute any code upon including, and never include the same file twice. (use [include-once](http://nl2.php.net/include_once) or [require-once](http://nl2.php.net/require_once)) | Design Tips for PHP Function Include Files | [
"",
"php",
"include",
"server-side-includes",
""
] |
I have a list of function calls stored in a database, and for some function calls, I care about what the arguments of the function call are. I am parsing C source code with my program (which is in C#). I'm trying to find the best way of getting the function calls with the arguments. I read the source code into a string prior to parsing it (so that I am not using the stream reader on the file). I tried using some regex (which is somewhat new to me) to parse the source file, but was retrieving more than just the function call when using a regex string like this: functionCall + ".\*\\)"; ( I am escaping the opening ( in the function call)
The function calls are stored in the following format in the DB
```
Function Call
============
some_Call(
```
There is a reason they are stored this way, and will not change.
Is there a good way to do this through regex, or would I be better suited to walk through the source code contents?
Let me know if any clarification is needed. | Part of the reason your solution failed is that you probably should have used `.*?)`, instead of greedy matching.
A complete answer would have to follow at least these:
Ignore parenthesis in strings and chars (which you can do with a regex, although with escaping it can be a little complicated)
```
functionCall("\")", ')')
```
Ignore parentheses in comments (which you can do with a regex)
```
functionCall(/*)*/ 1, // )
2)
```
Don't match too much (which you can do with a regex)
```
functionCall(1) + functionCall(2) + (2 * 3) // Don't match past the first )
```
but it would also have to ignore balanced parentheses
```
functionCall((1+(1))*(2+2))
```
This last one is something you can't do with a normal regex, because it involves counting parenthesis, and is generally something that regexs aren't suited for. However, it appears that [.NET has ways to do this](http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx).
(And technically you would have to handle macros, I can imagine a
```
#define close_paren )
```
would ruin your day...)
That said, you could likely come up with a naive solution (similar to what you had, or what some other poster recommends) and it would work for many cases, especially if you're working with known inputs. | I have written a quick regex and tested it, check the following:
```
string tst = "some_function(type<whatever> tesxt_112,type<whatever> tesxt_113){";
Regex r = new Regex(".*\\((.*)\\)");
Match m = r.Match(tst);
if (m.Success)
{
string[] arguments = m.Groups[1].Value.Split(',');
for (int i = 0; i < arguments.Length; i++)
{
Console.WriteLine("Argument " + (i + 1) + " = " + arguments[i]);
}
}
Console.ReadKey();
```
So the output for the above string would be:
Argument 1 = type<whatever> tesxt\_112
Argument 2 = type<whatever> tesxt\_113
Hope this helps:
Andrew :-) | Using C# and regex to parse source code and find function calls with arguments | [
"",
"c#",
"regex",
"parsing",
""
] |
Is it possible to do this from within a class?
```
$("#" + field).click(this.validate);
```
So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed. | Yes it is possible.
10 mins ago was writting a snipet because i had just that problem
```
$("div.myalarms_delete").click(function(){
var mid = this.id;
$("li#"+mid).fadeOut("fast");
});
```
the div.myalarms\_delete also as the id I needed | I am not sure about an easy way, but you can always go the closure route:
```
var that = this;
$("#" + field).click(function() {
that.validate();
});
``` | Can you do this using jquery? | [
"",
"javascript",
"jquery",
"events",
""
] |
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?
I see mainly two possibilities:
* Use an abstract base class and pass concrete object in
* Use a template
Here is a little example, implemented in the various versions:
**Version 1:** Abstract base class
```
class Brake {
public: virtual void stopCar() = 0;
};
class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};
class Car {
Brake* _brake;
public:
Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
```
**Version 2a:** Template
```
template<class Brake>
class Car {
Brake brake;
public:
Car(){ brake.stopCar(); }
};
```
**Version 2b:** Template and private inheritance
```
template<class Brake>
class Car : private Brake {
using Brake::stopCar;
public:
Car(){ stopCar(); }
};
```
Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?
I realize there is not a big difference between version 2a and 2b, see [C++ FAQ](http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.2).
Can you comment on these possibilities? | This depends on your goals. You can use version 1 if you
* Intend to replace brakes of a car (at runtime)
* Intend to pass Car around to non-template functions
I would generally prefer version 1 using the runtime polymorphism, because it is still flexible and allows you to have the Car still have the same type: `Car<Opel>` is another type than `Car<Nissan>`. If your goals are great performance while using the brakes frequently, i recommend you to use the templated approach. By the way, this is called policy based design. You provide a *brake policy*. Example because you said you programmed in Java, possibly you are not yet too experienced with C++. One way of doing it:
```
template<typename Accelerator, typename Brakes>
class Car {
Accelerator accelerator;
Brakes brakes;
public:
void brake() {
brakes.brake();
}
}
```
If you have lots of policies you can group them together into their own struct, and pass that one, for example as a `SpeedConfiguration` collecting `Accelerator`, `Brakes` and some more. In my projects i try to keep a good deal of code template-free, allowing them to be compiled once into their own object files, without needing their code in headers, but still allowing polymorphism (via virtual functions). For example, you might want to keep common data and functions that non-template code will probably call on many occasions in a base-class:
```
class VehicleBase {
protected:
std::string model;
std::string manufacturer;
// ...
public:
~VehicleBase() { }
virtual bool checkHealth() = 0;
};
template<typename Accelerator, typename Breaks>
class Car : public VehicleBase {
Accelerator accelerator;
Breaks breaks;
// ...
virtual bool checkHealth() { ... }
};
```
Incidentally, that is also the approach that C++ streams use: `std::ios_base` contains flags and stuff that do not depend on the char type or traits like openmode, format flags and stuff, while `std::basic_ios` then is a class template that inherits it. This also reduces code bloat by sharing the code that is common to all instantiations of a class template.
### Private Inheritance?
Private inheritance should be avoided in general. It is only very rarely useful and containment is a better idea in most cases. Common case where the opposite is true when size is really crucial (policy based string class, for example): Empty Base Class Optimization can apply when deriving from an empty policy class (just containing functions).
Read [Uses and abuses of Inheritance](http://www.gotw.ca/publications/mill06.htm) by Herb Sutter. | The rule of thumb is:
1) If the choice of the concrete type is made at compile time, prefer a template. It will be safer (compile time errors vs run time errors) and probably better optimized.
2) If the choice is made at run-time (i.e. as a result of a user's action) there is really no choice - use inheritance and virtual functions. | Template or abstract base class? | [
"",
"c++",
"design-patterns",
"templates",
"abstract-class",
"virtual-functions",
""
] |
I'm looking to do some physics simulations and I need fast rendering in Java.
I've run into performance issues with Java2d in the past, so what are the fast alternatives? Is JOGL significantly faster than Java2d? | My experience with Java2D is that it can be very fast, if you follow the rules. I had an application that went from 90% CPU to less than 5% CPU just by changing a few simple things. Using large transparent PNG's is a no no, for example.
A very good resource is the Java-Gaming.org forums: a lot of people, including the Sun 2D specialists, hang out there and provide many examples and solutions to performance issues for 2D drawing.
See: <http://www.javagaming.org/> and then the topic "Performance Tuning". | JOGL might be much faster than Java2D even if you use it for doing 2D graphics only: as Clayworth mentioned, it usually depends on what you need to do.
My guess is that for 2D physical simulations, where you have (textured or non-textured) objects rotating and translating with 2 degrees of freedom, JOGL should provide the best performance and also easily allow you to provide a zoomable interface. Here is a [tutorial](http://basic4gl.wikispaces.com/2D+Drawing+in+OpenGL) for OpenGL for 2D graphics (C, but easily adapted to JOGL).
JOGL will take a bit more time to learn than Java2D, but achieving good performance will most probably not require specialized optimizations as in Java2D. | What are some faster alternatives to Java2d? | [
"",
"java",
"performance",
"rendering",
"jogl",
"java-2d",
""
] |
Under the covers, Google Gears uses SQL Lite as its data store. Has anyone successfully connected to the Google Gears SQL Lite DB with C#?
Thanks | have a look at my favorite [SQLite ADO.NET Wrapper](http://sqlite.phxsoftware.com/), which I personally use in a lot of projects. I suppose, that Google Gears is using a default SQLite database with a little bit of modifications in the code to prevent ATTACH and #PRAGMA uses. But the dataformat should be identical and so you should be able to access it using this wrapper.
Best regards,
Martin | //Hi , Try this one :
```
//Courtesy of http://www.codoxide.com/post/My-Favorite-Database-Wrapper-for-C.aspx
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
namespace GenApp.Core.Providers.nsDb
{
//comm -- / <summary>
//comm -- / Abstract base class for encapsulating provider independant database interactin logic.
//comm -- / </summary>
//comm -- / <typeparam name="CONNECTION_TYPE"><see cref="DbConnection"/> derived Connection type.</typeparam>
//comm -- / <typeparam name="COMMAND_TYPE"><see cref="DbCommand"/> derived Command type.</typeparam>
//comm -- / <typeparam name="ADAPTER_TYPE"><see cref="DbDataAdapater"/> derived Data Adapter type.</typeparam>
public abstract
class AbstractDatabase<CONNECTION_TYPE, COMMAND_TYPE, ADAPTER_TYPE> : IDisposable
where CONNECTION_TYPE : DbConnection, new()
where COMMAND_TYPE : DbCommand
where ADAPTER_TYPE : DbDataAdapter, new()
{
#region : Connection :
//comm -- / <summary>Gets the Connection object associated with the current instance.</summary>
public DbConnection Connection
{
get
{
if (internal_currentConnection == null)
{
internal_currentConnection = new CONNECTION_TYPE();
// - Enable to measure the connection timeGenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf ( ref userObj , "GetConnectionString START" );
internal_currentConnection.ConnectionString = GetConnectionString();
// - Enable to measure the connection timeGenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf ( ref userObj , "GetConnectionString END" );
}
return internal_currentConnection;
}
}
private DbConnection internal_currentConnection;
//comm -- / <summary>When overridden in derived classes returns the connection string for the database.</summary>
//comm -- / <returns>The connection string for the database.</returns>
protected abstract string GetConnectionString();
#endregion
#region : Commands :
//comm -- / <summary>Gets a DbCommand object with the specified <see cref="DbCommand.CommandText"/>.</summary>
//comm -- / <param name="sqlString">The SQL string.</param>
//comm -- / <returns>A DbCommand object with the specified <see cref="DbCommand.CommandText"/>.</returns>
public DbCommand GetSqlStringCommand(string sqlString)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
DbCommand cmd = this.Connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlString;
return cmd;
}
//comm -- / <summary>Gets a DbCommand object with the specified <see cref="DbCommand.CommandText"/>.</summary>
//comm -- / <param name="sqlStringFormat">The SQL string format.</param>
//comm -- / <param name="args">The format arguments.</param>
//comm -- / <returns>A DbCommand object with the specified <see cref="DbCommand.CommandText"/>.</returns>
public DbCommand GetSqlStringCommand(string sqlStringFormat, params object[] args)
{
return GetSqlStringCommand(string.Format(sqlStringFormat, args));
}
//comm -- / <summary>Gets a DbCommand object for the specified Stored Procedure.</summary>
//comm -- / <param name="storedProcName">The name of the stored procedure.</param>
//comm -- / <returns>A DbCommand object for the specified Stored Procedure.</returns>
public DbCommand GetStoredProcedureCommand(string storedProcName)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
DbCommand cmd = this.Connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
return cmd;
}
#region : Parameters :
//comm -- / <summary>Adds an input parameter to the given <see cref="DbCommand"/>.</summary>
//comm -- / <param name="cmd">The command object the parameter should be added to.</param>
//comm -- / <param name="paramName">The identifier of the parameter.</param>
//comm -- / <param name="paramType">The type of the parameter.</param>
//comm -- / <param name="value">The value of the parameter.</param>
//comm -- / <returns>The <see cref="DbParameter"/> that was created.</returns>
public DbParameter AddInParam(DbCommand cmd, string paramName, DbType paramType, object value)
{
DbParameter param = cmd.CreateParameter();
param.DbType = paramType;
param.ParameterName = paramName;
param.Value = value;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add( param );
return param;
} //eof method AddInParam
//comm -- / <summary>Adds an input parameter to the given <see cref="DbCommand"/>.</summary>
//comm -- / <param name="cmd">The command object the parameter should be added to.</param>
//comm -- / <param name="paramName">The identifier of the parameter.</param>
//comm -- / <param name="paramType">The type of the parameter.</param>
//comm -- / <param name="size">The maximum size in bytes, of the data table column to be affected.</param>
//comm -- / <param name="value">The value of the parameter.</param>
//comm -- / <returns>The <see cref="DbParameter"/> that was created.</returns>
public DbParameter AddInParam(DbCommand cmd, string paramName, DbType paramType, int size, object value)
{
DbParameter param = cmd.CreateParameter();
param.DbType = paramType;
param.ParameterName = paramName;
param.Size = size;
param.Value = value;
param.Direction = ParameterDirection.Input;
//debugGenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf ( ref userObj , "Adding IN param " + value.ToString ( ) );
cmd.Parameters.Add(param);
return param;
}
public DbParameter AddInOutParam ( DbCommand cmd, string paramName, DbType paramType, int size, object value )
{
DbParameter param = cmd.CreateParameter ( );
param.DbType = paramType;
param.ParameterName = paramName;
param.Size = size;
param.Value = value;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add ( param );
//debug if needed here
return param;
}
public DbParameter AddInOutParam ( DbCommand cmd, string paramName, DbType paramType, object value )
{
DbParameter param = cmd.CreateParameter ( );
param.DbType = paramType;
param.ParameterName = paramName;
param.Value = value;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add ( param );
return param;
}
#endregion
#region : Executes :
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public int ExecuteNonQuery(DbCommand cmd)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
return cmd.ExecuteNonQuery();
}
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <param name="txn">The database transaction inside which the command should be executed.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public int ExecuteNonQuery(DbCommand cmd, DbTransaction txn)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
cmd.Transaction = txn;
return cmd.ExecuteNonQuery();
}
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public DbDataReader ExecuteReader(DbCommand cmd)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
return cmd.ExecuteReader();
}
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <param name="behavior">One of the <see cref="System.Data.CommandBehavior"/> values.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public DbDataReader ExecuteReader(DbCommand cmd , CommandBehavior behavior )
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
return cmd.ExecuteReader(behavior);
}
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public T ExecuteScalar<T>(DbCommand cmd, T defaultValue)
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
object retVal = cmd.ExecuteScalar();
if (null == retVal || DBNull.Value == retVal)
return defaultValue;
else
return (T)retVal;
}
//comm -- / <summary>Executes the specified command against the current connection.</summary>
//comm -- / <param name="cmd">The command to be executed.</param>
//comm -- / <returns>Result returned by the database engine.</returns>
public DataSet ExecuteDataSet(DbCommand cmd)
{
ADAPTER_TYPE adapter = new ADAPTER_TYPE();
adapter.SelectCommand = (COMMAND_TYPE)cmd;
DataSet retVal = new DataSet();
adapter.Fill(retVal);
return retVal;
}
////comm -- / <summary>Executes the specified command against the current connection.</summary>
////comm -- / <param name="cmd">The command to be executed.</param>
////comm -- / <returns>Result returned by the database engine.</returns>
//public DataSet ExecuteDataSet(DbCommand cmd )
//{
// ADAPTER_TYPE adapter = new ADAPTER_TYPE();
// adapter.SelectCommand = (COMMAND_TYPE)cmd;
// //cmd.CommandTimeout = 3600
// DataSet retVal = new DataSet();
// adapter.Fill(retVal);
// return retVal;
//}
#endregion
#endregion
//comm -- / <summary>Begins a transaction.</summary>
//comm -- / <returns>Created transaction.</returns>
public DbTransaction BeginTransaction()
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
return Connection.BeginTransaction();
}
#region : Construction / Destruction :
//comm -- / <summary>Disposes the resources associated with the current database connection.</summary>
~AbstractDatabase()
{
Dispose();
}
#region IDisposable Members
//comm -- / <summary>Disposes the resources associated with the current database connection.</summary>
public void Dispose()
{
if (null != internal_currentConnection)
{
internal_currentConnection.Dispose();
internal_currentConnection = null;
}
}
#endregion
#endregion
} //eof public abstract class AbstractDatabase
} //eof namespace Providers.nsDb
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace GenApp.Core.Providers.nsDb
{
public class Database : AbstractDatabase<SqlConnection, SqlCommand, SqlDataAdapter>
{
private string _ConnectionString;
public string ConnectionString
{
get { return _ConnectionString; }
set { _ConnectionString = value; }
} //eof property FieldName
public Database ( string connectionStr )
{
//debugGenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf(ref userObj , " CHECK --- nsDb.Database using the following connection string " + connectionStr);
this.ConnectionString = connectionStr;
} //eof constructor
protected override string GetConnectionString ( )
{
//GenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf ( ref userObj , "In GetConnectionString the ConnectionString is " + this.ConnectionString );
//GenApp.Core.Providers.nsDbMeta.DbDebugger.WriteIf ( ref userObj , "The comming fromURL IS " + commingFromURL );
return this._ConnectionString;
} //eof protected override string GetConnectionString()
} //eof class
} //eof namespace Providers.nsDb
``` | Google Gears SQL Lite DB and C# | [
"",
"c#",
"google-gears",
""
] |
Just would like some thoughts of what you think about my strategy to learn C++. While I understand that it takes years to master a programming language, I simply want to get to the point where I can be considered competent as quickly as possible. Why quickly? Well when I say *quickly* I'm really saying I'm committed, and that I don't want it to take forever where forever is never. If it takes five years to become competent, it takes five years. I'm not expecting 24 hours or 30 days.
About me: I don't have a CS degree, I have an anthropology degree and a Masters in library science. Learning the CS fundamentals such as Big O notation, and basics such as binary trees and linked lists, sort algorithms has been a challenge. Probably nothing substitutes a good CS degree. :( I do have many years programming experience, starting with PHP in 2001, ActionScript, 2003, JavaScript soon after. I have been writing programs in Python for about two years now and I have learned C (by reading the K&R book and writing some programs), but I'm probably not going to get hired for a C job. Also recently learned Objective C. I work as a JavaScript & Python, & CSS developer at a website at the moment.
Anyhow, this is my strategy: Read the Stroustrup book (I just started on Part I) and at the same time start a simple C++ project, while also doing many of the Stroustrup exercises.
Thoughts? | Bjarne's book is fantastic, especially for C++ syntax, but the one book that will really make you a competent C++ programmer is Meyers' [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876). Get it. Read it.
I as well do not have a CS degree, but I work for a silicon valley startup. It is possible, you just have to be aware of what's out there and never stop learning. Many students who graduate with a computer science degree end up working in a language they didn't study, so be sure to hit the fundamentals. If you hear something that's unfamiliar to you, be sure to find a good book and a coffee shop and get to it. The C++ will come in time - with Stroustrup and Meyers, you've got 90% of what it takes to be good at C++ | My usual advice is to keep C and C++ separate. Don't assume that C advice or best practices apply to C++, and vice versa. Keeping that in mind will probably help you avoid a lot of bad habits. | What is the best way to learn C++ if I have a bit of other programming experience? | [
"",
"c++",
""
] |
PHPWiki has a 5 second slow query each time you save a page edit. The query caught often in the "mysql-slow.log" is:
```
INSERT INTO wikiscore
SELECT w1.topage, COUNT(*)
FROM wikilinks AS w1, wikilinks AS w2
WHERE w2.topage=w1.frompage
GROUP BY w1.topage;
```
The current indexes are as follows:
```
table "wikilinks" has a primary index on "frompage" and "topage"
table "wikiscore" has a primary index on "pagename" and "score"
```
How could I reformulate the SELECT query to return the same results faster? How could I change the indexes so this query would be faster? My thought is it might be OVER-indexed?
I've timed the result of the SELECT part of the query only and it takes 1-2 seconds alone. The INSERT must take up the rest of that time.
There is a lag when saving pages that I would like to eliminate. I do not have the option of upgrading to another wiki engine (or version of PHPwiki) due to the amount of modifications that have been done.
Any ideas?
edit---
The results of "EXPLAIN" on the SELECT part of the query were:
```
SIMPLE
w2
index
PRIMARY
204
31871
Using index; Using temporary; Using filesort
SIMPLE
w1
ref
PRIMARY
PRIMARY
102
phpwiki.w2.topage
14
Using index
``` | > table "wikilinks" has a primary index on "frompage" and "topage"
```
WHERE w2.topage=w1.frompage
```
This condition cannot be searched over the composite index described above.
Either change order (create an index on `topage, frompage`) or create an additional index on `topage`.
P. S. The root of them problem is that the ranks of each and every page in the system are updated with every edit.
This ranking system seems a little bit weird to me: it counts link to links, not the links themselves.
If 1000 pages link to **Moscow** and only **Moscow** links to **Beket pond**, then the pond will get 1000 points and **Moscow** will get no points at all, though everyone knows of Moscow and none of the pond.
I think it's not what you meant. Most probably it should look like that:
```
INSERT INTO
wikiscore
SELECT
linked.topage, COUNT(*) AS cnt
FROM wikilinks current, wikilinks linked
WHERE current.frompage=@current_page
AND linked.topage = current.topage
GROUP BY
linked.topage
ON DUPLICATE KEY UPDATE
score = cnt;
```
This will sum all links to all pages referenced from the current page, that seems to be what you want.
You will need to get rid of `score` in `PRIMARY KEY` on `wikiscore` in this case, but I see no point in putting it there anyway.
If you want to speed up ranking queries, you create indices like that:
```
ALTER TABLE wikilinks ADD CONSTRAINT pk_wikilinkes_fromto PRIMARY KEY (frompage, topage);
CREATE INDEX ix_wikilinks_topage ON wikilinks (topage);
ALTER TABLE wikiscore ADD CONSTRAINT pk_wikiscore_pagename PRIMARY KEY (pagename);
CREATE INDEX ix_wikiscore_score ON wikiscore (score);
``` | It should be helpful to use the [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/de/explain.html) statement to figure out what part of your query takes the most time. Then you can decide what measures are to be taken to optimize your query. | Slow MySQL query. What should I index? | [
"",
"sql",
"mysql",
"indexing",
""
] |
I am looking for a tool to document legacy source code for an embedded C project I work with. I had it in my mind that there was a tool that would create charts of the various C and .h files, but I can't recall what it is called. Does anyone know of such a tool? | There's a big list at [this url](http://grok2.tripod.com/code_comprehension.html) too. | [CppDepend](http://www.cppdepend.com) The NDepend like for C\C++ | Code Dependency documentation software | [
"",
"c++",
"c",
""
] |
I am using a `Collection` (a `HashMap` used indirectly by the JPA, it so happens), but apparently randomly the code throws a `ConcurrentModificationException`. What is causing it and how do I fix this problem? By using some synchronization, perhaps?
Here is the full stack-trace:
```
Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$ValueIterator.next(Unknown Source)
at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
``` | This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.
```
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Entry item = it.next();
map.remove(item.getKey());
}
```
This will throw a `ConcurrentModificationException` when the `it.hasNext()` is called the second time.
The correct approach would be
```
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Entry item = it.next();
it.remove();
}
```
Assuming this iterator supports the `remove()` operation. | Try using a `ConcurrentHashMap` instead of a plain `HashMap` | Why is a ConcurrentModificationException thrown and how to debug it | [
"",
"java",
"exception",
"collections",
"concurrentmodification",
""
] |
I've gotten fed up with MSVC++6 and how everyone is always telling me that it's a crappy compiler and such.
So now I've decided to try to use vim plus g++ and makefiles. Here's my problem; I have the following makefile:
```
# This is supposed to be a comment..
CC = g++
# The line above sets the compiler in use..
# The next line sets the compilation flags
CFLAGS=-c -Wall
all: main.exe
main.exe: main.o Accel.o
$(CC) -o main.exe main.o Accel.o
main.o: main.cpp Accel.h
$(CC) $(CFLAGS) main.cpp
Accel.o: Accel.cpp Accel.h
$(CC) $(CFLAGS) Accel.cpp
clean:
del main.exe *.o
```
This gives an error when trying to `make`, because I need to link to a windows library called `Ws2_32.lib`, which is needed by `Winsock2.h`, which I `include` in one of my `.h` files.
So how do I do this? I've tried the `-l` option, but I can't make it work. How does it work with a path that has spaces? | First step: locate the library you are looking for. For me, it's in :
```
C:\Program Files\Microsoft Visual Studio\VC98\Lib
```
Second step, pass that directory with -L :
```
LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib"
```
Third step, pass the name of the library with -l (lowercase L):
```
LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib" -lWs2_32
```
Then use it:
```
main.exe: main.o Accel.o
$(CC) $(LINKFLAGS) -o main.exe main.o Accel.o
``` | This is not an answer to your question but I suggest to use [cmake](http://www.cmake.org) . It's a multi-platform multi-build environement project file generator. The syntax of CMake files is quite simple (certainly simpler than Makefile) and it will generate Makefile or Visual Studio projects on request.
Problem with hand-coded Makefile is that very soon, your dependency tree grows so big that maintaining all the rules of what needs to build what becomes a very tedious operation. Hence, there are tons of Makefile generators (autotools, CMake) or Makefile alternatives (Scons, waf, bjam, ....) | Makefiles on windows with g++, linking a library | [
"",
"c++",
"windows",
"makefile",
"g++",
""
] |
We have a const array of structs, something like this:
static const SettingsSuT \_table[] = { {5,1}, {1,2}, {1,1}, etc };
the structure has the following:
* size\_bytes:
* num\_items:
* Other "meta data" members
So the "total size" is size\_bytes\*num\_items for a single element. All of this information is in the const array, available at compile time. But, please note, the total size of \_table is not related to the size of the EEPROM itself. \_table does not mirror the EEPROM, it only describes the layout, usage, and other "meta data" type information we need. But, you can use this meta data to determine the amount of EEPROM we are using.
The array simply describes the data that is stored in an external EEPROM, which has a fixed/maximum size. As features are added and removed, the entries in the const array changes. We currently have a runtime check of the total size of the data to insure that it does not exceed the EEPROM size.
However, we have been changing over many of these runtime checks to static\_assert style template checks, so that the build stops immediately. I'm not a template expert, so could use some help on this one.
So, the question: how to create a template to add up the size of all the elements (multiplying the values of each element, and then adding all the results) and then do a static\_assert and stop the build if they exceed the magic number size of the EEPROM. I was looking at the typical recursive factorial template example as one approach, but it can not access the array, it requires a const value ( I think ).
thank you very much for any help, | Your problem is that they are constant, but they are not constant expressions when evaluated:
```
// f is constant, but its value not known at compile-time
int const f = rand() % 4;
```
What you need are true constant expressions. You can use `boost::mpl` to make up a mpl vector of mpl pairs, each with a pair of integral constants:
```
using namespace boost::mpl;
typedef vector<
pair< int_<5>, int_<1> >,
pair< int_<1>, int_<2> >,
pair< int_<1>, int_<1> >,
> numbers;
```
Now, you can iterate over the items of it using `boost::mpl` algorithms. Each `int_` is exposes a static int constant `value` set to the value you told it. That will evaluate to a constant expression:
```
// get at the first element of the pair, located in the first element
// of the vector. Then get its ::value member.
int array[at<numbers, 0>::type::first::value];
```
And that would actually make that array contain 5 elements.
Website of boost::mpl Reference Manual: [Here](http://www.boost.org/doc/libs/1_37_0/libs/mpl/doc/refmanual.html) | If you change the values to be template parameters rather than constructor arguments or some other runtime initialized value, then they are constants that can be used for your static\_asserts.
I'm not sure how this could work for an array of the structs though. You may need to declare your structs using some macro preprocessor magic so that it keeps track of your allocations for you.
```
BEGIN_EEPROM_STRUCT_TABLE()
STRUCT(size, num_bytes)
// etc.
END_EEPROM_STRUCT_TABLE()
```
This could possibly declare your table and a const that adds up all the sizes, provided they are constant at compile time (and that you write the macros appropriately, of course). | Wanted: a C++ template idea to catch an issue, but at compile time? | [
"",
"c++",
"templates",
"static-assert",
""
] |
I'm having the weirdest problem.
I have two PlaceHolders in a Master Page; one contains controls for users who are logged-out, and the other for users who are logged-in.
They are:
`plhLoggedOut`
`plhLoggedIn`
During my Page\_Load (of the Master Page), I set their visibility like so:
```
//LOGGED-IN?
plhLoggedOut.Visible = (app.UserID == 0);
plhLoggedIn.Visible = (app.UserID != 0);
```
However, the contents of BOTH PlaceHolders are still being rendered.
I'm even writing their visibility to a status message, and that status message confirms that only one is visible at any given time. e.g.,
```
plhLoggedOut.Visible == True; plhLoggedIn.Visible == False
```
Any ideas how this could happen (and how to fix it)?
Thanks very much,
Michael | I just removed the old PlaceHolders and created two new ones with different IDs. Then it started working.
I vaguely remember having weird behaviors like that before, where for some reason the code-behind and the markup are disconnected. That might happen because I don't use the visual designer, and write the .NET tags and the designer.cs file by hand.
FYI, slolife, I just tested it and visibility doesn't get passed down like that from parent controls to child controls. You can nest a hidden control that remains hidden even if you set its container's visibility to true.
Thanks, everyone,
Michael | Maybe somewhere else in your code you are setting a parent control of those panels to visible, which rips through all children and sets them to visible as well. You need to change your code so that plhLoggedOut and plhLoggedIn visibility is set after their parent controls. | Invisible controls still being rendered | [
"",
"c#",
".net",
"asp.net",
""
] |
Where would I start with firing an event over a network? In my case, when I change a database record, I want to inform any other user on the network running the same application that it has changed.
Edit:
It's nothing clever, don't get excited. I'm writing a document management system and when a document is changed in any way (deleted, checked out, up issued, etc), I want to "tell" everyone something's changed. I was going to use a FileSystemWatcher to watch a folder on the server, sign each instance up to it's Deleted event and just create and delete a file in the watched directory, but that's just dirty isn't it? As you can tell, I'm not a professional programmer :) | What kind of notification timeframe are you after? I would personally have the client machines poll the server for updates - e.g. "My most recent update was on 17/02/2009 11:56:00 - what's changed since then?" - by implementing a webservice or simple socket-based server on the actual server.
Otherwise, if it is a distributed app, your "simplest" bet would be a UDP broadcast - assuming they are on the same subnet and not separated by 20 degrees of routers.
Can you tell us a bit more about your situation? | Each instance of your client application could be listening to a socket of messages.
When your server application changes the database record (on behalf of a client, or for any other reason), it also inserts a "something changed" message in the queue of messages for each client.
The server application could either immediately send the message to the client application - or the client application could poll. | Firing an event over a network | [
"",
"c#",
"networking",
""
] |
I've been a Java programmer for over 10 years since starting off with Smalltalk. It's my opinion that *next big languages* are likely to be ones which run on the ubiquitous Java Virtual Machine. I'd like to take advantages of some of the features that Scala (among other languages) has - `case` statements for class hierarchies, closures, type inference as it will allow me to write more concise and clear (I hope) code. A bit closer to Smalltalk!
All the things that are second-nature in Java:
* Building with `ant`
* deploying applications/libraries into logical `jar`s
* Great IDE tool support
* Writing GUIs (or having a Swing GUI talk to it via some kind of remoting?)
* 3rd party libraries/frameworks
* Configuration (properties, `XML`, `Spring` etc)
* DB drivers etc
I'm concerned that the difference between playing around with some pet project and actually making the leap to using it in anger in the workplace is a bit too much.
1. Has anyone made this leap?
2. Was it worth it?
3. What lessons did you learn?
(Obviously people are *using* Scala - but is anyone building actual, for the want of a better word, **Enterprise** applications?) | I have used Scala on our existing Java infrastructure to query and manipulate large xml documents. Was not possible using the standard Java xml libraries or not as easily.
I was tempted to use it for portfolio performance calculations, but had already finished the Java version. A Scala version would have been easier to maintain as it is easier to translate the formulas directly into code.
Another area where you can sneak in Scala is with multithreading. Have no real experience with this, but it seems to be easier in Scala.
Point is, don't try to see it as a Java replacement for now, but use it where you can utilize it strenghts next to your existing Java code.
I used Intellij with the Scala plugin as an IDE, but it is not there yet. It is do-able in combination with the maven plugin and the console.
I'm also a Smalltalk programmer and love being able to use code blocks in Scala. Compared to Java there is less code, but still not as readible as Smalltalk code.
*BTW, the smalltalk community is growing again thanks to the Seaside framework, so you might want to return*
The things I learned or got a better understanding of:
* the use of constructors
* the immutable concept
* working with lists and recursion
* functional programming in general
So yes, I think it is worth it. | Jonas Bonér for one: <http://jonasboner.com/2009/01/30/slides-pragmatic-real-world-scala.html> | Is anyone using Scala in anger (and what advice for a Java programmer)? | [
"",
"java",
"scala",
"jvm-languages",
""
] |
I've got a very small set of classes built up in a custom package hierarchy with one console app class that employs them. Everything works fine from JCreator and from a command prompt.
I'd like to build a second console app that re-uses that same package.
As a Java newbie, what is the quickest, dirtiest method to do that?
My main concern was avoiding copying the package directories over to the new console app's directory.
Using JCreator, I didn't have any problems adding the package directory to the project and compiling and running. But when I tried to run the console app from the command line, it couldn't find the classes in the package hierarchy.
In Visual Studio, you just add a reference... | What you want to do for both apps is create a jar file with a Main-class definition in the var manifest. There's a good bit of information on this in the [Java Tutorials](http://java.sun.com/docs/books/tutorial/deployment/jar/), but the gist of it is just that you'll create a jar file with the jar tool, and then make a little wrapper to run it as
```
java -jar myfile.jar
``` | If you do not wish to copy your class files from your first application, then you need to set up the classpath used when you run java from the command line to include the location of those files.
Make sure you also include the location of your newly created class files. | Quickest method to package a Java console app | [
"",
"java",
"console",
"classpath",
"package",
""
] |
I have a bunch of ZIP files that are in desperate need of some hierarchical reorganization and extraction. What I can do, currently, is create the directory structure and move the zip files to the proper location. The mystic cheese that I am missing is the part that extracts the files from the ZIP archive.
I have seen the MSDN articles on the `ZipArchive` class and understand them reasonable well. I have also seen the [VBScript ways to extract](https://stackoverflow.com/questions/291406/extract-files-from-zip-file-with-vbscript). This is not a complex class so extracting stuff should be pretty simple. In fact, it works "mostly". I have included my current code below for reference.
```
using (ZipPackage package = (ZipPackage)Package.Open(@"..\..\test.zip", FileMode.Open, FileAccess.Read))
{
PackagePartCollection packageParts = package.GetParts();
foreach (PackageRelationship relation in packageParts)
{
//Do Stuff but never gets here since packageParts is empty.
}
}
```
The problem seems to be somewhere in the `GetParts` (or Get*Anything* for that matter). It seems that the package, while open, is empty. Digging deeper the debugger shows that the private member \_zipArchive shows that it actually has parts. Parts with the right names and everything. Why won't the `GetParts` function retrieve them? I'ver tried casting the open to a ZipArchive and that didn't help. Grrr. | If you are manipulating ZIP files, you may want to look into a 3rd-party library to help you.
For example, DotNetZip, which has been recently updated. The current version is now v1.8. Here's an example to create a zip:
```
using (ZipFile zip = new ZipFile())
{
zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
zip.AddFile("c:\\Desktop\\2005_Annual_Report.pdf");
zip.AddFile("ReadMe.txt");
zip.Save("Archive.zip");
}
```
Here's an example to *update* an existing zip; you don't need to extract the files to do it:
```
using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
{
// 1. remove an entry, given the name
zip.RemoveEntry("README.txt");
// 2. Update an existing entry, with content from the filesystem
zip.UpdateItem("Portfolio.doc");
// 3. modify the filename of an existing entry
// (rename it and move it to a sub directory)
ZipEntry e = zip["Table1.jpg"];
e.FileName = "images/Figure1.jpg";
// 4. insert or modify the comment on the zip archive
zip.Comment = "This zip archive was updated " + System.DateTime.ToString("G");
// 5. finally, save the modified archive
zip.Save();
}
```
here's an example that extracts entries:
```
using (ZipFile zip = ZipFile.Read("ExistingZipFile.zip"))
{
foreach (ZipEntry e in zip)
{
e.Extract(TargetDirectory, true); // true => overwrite existing files
}
}
```
DotNetZip supports multi-byte chars in filenames, Zip encryption, AES encryption, streams, Unicode, self-extracting archives.
Also does ZIP64, for file lengths greater than 0xFFFFFFFF, or for archives with more than 65535 entries.
free. open source
get it at
[codeplex](https://archive.codeplex.com/?p=dotnetzip) or [direct download from windows.net](https://codeplexarchive.blob.core.windows.net/archive/projects/DotNetZip/DotNetZip.zip) - CodePlex has been discontinued and archived | From [MSDN](http://blogs.msdn.com/msdnmagazine/archive/2007/05/16/2675596.aspx),
In this sample, the Package class is used (as opposed to the ZipPackage.) Having worked with both, I've only seen flakiness happen when there's corruption in the zip file. Not necessarily corruption that throws the Windows extractor or Winzip, but something that the Packaging components have trouble handling.
Hope this helps, maybe it can provide you an alternative to debugging the issue.
```
using System;
using System.IO;
using System.IO.Packaging;
using System.Text;
class ExtractPackagedImages
{
static void Main(string[] paths)
{
foreach (string path in paths)
{
using (Package package = Package.Open(
path, FileMode.Open, FileAccess.Read))
{
DirectoryInfo dir = Directory.CreateDirectory(path + " Images");
foreach (PackagePart part in package.GetParts())
{
if (part.ContentType.ToLowerInvariant().StartsWith("image/"))
{
string target = Path.Combine(
dir.FullName, CreateFilenameFromUri(part.Uri));
using (Stream source = part.GetStream(
FileMode.Open, FileAccess.Read))
using (Stream destination = File.OpenWrite(target))
{
byte[] buffer = new byte[0x1000];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, read);
}
}
Console.WriteLine("Extracted {0}", target);
}
}
}
}
Console.WriteLine("Done");
}
private static string CreateFilenameFromUri(Uri uri)
{
char [] invalidChars = Path.GetInvalidFileNameChars();
StringBuilder sb = new StringBuilder(uri.OriginalString.Length);
foreach (char c in uri.OriginalString)
{
sb.Append(Array.IndexOf(invalidChars, c) < 0 ? c : '_');
}
return sb.ToString();
}
}
``` | Extracting files from a Zip archive programmatically using C# and System.IO.Packaging | [
"",
"c#",
"zip",
"system.io.packaging",
""
] |
Today I fixed a bug in an application that might have lead to an endless loop in a servlet request/response cycle.
So just out of curiousity: What happens, if my servlet actually gets trapped in a for(;;) loop?
Is it somehow possible to recover? Will tomcat detect this? Can this instance be killed without restarting the server?
Or is this one of the worst things that can happen and a very quick way to kill a webcontainer?
EDIT: It was a true endless loop consuming CPU all the time but not memory. I kept it running for a few minutes. I think, I can confirm that tomcat will not detect this kind of thing :-) | I don't think that Tomcat will detect an infinite loop. You might be able to stop the servlet using the Tomcat manager, if the servlet is not consuming all the CPU time with its loop. Otherwise, it's probably safest and easiest to just restart the server.
This is why you do extensive tests locally before deploying your apps ;-) and be very careful that all your loops have exit conditions... | Not sure if Tomcat has such detection, but e.g Websphere's web container does.
However, it obviously takes the container a relatively long time to detect a "hung" thread. Server under a load can be easily and quickly killed by such code. | Endless loop in a servlet - recovery possible? | [
"",
"java",
"servlets",
""
] |
I am using ASP.NET C#.
How do I implement URL re-writing procedure that is similar to StackOverflow.com?
```
http://stackoverflow.com/questions/358630/how-to-search-date-in-sql
```
Also, what is the meaning of values such as "358630" in the URL? Is this the question ID (the basis for which they use to fetch the data from the table)? Whatever it is, in my application I am identifying records using an "ID" field. This field is an identity column in an SQL table. Right now, my URLs are like the following:
```
http://myweb.com/showdetails.aspx?id=9872
```
But I'd like them to appear like:
```
http://myweb.com/showdetails/9872/my_question_title
```
Or:
```
http://myweb.com/9872/my_question_title
```
Or whatever the best way, which will taste good to search bots.
My application is hosted on [Go Daddy](http://en.wikipedia.org/wiki/Go_Daddy)'s shared hosting service, and I feel that no customized ASP.NET "HTTP module" or no customized DLL for URL re-writing is working on their server. I tried many samples but no luck yet!
I found that Stack Overflow is hosted on Go Daddy (shared hosting?). Maybe Stack Overflow's method will work for me. | SO is using [ASP.NET MVC](http://asp.net/mvc). You really need to read in details how MVC URL rewriting works, but the gist of it is that the 'questions' part in the URL is the name of the Controller class (which roughly corresponds to the 'showdetails' in your URL) and the number is a ID parameter for the default action on that Controller (same as the parameter 'id' in your URL). | Since MVC isn't an option you can try redirecting the 404s. This will work in ASP.NET **1.1** and above: Redirect 404s and 405s to your own handler using either IIS config or web.config, parse out the request in the handler and redirect to the appropriate resource.
```
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="error.html">
<error statusCode="404" redirect="newHandler.aspx"/>
</customErrors>
</system.web>
</configuration>
``` | Rewriting URLs in ASP.NET? | [
"",
"c#",
"asp.net",
"url-rewriting",
"web-config",
""
] |
I'm using C# with SMO and attempting to detect what edition of SQL Server (e.g., enterprise, standard) I'm connecting to. I know how to get the version information, but that only tells me what version of SQL Server (e.g., SQL Server 2008 vs SQL Server 2005).
Does anyone know how to get the actual product edition (e.g., enterprise, standard)?
I need this information because some SQL Server features are only enterprise. Thus, I could just try to call them and catch the exception, but I'd much prefer an upfront detection.
Thanks! | It looks like you might be able to do it via SMO and the Server object. There are properties like Information.Edition which looks like it should do what you want. | ```
SELECT SERVERPROPERTY('productversion'),
SERVERPROPERTY ('productlevel'),
SERVERPROPERTY ('edition')
```
on my system returns
```
9.00.1399.06, RTM, Express Edition
```
It seems this technique only works on SQL Server 2000 or later, if any of your databases are 7.0 or less, you'll have to use @@Version and manipulate the results as others have posted | Programmatically detect SQL Server Edition | [
"",
"sql",
"sql-server",
"smo",
""
] |
I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like:
```
while True:
pass
```
or
```
while True:
time.sleep(1)
```
Which one will have the least impact on a system? What is the preferred way to do nothing, but keep a python app running? | I would imagine *time.sleep()* will have less overhead on the system. Using *pass* will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended.
**EDIT**: just to prove the point, if you launch the python interpreter and run this:
```
>>> while True:
... pass
...
```
You can watch Python start eating up 90-100% CPU instantly, versus:
```
>>> import time
>>> while True:
... time.sleep(1)
...
```
Which barely even registers on the Activity Monitor (using OS X here but it should be the same for every platform). | Why sleep? You don't want to sleep, you want to wait for the threads to finish.
So
```
# store the threads you start in a your_threads list, then
for a_thread in your_threads:
a_thread.join()
```
See: [thread.join](http://www.python.org/doc/2.5.2/lib/thread-objects.html#l2h-3460) | Python: Pass or Sleep for long running processes? | [
"",
"python",
""
] |
a quick question. I am using the jQuery.forms.js plug-in.
I have a form that posts to a php page and returns data with jSon.
The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded.
So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?
```
// jQuery for submitting info to php doc and, on success, replacing the form
$(document).ready(function() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
});
<!-- /////////////////////// POST ONLINE /////////////////////// -->
<div id='onlineStatus<?php echo $b_id ?>' class='postOnline'>
<form name="postOnline" id="postOnline<?php echo $b_id ?>" action="postOnline.php" method="post">
<input type="hidden" value="<?php echo $b_id ?>" name="b" />
<input type="hidden" value="1" name="p" />
<input type="submit" class="button" value="Post Online" />
</form>
</div>
<!-- /////////////////////// POST ONLINE /////////////////////// -->
// ... code for entering data into database and then...
$result = mysql_query( $sql );
if($result) {
if($show == '1'){$val = 'remove from online'; $num='0';}
if($show == '0'){$val = 'show online'; $num='1';}
$return = "
<form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'>
<input type='hidden' value='$b_id' name='b' />
<input type='hidden' value='$num' name='p' />
<input type='submit' class='button' value='$val' />
</form>
";
print json_encode(array("rid" => $id, "formed" => $return));
}
?>
``` | The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:
```
$(document).ready(function() {
jQuery('form[id*=postOnline]').live('submit', function() {
var formdata = $(this).serialize();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
dataType: 'json',
data: formdata,
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
return false;
});
});
```
Now since you are using jQuery's new (1.3) [`live`](http://docs.jquery.com/Events/live) functionality, any forms you add that match the `form[id*=postOnline]` selector will still be wired with this event.
Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it `live`. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:
```
function bindForm() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
bindForm();
}
});
}
$(document).ready(function() {
bindForm();
});
```
I don't think it is very neat, but it should work. | You need to rebind the event handlers after the ajax call. I heard about a new feature in the newer version of jquery called [live events](http://docs.jquery.com/Events/live), that would make this unnecessary though. | jQuery: form returned on "success" needs re-binding | [
"",
"php",
"jquery",
"json",
"jquery-plugins",
""
] |
I am using multithreading in my C# code as follow:
```
Thread startThread;
public void NewThread()
{
ThreadStart starter = delegate { foo(); };
startThread = new Thread(starter);
startThread.Start();
}
private void foo()
{
//do some work
}
```
And then in my application I call NewThread()to run the new thread.
But now I am having lots of threads on each class and each one has a NewThread() for itself, I was thinking of moving this to a static Util class and pass it the function name each time I want a new thread on that function.
**Do you know how this the best way of doing it, if yes how can I pass the function name as a parameter to it?** | Well, since the method is private, does it make sense for the caller to know the method name? If it was public, you could pass the method in:
```
public void NewThread(Action task)
{
ThreadStart starter = delegate { task(); };
startThread = new Thread(starter);
startThread.Name = task.Method.Name;
startSpoolerThread.Start();
}
public void foo()
{
//do some work
}
NewThread(obj.foo);
```
However, for a private method, I suspect an enum/switch is the best option...
```
NewThread(TasktType.Foo);
```
Alternatively, you can get the method via reflection...
```
public void NewThread(string name)
{
MethodInfo method = GetType().GetMethod(name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, Type.EmptyTypes, null);
ThreadStart starter = delegate { method.Invoke(this, null); };
// etc (note: no point using Delegate.CreateDelegate for a 1-call usage
``` | Unless there's a specific reason you're explicitly creating threads, why not use the Threadpool? The Threadpool.QueueUserWorkItem method takes a delegate as the unit of work to perform. The delegate is a specific type but you can wrap your own delegate call within it as you do in your example. Unless you need fine control or cancellation, in general it's better to use the thread pool rather than spinning up threads yourself. | Multithreading in C#: How can I pass a function name to another function to start a new thread? | [
"",
"c#",
".net",
"multithreading",
"oop",
""
] |
I am working on debugging some code and noticed a bunch of auto generated methods and objects.
At the top of the code for these I find the following comment:
```
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
```
**How** do you figure out what generated the code? My curiosity has gotten the better of me on this so that is why I ask. I have looked for parts of the comment in Google and found nothing concrete. | ```
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FirstWeb
{
public partial class _Default
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
```
You will not change this auto-generated C# file. As you keep adding ASP.NET controls to the page, this file grows with the additional declarations. In the older versions of C# (before version 2.0) and Visual Studio (before Version 2005), this code would be in the regular Default.aspx.cs file as well.
With the introduction of partial classes in C#, the code belonging to the same class can be split across multiple files. Here you see the “public partial class \_Default’, which is used to hold the **code generated by the Visual Studio designer**. You will see the same class signature in the Default.aspx.cs file as well (you use this to write your own custom code).
So, the developer (you) and the designer (Visual Studio) can work independently without stepping over each other.
This is taken from [First Web Program (Web Project) in C# Explained](http://www.infinitezest.com/articles/first-web-program-web-project-in-csharp-explained.aspx) | It will entirely depend on what the code is.
Presumably you know the class you're debugging - whether it's part of an ORM, part of a web service generated proxy etc. That's the crucial bit of information. | auto-generated Code | [
"",
"c#",
"visual-studio",
""
] |
Here's the scenario...
```
if (entry.Properties["something"].Value != null)
attribs.something = entry.Properties["something"].Value.ToString();
```
While effective and working correctly, this looks ugly to me. If I don't check for a null before performing the ToString() then it throws an exception if the property was null. Is there a better way to handle this scenario?
Much appreciated! | Update 8 years later (wow!) to cover [c# 6's null-conditional operator](https://msdn.microsoft.com/en-us/library/dn986595.aspx):
```
var value = maybeNull?.ToString() ?? String.Empty;
```
Other approaches:
```
object defaultValue = "default";
attribs.something = (entry.Properties["something"].Value ?? defaultValue).ToString()
```
I've also used this, which isn't terribly clever but convenient:
```
public static string ToSafeString(this object obj)
{
return (obj ?? string.Empty).ToString();
}
``` | If you are targeting the .NET Framework 3.5, the most elegant solution would be an extension method in my opinion.
```
public static class ObjectExtensions
{
public static string NullSafeToString(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
}
```
Then to use:
```
attribs.something = entry.Properties["something"].Value.NullSafeToString();
``` | Checking for null before ToString() | [
"",
"c#",
".net",
"string",
"properties",
""
] |
I'm building a MySQL query to determine how many items from each of several categories appear in a given date range. My initial attempt looked like this:
```
select Title,
(select count(*) from entries where CategoryID=1
and Date >= @StartDate and Date <= @EndDate) as Cat1,
(select count(*) from entries where CategoryID=2
and Date >= @StartDate and Date <= @EndDate) as Cat2,
(select count(*) from entries where CategoryID is null
and Date >= @StartDate and Date <= @EndDate) as UnkownCategory
from entries
where Date >= @StartDate and Date <= @EndDate
```
The table is quite large and I'd like to refactor the query to speed it up, but I'm not sure how - can this be rewritten using GROUP BY/HAVING statements or is there another way I'm missing?
**Edit**: Sample result set - something like this:
```
Title | Category 1 Total | Category 2 Total | Unknown Category Total
ABC 1 3 0
DEF 2 7 2
``` | ```
select Title, SUM(CategoryID=1) as Cat1, SUM(categoryID=2) as Cat2,
SUM(categoryID IS NULL) as UnknownCategory
FROM entries
WHERE Date BETWEEN @StartDate AND @EndDate
GROUP BY Title
```
You can stick expressions in sum() functions: truth equals 1, false equals 0. Also I used the BETWEEN operator which is a little faster.
An alternative that would return a different result layout but is a little conceptually simpler:
```
select Title, CategoryID, count(*)
from entries
WHERE Date BETWEEN @StartDate AND @EndDate
group by Title, CategoryID
``` | ```
Select COUNT(*), sTitle, CategoryID FROM entries
WHERE Date >= @StartDate and Date <= @EndDate
GROUP BY CategoryID, sTitle
``` | Refactor subqueries using GROUP BY/HAVING? | [
"",
"sql",
"mysql",
"refactoring",
"query-optimization",
""
] |
If I have a method that returns something, like
```
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
}
```
This produces compiler error, obviously because `catch{}` block does not return anything.
So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice? | Store your return value in a temporary variable like this:
```
public DataTable ReturnSomething()
{
DataTable returnValue = null;
try
{
//logic here
returnValue = ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
return returnValue;
}
``` | You should raise/throw the exception in your catch block and handle it in the calling method.
```
public void invokeFaultyCode()
{
try
{
DataTable dt = ReturnSomething();
}
catch(Exception e)
{
// Print the error message, cleanup, whatever
}
}
public DataTable ReturnSomething() throws Exception
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw;
}
}
```
PS: Sorry for any syntax error, I'm a bit rusty on C#. | try-catch blocks with the return type | [
"",
"c#",
"error-handling",
""
] |
Here is the **scenario 1.**
I have a table called "items", inside the table has 2 columns, e. g. `item_id` and `item_name`.
I store my data in this way:
item\_id | item\_name
```
Ss001 | Shirt1
Sb002 | Shirt2
Tb001 | TShirt1
Tm002 | TShirt2
```
... etc, i store in this way:
first letter is the code for clothes, i.e S for shirt, T for tshirt
second letter is size, i.e s for small, m for medium and b for big
Lets say in my items table i got 10,000 items. I want to do fast retrieve, lets say I want to find a particular shirt, can I use:
Method1:
```
SELECT * from items WHERE item_id LIKE Sb99;
```
or should I do it like:
Method2:
```
SELECT * from items WHERE item_id LIKE S*;
```
\*Store the result, then execute second search for the size, then third search for the id. Like the hash table concept.
What I want to achieve is, instead of search all the data, I want to minimize the search by search the clothes code first, follow by size code and then id code. Which one is better in term of speed in mysql. And which one is better in long run. I want to reduce the traffic and not to disturb the database so often.
Thanks guys for solving my first scenario. But another scenario comes in:
**Scenario 2:**
I am using PHP and MySQL. Continue from the preivous story. If my users table structure is like this:
```
user_id | username | items_collected
U0001 | Alex | Ss001;Tm002
U0002 | Daniel | Tb001;Sb002
U0003 | Michael | ...
U0004 | Thomas | ...
```
I store the items\_collected in id form because one day each user can collect up to hundreds items, if I store as string, i.e. Shirt1, pants2, ..., it would required a very large amount of database spaces (imagine if we have 1000 users and some items name are very long).
Would it be easier to maintain if I store in id form?
And if lets say, I want to display the image, and the image's name is the item's name + jpg. How to do that? Is it something like this:
$result = Select items\_collected from users where userid= $userid
Using php explode:
$itemsCollected = explode($result, ";");
After that, matching each item in the items table, so it would like:
shirt1, pants2 etc
Den using loop function, loop each value and add ".jpg" to display the image? | The first method will be faster - but IMO it's not the right way of doing it. I'm in agreement with tehvan about that.
I'd recommend keeping the item\_id as is, but add two extra fields one for the code and one for the size, then you can do:
```
select * from items where item_code = 'S' and item_size = 'm'
```
With indexes the performance will be greatly increased, and you'll be able to easily match a range of sizes, or codes.
```
select * from items where item_code = 'S' and item_size IN ('m','s')
```
Migrate the db as follows:
```
alter table items add column item_code varchar(1) default '';
alter table items add column item_size varchar(1) default '';
update items set item_code = SUBSTRING(item_id, 1, 1);
update items set item_size = SUBSTRING(item_id, 2, 1);
```
The changes to the code should be equally simple to add. The long term benefit will be worth the effort.
---
For scenario 2 - that is not an efficient way of storing and retrieving data from a database. When used in this way the database is only acting as a storage engine, by encoding multiple data into fields you are precluding the relational part of the database from being useful.
What you should do in that circumstance is to have another table, call it 'items\_collected'. The schema would be along the lines of
```
CREATE TABLE items_collected (
id int(11) NOT NULL auto_increment KEY,
userid int(11) NOT NULL,
item_code varchar(10) NOT NULL,
FOREIGN KEY (`userid`) REFERENCES `user`(`id`),
FOREIGN KEY (`itemcode`) REFERENCES `items`(`item_code`)
);
```
The foreign keys ensure that there is [Referential integrity](http://en.wikipedia.org/wiki/Referential_integrity), it's essential [to have referential integrity](http://rapidapplicationdevelopment.blogspot.com/2007/07/referential-integrity-data-modeling.html).
Then for the example you give you would have multiple records.
```
user_id | username | items_collected
U0001 | Alex | Ss001
U0001 | Alex | Tm002
U0002 | Daniel | Sb002
U0002 | Daniel | Tb001
U0003 | Michael | ...
U0004 | Thomas | ...
``` | The first optimization would be splitting the id into three different fields:
one for type, one for size, one for the current id ending (whatever the ending means)
If you really want to keep the current structure, go for the result straight away (option 1). | Optimize MySQL search process | [
"",
"php",
"mysql",
"search",
"methods",
""
] |
In Python, is there a better way to **parameterise strings into regular expressions** than doing it manually like this:
```
test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
```
*This noddy example tries to match each name in turn. I know there's better ways of doing that, but its a simple example purely to illustrate the point.*
---
**The answer appears to be no, there's no real alternative. The best way to paramaterise regular expressions in python is as above or with derivatives such as `str.format()`.** I tried to write a generic question, rather than *'fix ma codez, kthxbye'*. For those still interested, I've fleshed out an example closer to my needs here:
```
for diskfilename in os.listdir(''):
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
for filename in filenames:
name, ext = filename.split('.')
regexp = "%s.*\.%s" % (name, ext)
m = re.search(regexp, diskfilename)
if m:
print diskfilename, regexp, re.search(regexp, diskfilename)
# ...
```
I'm trying to figure out the 'type' of a file based on its filename, of the form `<filename>_<date>.<extension>`. In my real code, the `filenames` array is a dict, containing a function to call once a match is found.
Other ways I've considered doing it:
* **Have a regular expression in the array.** I already have an array of filenames without any regular expression magic, so I am loathe to do this. I have done this elsewhere in my code and its a mess (though necessary there).
* **Match only on the start of the filename.** This would work, but would break with .bak copies of files, etc. At some point I'll probably want to extract the date from the filename so would need to use a regular expression anyway.
---
Thanks for the responses suggesting alternatives to regular expressions to achieve the same end result. I was more interested in parameterising regular expressions for now and for the future. I never come across *fnmatch*, so its all useful in the long run. | Well, as you build a regexp from a string, I see no other way. But you could *parameterise the string itself* with a dictionary:
```
d = {'bar': 'a', 'foo': 'b'}
regexp = '%(foo)s|%(bar)s' % d
```
Or, depending on the problem, you could use list comprehensions:
```
vlist = ['a', 'b', 'c']
regexp = '|'.join([s for s in vlist])
```
**EDIT:** Mat clarified his question, this makes things different and the above mentioned is totally irrelevant.
I'd probably go with an approach like this:
```
filename = 'bob_20090216.txt'
regexps = {'bob': 'bob_[0-9]+.txt',
'fred': 'fred_[0-9]+.txt',
'paul': 'paul_[0-9]+.txt'}
for filetype, regexp in regexps.items():
m = re.match(regexp, filename)
if m != None:
print '%s is of type %s' % (filename, filetype)
``` | ```
import fnmatch, os
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
# 'b.txt.b' -> 'b.txt*.b'
filepatterns = ((f, '*'.join(os.path.splitext(f))) for f in filenames)
diskfilenames = filter(os.path.isfile, os.listdir(''))
pattern2filenames = dict((fn, fnmatch.filter(diskfilenames, pat))
for fn, pat in filepatterns)
print pattern2filenames
```
Output:
```
{'bob.txt': ['bob20090217.txt'], 'paul.txt': [], 'fred.txt': []}
```
Answers to previous revisions of your question follow:
---
I don't understand your updated question but `filename.startswith(prefix)` might be sufficient in your specific case.
After you've updated your question the old answer below is less relevant.
---
1. Use `re.escape(name)` if you'd like to match a `name` literally.
2. Any tool available for string parametrization is applicable here. For example:
```
import string
print string.Template("$a $b").substitute(a=1, b="B")
# 1 B
```
Or using [`str.format()`](http://docs.python.org/library/string.html#format-string-syntax) in Python 2.6+:
```
print "{0.imag}".format(1j+2)
# 1.0
``` | Parameterised regular expression in Python | [
"",
"python",
"regex",
""
] |
Is it possible to establish a set of templated function pointers, without the hassle of doing so manually? Here's an example to illustrate what the heck I'm talking about.
Let's say I have a frequently-called function "write" of which I have two implementations (write0 and write1) that I'd like to be able to switch between dynamically. These write functions are templated on the argument type. One way to do this is to just have a templated front-end function write() which internally uses an if statement.
This turns out to be fast enough for my needs, but now I was left wondering if I can do the same using function pointers (just for fun). The problem with this approach is that setting up the function pointers is a hassle. Are there any other ways to essentially achieve the ideal of write() but without the conditional (direct static dispatch)?
(Other "rules": I can't change the Msg classes to have write() methods, and I can't change the use site code to replace Msgs with adaptors for Msgs.)
FWIW, I found [this article](http://www.devarticles.com/c/a/Cplusplus/Function-Pointers-part-1/3/) basically saying the same thing I'm saying here.
```
#include <iostream>
using namespace std;
template<typename T> void write0(T msg) { cout << "write0: " << msg.name() << endl; }
template<typename T> void write1(T msg) { cout << "write1: " << msg.name() << endl; }
// This isn't so bad, since it's just a conditional (which the processor will
// likely predict correctly most of the time).
bool use_write0;
template<typename T> void write(T msg) { if (use_write0) write0(msg); else write1(msg); }
struct MsgA { const char *name() { return "MsgA"; } };
struct MsgB { const char *name() { return "MsgB"; } };
struct MsgC { const char *name() { return "MsgC"; } };
struct MsgD { const char *name() { return "MsgD"; } };
// This doesn't work: templates may not be virtual.
#if 0
struct Writer { template<typename T> virtual void write(T msg) = 0; };
struct Writer0 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } };
struct Writer1 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } };
#endif
int main(int argc, char **argv) {
use_write0 = argc == 1;
// I can do this:
write(MsgA());
// Can I achieve the following without the verbosity (manual setup, named
// template instantiations, etc.)?
void (*pwriteA)(MsgA) = use_write0 ? (void(*)(MsgA)) write0<MsgA> : (void(*)(MsgA)) write1<MsgA>;
void (*pwriteB)(MsgB) = use_write0 ? (void(*)(MsgB)) write0<MsgB> : (void(*)(MsgB)) write1<MsgB>;
void (*pwriteC)(MsgC) = use_write0 ? (void(*)(MsgC)) write0<MsgC> : (void(*)(MsgC)) write1<MsgC>;
void (*pwriteD)(MsgD) = use_write0 ? (void(*)(MsgD)) write0<MsgD> : (void(*)(MsgD)) write1<MsgD>;
pwriteA(MsgA());
pwriteB(MsgB());
pwriteC(MsgC());
pwriteD(MsgD());
return 0;
}
``` | If you want to switch logging functions back and forth while the program runs, I think you have to manually set the function pointer for each type.
If it's enough to just choose the logging function at startup, it can be done in a fully generic way without even knowing for which types the function will be called later:
```
// writer functions
template<typename T> void write0(T msg) { std::cout << 0; };
template<typename T> void write1(T msg) { std::cout << 1; };
// global flag
bool use_write0;
// function pointers for all types
template<typename T>
struct dispatch {
typedef void (*write_t)(T);
static write_t ptr;
};
// main write function
template<typename T>
inline void write(T msg) {
(*dispatch<T>::ptr)(msg);
}
// the fun part
template<typename T>
void autoinit(T msg) {
if (use_write0)
dispatch<T>::ptr = &write0<T>;
else
dispatch<T>::ptr = &write1<T>;
// call again for dispatch to correct function
write(msg);
}
// initialization
template<typename T>
typename dispatch<T>::write_t dispatch<T>::ptr = &autoinit<T>;
// usage example
int main(int argc, char **argv) {
use_write0 = (argc == 1);
write("abc");
return 0;
}
```
For each type `T` the first call to `write<T>()` decides which writing function should be used. Later calls then directly use the function pointer to that function. | You could also use Don Clugston's [FastDelegates](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) header. Generates no runtime overhead whatsoever and truly object-oriented delegates. While the syntax for using them is not perfect, it is a bit simpler than fiddling with raw function pointers. | How else to achieve "templated function pointers"? | [
"",
"c++",
"templates",
"function-pointers",
""
] |
I'm using WAMP as a server, and I have a need to execute svn, which can be found in my Windows directory: C:/Program Files/Subversion/bin/
The problem, is that when I launch the php program from the server, it won't produce output. It works from the command line, which makes me think this is a permissions problem with WAMP. However after giving it unlimited power, it still won't execute svn commands unless I call it from the command line.
I've tried calling it with the full path to svn, and it's regular path. Other commands like "dir" work fine.
To clarify my question: How can I execute svn from php through WAMP? | use free svn classes instead, they don't require svn module:
<http://www.phpclasses.org/browse/package/3427.ht>
<http://code.google.com/p/phpsvnclient/> | PHP has a [whole bunch](http://php.net/svn) of functions which deal explicitly with svn repositories and doesn't require you to use any system()-type functions.
Since you said you cannot use the various svn functions, try the following:
```
<?php
$cmd = 'set PATH';
echo '<pre>' , shell_exec( $cmd ) , '</pre>';
?>
```
See what that returns (look for the PATH environment variable). See what PATH contains.
You may have to add the Subversion folder to your PATH:
```
<?php
$cmd = 'set PATH=%PATH%;"C:\Program Files\Subversion\bin\"; svn up';
shell_exec( $cmd );
?>
```
Hopefully, setting the PATH will solve your problem. | WAMP - PHP shell_exec() problem | [
"",
"php",
"svn",
"command-line",
"permissions",
"wamp",
""
] |
Suppose I need to have a class which wraps a priority queue of other objects (meaning the queue is a member of the class), and additionally gives it some extra functions.
I am not quite sure what the best way is to define that vector and, mainly, how to instantiate it.
Currently I have something like this in the header file:
```
// in SomeClass.h:
class SomeClass
{
public:
SomeClass(); // constructor
// other methods
private:
std::priority_queue<OtherClass> queue;
};
```
while the source file is something like this:
```
// in SomeClass.cpp
SomeClass::SomeClass():
queue() // removed the constructor, no need to explicitly call it
{}
// other methods
```
---
**EDIT:** removed the call, per Ray's answer. | Just write:
```
SomeClass::SomeClass():
queue() { }
```
C++ knows to call the constructor automatically from there with no arguments. | Your member is an instance, but what you're doing is trying to initialize that instance with a pointer to a newly allocated instance. Either leave the initialization empty (as Ray pointed out) or leave it out of the initialization list of the constructor completely.
```
SomeClass::SomeClass() {}
```
has the same queue initialized as
```
SomeClass::SomeClass() : queue() {}
```
If you really want to allocate it on the heap using new, then your member needs to be declared in the header as:
```
private:
std::priority_queue<OtherClass>* queue;
```
But I would recommend against doing that, unless you plan to let some other class take over ownership of the same instance of queue later and don't want the destructor of SomeClass to free it. | Instantiating a queue as a class member in C++ | [
"",
"c++",
"oop",
""
] |
In the computer algebra system [Sage](http://www.sagemath.org/),
I need to multiply a list by 2.
I tried the code
```
sage: list = [1, 2, 3];
sage: 2 * list
```
which returns
```
[1, 2, 3, 1, 2, 3]
```
How can I just multiply each element by two? | Do you want to multiply each element by 2? That would be:
```
[2*i for i in List]
``` | Or:
```
import numpy
numpy.multiply(List, 2)
``` | How can I manipulate lists? | [
"",
"python",
"list",
""
] |
**<edit>**
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:
```
zip(range(len(files)), files, directories)
```
**</edit>**
Hi,
I'm in the process of learning Python, but I come from a background where the following pseudocode is typical:
```
directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for(i = 0; i < directories.length; i++) {
print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n'
}
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
```
In Python, the way I would write the above right now, would be like this:
```
directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for i in range(len(directories)):
print '%s. %s/%s' % ((i + 1), directories[i], files[i]
# Output:
# 1. directory_0/file_a
# 2. directory_1/file_b
# 3. directory_2/file_c
```
While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" ([Simple Counters](http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter)). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages.
I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way?
If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension?
For example, if all I wanted from the output was this (no counters, is that possible with list comprehension):
```
# Output:
# directory_0/file_a
# directory_1/file_b
# directory_2/file_c
```
Thanks in advance for any help. | ```
import os.path
for dir, file in zip(directories, files):
print(os.path.join(dir, file)) # for directories, files
```
you can have it as a list comprehension as well, creating list of string with print going after that]
with counter:
```
for i, (dir, file) in enumerate(zip(directories, files)):
print(i, os.path.join(dir, file))
``` | Try this:
```
directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for file, dir in zip(files, directories):
print dir + '/' + file
```
To explain, the `zip()` function takes lists as input and returns a list of "zipped" tuples. so `zip([1,2,3,4,5],[a,b,c,d,e])` would return `[(1,a),(2,b)` and so on.
You can then assign the members of the tuples to variables with the python `for <var> in <list>` syntax.
There are a million different ways to do what you are asking, but the above uses some more "pythonic" constructs to make the code a lot more readable (IMHO, anyway). | Python loops with multiple lists? | [
"",
"python",
"arrays",
"loops",
"list",
""
] |
I need to query this DB to get each row, but also the SUM of one of the column values of the results. I could use php to get the total value, but then I'd need to run two loops, one to get the total (which goes at the top above the results). So I'd prefer the query to catch it and just make a "total" row, but the only way I've gotten it to work is with a subquery that is essentially a repeat of the original query. Is there a better way?
```
SELECT
CONCAT(u.firstname, ' ', u.lastname ) name, u.id, s.description, s.shiftstart, s.shiftend,
(SELECT
SUM( TIME_TO_SEC( TIMEDIFF( shiftend, shiftstart ) ) ) /3600
FROM shifts
WHERE id = '$user'
AND DATE( shiftstart )
BETWEEN '$start'
AND '$end') total
FROM shifts s
INNER JOIN users u ON ( s.id = u.id )
WHERE s.id = '$user'
AND DATE( shiftstart )
BETWEEN '$start'
AND '$end'
ORDER BY shiftstart
```
The above works and outputs:
```
name id description shiftstart shiftend total
Joe User joeuser Stuff 2009-01-05 07:45:00 2009-01-05 12:15:00 39.5000
Joe User joeuser Stuff 2009-01-05 13:00:00 2009-01-05 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-06 07:45:00 2009-01-06 10:45:00 39.5000
Joe User joeuser Stuff 2009-01-06 10:45:00 2009-01-06 12:45:00 39.5000
Joe User joeuser Stuff 2009-01-06 13:30:00 2009-01-06 14:30:00 39.5000
Joe User joeuser Stuff 2009-01-06 14:30:00 2009-01-06 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-07 09:45:00 2009-01-07 14:00:00 39.5000
Joe User joeuser Stuff 2009-01-07 15:00:00 2009-01-07 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-08 08:00:00 2009-01-08 12:15:00 39.5000
Joe User joeuser Stuff 2009-01-08 13:15:00 2009-01-08 17:00:00 39.5000
Joe User joeuser Stuff 2009-01-09 07:45:00 2009-01-09 10:45:00 39.5000
Joe User joeuser Stuff 2009-01-09 11:45:00 2009-01-09 15:15:00 39.5000
Joe User joeuser Stuff 2009-01-09 15:15:00 2009-01-09 17:00:00 39.5000
```
Which is what I need, but probably not the best way to get it. | MySQL supports a special group-by modifier called [ROLLUP](http://dev.mysql.com/doc/refman/5.1/en/group-by-modifiers.html).
```
SELECT CONCAT(u.firstname, ' ', u.lastname ) name, u.id,
s.description, s.shiftstart, s.shiftend,
SUM( TIME_TO_SEC( TIMEDIFF( shiftend, shiftstart ) ) ) /3600 total
FROM shifts s INNER JOIN users u ON ( s.id = u.id )
WHERE s.id = ? AND DATE( shiftstart ) BETWEEN ? AND ?
GROUP BY u.id, s.shiftstart WITH ROLLUP
ORDER BY shiftstart;
``` | The better way is to do this with code. People keep insisting on using SQL, which is a relational algebra, for doing procedural duties. Trying to shoehorn procedural-ness onto SQL is **always** a bad idea, in terms of both complexity and performance. Take this advice from a professional DBA.
Run two queries from your code. Output the larger set first then the total line in whatever format you desire. Your queries will be smaller and simpler, your performance will improve and you'll get the output you desire.
Some other advice - disk space is cheap and most database tables are read far more often than they're written. Set up an insert/update trigger (if possible in MySQL) to populate a separate column with calculated fields like "`CONCAT(u.firstname,' ',u.lastname)`" and use that for queries. Per-row functions are not scalable and will kill your DBMS performance as it gets bigger. | MySQL add total column | [
"",
"sql",
"mysql",
"aggregate-functions",
"subquery",
""
] |
I've got an input which it's type is set to hidden, I need to change it's type to text. Can't seem to figure this out or if it's possible with jQuery | With jQuery 1.4 you can change the type of an input while it's detached.
```
marker = $('<span />').insertBefore('#myInput');
$('#myInput').detach().attr('type', 'text').insertAfter(marker);
marker.remove();
``` | I'm not sure this is possible, so I would suggest using a hidden div to contain the input element, which can be shown as needed. The text input field can still hold data even if it's hidden. | jQuery: Change element type from hidden to input | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
I'm trying to implement a log viewer in my application. The idea is simple, a listbox that shows some messages sended from other classes, but I don't know what is the best way to do this.
My initial thought was to make a Logger class (**singletone**) that contains a **List** or **Queue**, then I'll add a **method AddMessage(string s)** or something like that. When this method is called it will add the message to the list or queue and it **will fire a NewMessage event**. This event is because I don't think that is a good idea to check the list every some amount of time. The sequence of messages could be 3 consecutives, then 40 minutes without nothing, then a few more ...
So, in my form class (or wherever I want to receive the messages) I will listen to this event to empty the list or queue **(this is because I should be able to send messages even when the listbox (final receptor) has not been created)**. The idea of the list is to save messages when no one is listening the event.
Also, i've put a restriction of 300 messages... so the oldest ones will be deleted everytime i'm going to add new ones... something like this:
```
while(listbox.Items.Count > 300)
{
listbox.Items.RemoveAt(0);
}
```
Do you think that this is the best approach?
Thanks for your time.
Best regards.
**Edit 1: I don't want to use another framework.**
**Edit 2: STOP suggesting frameworks or another application. I want to learn the logic behind, and if what i was proposing is right or wrong!** | Some of the questions to consider are:
* Is your application multi-threaded? Is the thread[s] which write[s] the messages the same as the UI thread which reads the messages and populates the list box?
* How many messages per second and being created?
* How many times per second do you want to update the list box?
* What's the maximum number of messages over time? Do you display them all in the list box, or do you discard older ones?
* Do you want log the messages into a file as well (e.g. for tech support purposes)?
* Is the listbox (the UI element) the only place where messages are stored? Is the listbox always displayed, or can the user hide/destroy it?
* How sophisticated are the end-users? Can you ask them to use other (better) tools to view your log file, or do you need to implement a (relatively unsophisticated) viewer into your own UI?
Sorry to answer your question with questions, but these are questions which need answering before you can say "is this the best approach?".
---
> it's not a multithreaded application, is a freaking small application that I don't want to overload.
If the application isn't multi-threaded, then the 'simplest thing that could possibly work' would be to not bother with a list or queue; and instead, let your other classes append messages directly into the UI listbox element (perhaps via a delegate), for example:
```
class MyClass
{
Action<string> log;
MyClass(Action<string> log)
{
this.log = log;
}
void Something()
{
//log a message
log("Hello world!");
}
}
class MyForm
{
ListBox listBox = new ListBox();
MyClass myClass;
MyForm()
{
//create a delegate which logs strings
//by writing them to the ListBox
Action<string> log = delegate(string s) {
listBox.Items.Add(s);
};
//pass this logger to classes which need to use it
myClass = new MyClass(log);
//test it
myClass.Something();
}
}
```
---
Here's similar code using a non-anonymous delegate, with some extra functionality as requested in one of your comments:
```
class MyForm
{
ListBox listBox = new ListBox();
MyClass myClass;
MyForm()
{
//pass the Log action to classes which need to use it
myClass = new MyClass(Log);
//test it
myClass.Something();
}
///logs strings by writing them to the ListBox
void Log(string s)
{
if (listBox.Items.Count == 300)
listBox.Items.RemoveAt(0);
listBox.Items.Add(s);
}
}
```
---
> I think I answer wrong the (6). I should be able to send messages even if the listbox has not been created yet... that's why I suggested a List or Queue
In this case, you do need storage other than only the ListBox. Your suggestion would work. An alternative suggestion is:
* When you create your ListBox, populate it from the List (using the ListBox.Items.AddRange method)
* In the Log function, if the ListBox doesn't exist then write the message to the List, else if the ListBox does exist then write the message to the ListBox.
Doing this *might* be (very slightly) simpler than defining, listening to, and firing an event. | Any reason not to use existing technologies?
* [Log4Net](http://logging.apache.org/log4net/index.html) or some other framework to write out to a log file
* A text editor (and text filters, grep etc) to view and filter the log files
EDIT: I would still be tempted to use Log4Net and have a listener for *some* categories/levels which dumps to a scrolling textbox. That way you can *also* log (with possibly more detail) to a file.
EDIT: If you want to learn, then I would suggest looking at the design and implementation of Log4Net. Work out its strengths and weaknesses with respect to your particular situation. | What is the best approach to send some text from one class to another (with some restrictions)? | [
"",
"c#",
".net",
"logging",
""
] |
The following script works fine in IE7 but fails to execute in Firefox 3. The div tag which was display: none; shows in IE but never in FF. I am not a client / javascript guy... thanks.
```
<script type="text/javascript">
//<![CDATA[
document.getElementById("Fred1_Panel").style.setAttribute("display","inline");//]]>
</script>
``` | try this:
```
document.getElementById("Fred1_Panel").style.display = '';
```
OR
```
document.getElementById("Fred1_Panel").style.display = 'inline';
``` | This will work in both browsers:
```
document.getElementById("Fred1_Panel").style.display = 'inline';
``` | Javascript in IE vs Firefox | [
"",
"javascript",
"dom",
""
] |
My clipboard is populated with text, but when I run
```
string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);
```
I get back an empty string. I've toyed with various forms of the call including:
```
string clipboardData = Clipboard.GetText();
string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.UnicodeText);
```
But with the same result.
Am I missing something obvious? | You can only access the clipboard from an STA thread. Rick Brewster ran into this with some refactoring of the regular Edit->Paste command, in Paint.NET.
Code:
```
IDataObject idat = null;
Exception threadEx = null;
Thread staThread = new Thread(
delegate ()
{
try
{
idat = Clipboard.GetDataObject();
}
catch (Exception ex)
{
threadEx = ex;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
// at this point either you have clipboard data or an exception
```
Code is from Rick. <http://forums.getpaint.net/index.php?/topic/13712-/page__view__findpost__p__226140>
**Update**: [Jason Heine](https://stackoverflow.com/users/337315/jason-heine) made a good point of adding `()` after `delegate` to fix the ambiguous method error. | Honestly, I don't know what a STA thread is, but in simple projects it might solve the problem to add `[STAThread]` right before the `Main` method:
```
[STAThread]
static void Main(string[] args)
{ (...)
```
It works for me, so I don't question the method ;)
---
Further information about the `[STAThread]` decorator is on blog post *[Why is STAThread required?](https://web.archive.org/web/20160219220313/http://blogs.msdn.com:80/b/jfoscoding/archive/2005/04/07/406341.aspx)*. | Clipboard.GetText returns null (empty string) | [
"",
"c#",
".net",
""
] |
I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str".
```
import smtplib
smtpserver = 'mail.somedomain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin@somedomain.com' # for SMTP AUTH, set SMTP username here
smtppass = 'somepassword' # for SMTP AUTH, set SMTP password here
msg = "Some message to send"
RECIPIENTS = ['admin@somedomain.com']
SENDER = 'someone@someotherdomain.net'
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, msg)
```
Google shows there are some issues with that error not being clear, but I still can't figure out what I need to try to make it work. Suggestions included defining the username as b"username", but that doesn't seem to work either. | **UPDATE**: just noticed from a look at the bug tracker there's a suggested fix also:
Edit smtplib.py and replace the existing `encode_plain()` definition with this:
```
def encode_plain(user, password):
s = "\0%s\0%s" % (user, password)
return encode_base64(s.encode('ascii'), eol='')
```
Tested here on my installation and it works properly. | ```
Traceback (most recent call last):
File "smtptest.py", line 18, in <module>
session.login(smtpuser, smtppass)
File "c:\Python30\lib\smtplib.py", line 580, in login
AUTH_PLAIN + " " + encode_plain(user, password))
File "c:\Python30\lib\smtplib.py", line 545, in encode_plain
return encode_base64("\0%s\0%s" % (user, password))
File "c:\Python30\lib\email\base64mime.py", line 96, in body_encode
enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
TypeError: b2a_base64() argument 1 must be bytes or buffer, not str
```
Your code is correct. This is a bug in **smtplib** or in the **base64mime.py**.
You can track the issue here:
<http://bugs.python.org/issue5259>
Hopefully the devs will post a patch soon. | Python 3.0 smtplib | [
"",
"python",
"python-3.x",
""
] |
I have a class `Customer` (with typical customer properties) and I need to pass around, and databind, a "chunk" of `Customer` instances. Currently I'm using an array of `Customer`, but I've also used `Collection` of `T` (and `List` of `T` before I knew about `Collection` of `T`). I'd like the thinnest way to pass this chunk around using C# and .NET 3.5.
Currently, the array of `Customer` is working just fine for me. It data binds well and seems to be as lightweight as it gets. I don't need the stuff `List` of `T` offers and `Collection` of `T` still seems like overkill. The array does require that I know ahead of time how many `Customer`s I'm adding to the chunk, but I always know that in advance (given rows in a page, for example).
Am I missing something fundamental or is the array of `Customer` OK? Is there a tradeoff I'm missing?
Also, I'm assuming that `Collection` of `T` makes the old loosely-typed `ArrayList` obsolete. Am I right there? | No one has mentioned the Framework Guidelines advice: [Don't use `List<T>` in public API's](http://blogs.gotdotnet.com/kcwalina/archive/2005/09/26/474010.aspx):
> We don’t recommend using List in
> public APIs for two reasons.
>
> * `List<T>` is not designed to be extended. i.e. you cannot override any
> members. This for example means that
> an object returning `List<T>` from a
> property won’t be able to get notified
> when the collection is modified.
> `Collection<T>` lets you overrides
> SetItem protected member to get
> “notified” when a new items is added
> or an existing item is changed.
> * List has lots of members that are not relevant in many scenarios. We
> say that `List<T>` is too “busy” for
> public object models. Imagine
> ListView.Items property returning
> `List<T>` with all its richness. Now,
> look at the actual `ListView.Items`
> return type; it’s way simpler and
> similar to `Collection<T>` or
> `ReadOnlyCollection<T>`
Also, if your goal is two-way Databinding, have a look at [`BindingList<T>`](http://msdn.microsoft.com/en-us/library/ms132679.aspx) (with the caveat that it is not sortable 'out of the box'!) | Yes, `Collection<T>` (or `List<T>` more commonly) makes `ArrayList` pretty much obsolete. In particular, I believe `ArrayList` isn't even supported in Silverlight 2.
Arrays are okay in some cases, but should be [considered somewhat harmful](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx) - they have various disadvantages. (They're at the heart of the *implementation* of most collections, of course...) I'd go into more details, but Eric Lippert does it so much better than I ever could in the article referenced by the link. I would summarise it here, but that's quite hard to do. It really is worth just reading the whole post. | ArrayList versus an array of objects versus Collection of T | [
"",
"c#",
"arrays",
"generics",
"collections",
""
] |
I have many different regex patterns automatically loaded everytime my greasemonkey script starts. 95% of this loaded memory isn't needed at any stage, so I would like to find a way to not even put that data into memory to begin with if I know it won't be used.
Take this a basic example:
```
var patterns = [
{
name : 'p1',
url : 'http://www.someurl.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
},
{
name : 'p2',
url : 'http://www.someurl2.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
},
{
name : 'p3',
url : 'http://www.someurl3.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
},
];
```
....and many more patterns.
I don't need to load any of the data if the url does not match the current url (location.href). | The best way is if you could load data on demand via GM\_getResourceText+eval. The resource data defined in the metadata block will be downloaded on the userscript's first install.
Documentation: <http://wiki.greasespot.net/Metadata_block#.40resource>
You need to think how to store the data - maybe a resource per site (nasty I know) ?
Another simpler solution to alleviate performance problems is to store the regular expressions as simple strings and create RegExp objects only when needed. Eg: `patterns : [".", ".", "."]` and `new RegExp(the_pattern)` when the expression is actually needed. | You could stick with your current definition of patterns and remove all the patterns you don't need:
```
var patterns = [
//patterns array as defined in question
];
var newpatterns = [];
var count = 0;
for (var i = 0 ; i < patterns.length ; i++ ){
if (href.indexOf(patterns[i].url) == -1) {
newpatterns[count++] = patterns[i];
console.log("remove " + patterns[i].name);
}
}
patterns = newpatterns;
```
Although this way you're still loading it all into memory initially, but not keeping objects you don't need for the whole lifetime of the page.
A better way would be to test each object one at a time, before it's added to the patterns array, and only adds objects relevant to the current url.
```
var patterns = [];
var count = 0;
var href = window.location.href;
function addPattern(p){
if (href.indexOf(p.url) != -1) patterns[count++] = p;
}
addPattern({
name : 'p1',
url : 'http://www.someurl.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
})
addPattern({
name : 'p2',
url : 'http://www.someurl2.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
})
addPattern({
name : 'p3',
url : 'http://www.someurl3.com',
pattern1 : /./,
pattern2 : /./,
pattern3 : /./,
})
``` | Javascript: loading mass amount of data in memory based on condition | [
"",
"javascript",
"greasemonkey",
""
] |
Often I find myself working on a new project with a giant RDBMS whose schema I don't yet understand. I want to be able to mark a checkpoint in the database, do something in the app, and then go back to the database and ask it which tables changed (and ideally, what records changed).
Is there a way to do something like this with SQL? I found [this](https://stackoverflow.com/questions/36/check-for-changes-to-a-sql-table), but it's MSSQL-only (which I'm not using).
It doesn't need to be super efficient. It's just going to be on my dev box and I can wait a few seconds if need be, but I am looking for something better than "dump the whole DB twice and diff the results". | If your DBMS supports query logging, turn it on and tail -f the log. | SQL Server and Oracle both have a feature you can enable called "Change Data Capture". You said you're not using SQL Server, but there's still hope here if you're on Oracle. Perhaps you should mention what dbms you use. | Is there a way in SQL to ask "what changed?"? | [
"",
"sql",
"database",
"diff",
""
] |
Where can I find a list of the US States in a form for importing into my database?
SQL would be ideal, otherwise CSV or some other flat file format is fine.
Edit: Complete with the two letter state codes | I needed this a few weeks ago and put it on my blog as SQL and Tab Delimited. The data was sourced from wikipedia in early January so should be up to date.
US States: <http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-us-states/>
I use the Worlds Simplest Code Generator if I need to add columns or remove some of the fields - <http://secretgeek.net/wscg.asp>
I've also done Countries of the world and International Dialling Codes too.
Countries: <http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-countries/>
IDC's: <http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-international-dialling-codes-idcs/>
Edit: New: [Towns and cities of New Zealand](http://www.john.geek.nz/index.php/2009/01/sql-tips-list-of-new-zealand-towns-and-cities/) | Depending on why you need the states, it is worth keeping in mind that there are more than 50 valid state codes. For someone deployed outside the USA, it is annoying to come across websites that do not allow address entry with perfectly valid state codes like AE and AP. A better resource would be [USPS](https://www.usps.com/send/official-abbreviations.htm). | Is there a publicly available list of the US States in machine readable form? | [
"",
"sql",
"csv",
"list",
"lookup",
""
] |
In the application, when special types of objects are created, I need to generate a unique-id for each of them. The objects are created thro' a factory and have a high possibility of being created in a 'bulk' operation. I realize that the "Random" from the framework is not so 'random' after all, so I tried appending the time-stamp as follows:
```
private string GenerateUniqueId()
{
Random randomValue = new Random();
return DateTime.Now.Ticks.ToString() + randomValue.Next().ToString();
}
```
Unfortunately, even this does not work. For objects that are created in rapid succession, I generate the same Unique Id :-(
Currently, I am implementing it in a crude way as follows:
```
private string GenerateUniqueId()
{
Random randomValue = new Random();
int value = randomValue.Next();
Debug.WriteLine(value.ToString());
Thread.Sleep(100);
return DateTime.Now.Ticks.ToString() + value.ToString();
}
```
Since this is not a very large application, I think a simple and quick technique would suffice instead of implementing an elaborate algorithm.
Please suggest. | A [GUID](http://msdn.microsoft.com/en-us/library/system.guid.aspx) is probably what you're looking for:
```
private string GenerateUniqueId()
{
return Guid.NewGuid().ToString("N");
}
```
If you want a smaller, more manageable ID then you could use something like this:
```
private string GenerateUniqueId()
{
using (var rng = new RNGCryptoServiceProvider())
{
// change the size of the array depending on your requirements
var rndBytes = new byte[8];
rng.GetBytes(rndBytes);
return BitConverter.ToString(rndBytes).Replace("-", "");
}
}
```
Note: This will only give you a 64-bit number in comparison to the GUID's 128 bits, so there'll be more chance of a collision. Probably not an issue in the real world though. If it is an issue then you could increase the size of the `byte` array to generate a larger id. | Assuming you do not want a GUID, First option would be a static field, and interlocked:
```
private static long lastId = 0
private static long GetNextId() {
return Interlocked.Increment(ref lastId);
}
```
If you want something based on time ticks, remember the last value and if the same manually increment and save; otherwise just save:
```
private static long lastTick = 0;
private static object idGenLock = new Object();
private static long GetNextId() {
lock (idGenLock) {
long tick = DateTime.UtcNow.Ticks;
if (lastTick == tick) {
tick = lastTick+1;
}
lastTick = tick;
return tick;
}
}
```
(Neither of these approaches will be good with multiple processes.) | Alternate UniqueId generation technique | [
"",
"c#",
".net",
"algorithm",
""
] |
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:
**foo.py:**
```
def f():
print __name__
```
**bar.py:**
```
from foo import f
def b(): f()
```
This obviously does not work as `__name__` is the name of the module that contains the function. What I would like to be access inside the `foo` module is the name of the current executing module that is using `foo`. So in the case above it would be `bar` but if any other module imported `foo` I would like `foo` to dynamically have access to the name of that module.
**Edit:** The `inspect` module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.
**Edit:** Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "`/home/hare/app_logs`". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under `app_logs` that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.
In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist. | From the comment -- not the question.
> I am simply curious to see if what I am trying to do is possible.
The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion.
Since the answer is always "yes", your question is ill-formed. The real question is "what's a good way to have my logging module know the name of the client?" or something like that.
The answer is "Accept it as a parameter." Don't mess around with inspecting or looking for mysterious globals or other tricks.
Just follow the design pattern of `logging.getLogger()` and use explicitly-named loggers. A common idiom is the following
```
logger= logging.getLogger( __name__ )
```
That handles almost all log naming perfectly. | This should work for referencing the current module:
```
import sys
sys.modules[__name__]
``` | How can I access the current executing module or class name in Python? | [
"",
"python",
"module",
""
] |
Given a table of items, a table of tags and a join table between them, what is a good and efficient way to implement queries of the form:
`p1 AND p2 AND ... AND pn AND NOT n1 AND NOT n2 ... AND NOT nk`
I am using SQL. So to find all items that match all tags p1...pn and none of n1...nk?
Is there a good "standard" solution for this? | Difficult to say without knowing your schema, but something like this would work:
```
select article_id from articles
inner join tag t1 on t1.article_id=articles.article_id and t1.tag='included_tag'
inner join tag t2 on t2.article_id=articles.article_id and t2.tag='another_included_tag'
left outer join tag t3 on t3.article_id=articles.article_id and t3.tag='dont_include_tag'
left outer join tag t4 on t4.article_id=articles.article_id and t4.tag='also_dont_include_tag'
where t3.tag_id is null and t4.tag_id is null
```
inner join to tags that are to be included, and do an anti-join (outer join + where a required column is null) to tags that are not to be included | I think this is what you're looking for:
```
SELECT * FROM TABLE_NAME WHERE COLUMN1 IN ('value1','value2','value3') AND COLUMN1 NOT IN ('value4','value5','value6')
```
If not, let me know. I may have misunderstood your question. | How can I implement a boolean tag search in SQL? | [
"",
"sql",
"database",
"search",
"tags",
""
] |
What's the preferred container type when returning multiple objects of the same type from a function?
Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?
Thanks! | Eric Lippert has a good [article](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx) on this. In case you can't be bothered to read the entire article, the answer is: return the interface. | Return an `IEnumerable<T>` using a [`yield return`](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx). | Should I return an array or a collection from a function? | [
"",
"c#",
".net",
"return-type",
""
] |
Simple question: are the following statements equivalent? or is the second one doing more implicit things behind the scenes (if so, what?)
```
myClass x(3);
myClass x = myClass(3);
```
Thanks! | They are not completely identical. The first is called "direct initialization" while the second is called "copy initialization".
Now, the Standard makes up two rules. The first is for direct initialization and for copy initialization where the initializer is of the type of the initialized object. The second rule is for copy initialization in other cases.
So, from that point of view both are termed in one - the first - rule. In the case where you have copy initialization with the same type, the compiler is allowed to elide a copy, so it can construct the temporary you create directly into the initialized object. So you can end up very well with the same code generated. But the copy constructor, even if the copy is elided (optimized out), must still be available. I.e if you have a private copy constructor, that code is invalid if the code in which it appears has no access to it.
The second is called copy-initialization, because if the type of the initializer is of a different type, a temporary object is created in trying to implicitly convert the right side to the left side:
```
myclass c = 3;
```
The compiler creates a temporary object of the type of myclass then when there is a constructor that takes an int. Then it initializes the object with that temporary. Also in this case, the temporary created can be created directly in the initialized object. You can follow these steps by printing messages in constructors / destructors of your class and using the option `-fno-elide-constructors` for GCC. It does not try to elide copies then.
On a side-note, that code above has nothing to do with an assignment operator. In both cases, what happens is an initialization. | The second one may or may not call for an extra `myclass` object construction if copy elision is not implemented by your compiler. However, most constructors, have copy elision turned on by default even without any optimization switch.
**Note** initialization while construction never ever calls the assignment operator.
Always, keep in mind:
> **assignment:** an already present object gets a new value
>
> **initialization:** a new object gets a value at the moment it is born. | C++ constructor syntax | [
"",
"c++",
"constructor",
""
] |
I've got a bit of a problem. I'm moving my source repository from one machine to another, and in the process I'm doing some culling of what's stored as I've learned more about creating/managing a repository since I started.
The problem is that we're using dxperience tools from devexpress and it uses the .net license system (licenses.licx). Originally I had this license in the repository, and [I'm hearing](https://stackoverflow.com/questions/51363/how-does-the-licenses-licx-based-net-component-licensing-model-work) that this isn't necessarily the best idea. So I haven't included it in the repository. But now, when I checkout the project from the repository on my machine (same machine that I was checking out to before the move), it's looking for the license file and not generating it as (I think) it should be. | We have run into the same problem using Infragistics controls.
Our solution has been to keep a blank licnenses.licx file in our source repository (Source Gear Vault) and then change the properties of the file to Read Only false on our local workations. This way we do not end up stepping on each other with that file and it is generated with the proper keys off of our workstations.
Of course this is a bit of a manual work around that may not be suitable for you, but that is how we have been doing it. | Alternatively, you can install the [EmptyLicensesLicx](https://github.com/caioproiete/EmptyLicensesLicx) nuget package, and it will make sure there's an empty `Licenses.licx` in your project, before it gets compiled (which is all you need). | generating licenses.licx | [
"",
"c#",
"visual-studio-2008",
"licensing",
"licenses.licx",
"emptylicenseslicx",
""
] |
I have a ListView whereby I want to display one context menu if an item is right-clicked, and another if the click occurs in the ListView control. The problem I'm getting is the MouseClick event is only firing when an item is right-clicked, not the control. What's causing this and how can I get around it? | You could subclass the ListView to add a right-click event:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace MyCustomControls
{
public delegate void MyDelegate(Object sender, EventArgs e);
class MyListView : ListView
{
private static readonly object EventRightClickRaised = new object();
public MyListView()
{
//RightClick += new MyDelegate(OnRightClick);
}
public event EventHandler RightClick
{
add
{
Events.AddHandler(EventRightClickRaised, value);
}
remove
{
Events.RemoveHandler(EventRightClickRaised, value);
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
OnRightClick(EventArgs.Empty);
}
base.OnMouseUp(e);
}
protected void OnRightClick(EventArgs e)
{
EventHandler RightClickRaised = (EventHandler)Events[EventRightClickRaised];
if (RightClickRaised != null)
{
RightClickRaised(this, e);
}
}
}
}
``` | Use MouseUp instead of MouseClick! Sorry about that. Should have googled harder. | ListView MouseClick Event | [
"",
"c#",
"listview",
""
] |
My TextBox won't update! I am using it as a Log to update what other things are doing...
**Form 1 code:**
```
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.OleDb;
using System.Collections.Specialized;
using System.Text;
delegate void logAdd(string message);
namespace LCR_ShepherdStaffupdater_1._0
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
public void logAdd(string message)
{
this.Log.Items.Add(message); // Doesnt add to textbox
this.Log.Items.Add("This won't update the textbox!!! Why?"); // Doesnt add to textbox
}
private void exitProgramToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
Form aboutBox = new AboutBox1();
aboutBox.ShowDialog();
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void settingsToolStripMenuItem1_Click(object sender, EventArgs e)
{
settingsForm.settings.ShowDialog();
}
private void synchronize_Click(object sender, EventArgs e)
{
this.Log.Items.Add("This WILL update the textbox. It is exactly the same as the other one..."); // This will add to the textbox
DatabaseHandling.createDataSet();
}
}
public class settingsForm
{
public static Form settings = new Settings();
}
}
```
**My Logging Class code:**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LCR_ShepherdStaffupdater_1._0
{
public class Logging
{
static Main mainClass = new Main();
static logAdd logAddDelegate;
public static void updateLog(string message)
{
logAddDelegate = mainClass.logAdd;
logAddDelegate(message);
}
}
}
```
I am just completely stumped....does anyone know how I can fix the logAdd function so I can get my textbox log to finally update?
**EDIT:**
I finally got it to work, here was the fix:
**Form1 Code**
```
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.OleDb;
using System.Collections.Specialized;
using System.Text;
delegate void logAdd(string message);
namespace LCR_ShepherdStaffupdater_1._0
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
public void add(string message)
{
this.Log.Items.Add(message);
}
public void logAdd(string message)
{
Log.Invoke(new logAdd(add), new object[] { message });
}
private void exitProgramToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
Form aboutBox = new AboutBox1();
aboutBox.ShowDialog();
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void settingsToolStripMenuItem1_Click(object sender, EventArgs e)
{
settingsForm.settings.ShowDialog();
}
private void synchronize_Click(object sender, EventArgs e)
{
logAdd("this works");
}
}
public class settingsForm
{
public static Form settings = new Settings();
}
}
```
**Logging Code:**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LCR_ShepherdStaffupdater_1._0
{
public class Logging
{
static Main mainClass = new Main();
static logAdd logAddDelegate;
public static void updateLog(string message)
{
logAddDelegate = mainClass.logAdd;
logAddDelegate(message);
}
}
}
```
Well...I can tell that is a really bad way to do it...but until I find a true fix as long as it works im happy. Thanks for the help guys! | What thread are you calling `Logging.updateLog()` from? If it's not the UI thread, I could see that the TextBox wouldn't get updated in that case. If you try calling `logAdd()` from `synchronize_Click()` (assuming that this is called from the UI thread based on the name), does it work then? | From the code you posted your static Logger class is creating a new instance of the Main form. which is different than the one your running on the UI.
Overall this isn't a very good design pattern. write a comment if you want me to elaborate and give a sample. | Why won't my textbox update when I am doing the exact same thing just with a different function? | [
"",
"c#",
"multithreading",
"class",
"delegates",
"invoke",
""
] |
Can't exactly find a way on how to do the following in C/C++.
Input : hexdecimal values, for example: ffffffffff...
I've tried the following code in order to read the input :
```
uint16_t twoBytes;
scanf("%x",&twoBytes);
```
Thats works fine and all, but how do I split the 2bytes in 1bytes `uint8_t` values (or maybe even read the first byte only). Would like to read the first byte from the input, and store it in a byte matrix in a position of choosing.
```
uint8_t matrix[50][50]
```
Since I'm not very skilled in formating / reading from input in C/C++ (and have only used scanf so far) any other ideas on how to do this easily (and fast if it goes) is greatly appreciated .
Edit: Found even a better method by using the fread function as it lets one specify how many bytes it should read from the stream (stdin in this case) and save to a variable/array.
```
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
```
Parameters
ptr - Pointer to a block of memory with a minimum size of (size\*count) bytes.
size - Size in bytes of each element to be read.
count - Number of elements, each one with a size of size bytes.
stream - Pointer to a FILE object that specifies an input stream.
[cplusplus ref](http://www.cplusplus.com/reference/clibrary/cstdio/fread.html) | `%x` reads an `unsigned int`, not a `uint16_t` (thought they may be the same on your particular platform).
To read only one byte, try this:
```
uint32_t byteTmp;
scanf("%2x", &byteTmp);
uint8_t byte = byteTmp;
```
This reads an `unsigned int`, but stops after reading two characters (two hex characters equals eight bits, or one byte). | You should be able to split the variable like this:
```
uint8_t LowerByte=twoBytes & 256;
uint8_t HigherByte=twoBytes >> 8;
``` | C/C++ read a byte from an hexinput from stdin | [
"",
"c++",
"byte",
"stdin",
"scanf",
""
] |
I have a working WinForm that handles the search functionality in my customer database. It contains the following controls:
* A textBox where you type your search string (A)
* A "search" button (B)
* A DataGridView (C) that returns the result of the search
* An "OK" button (D) and a "Cancel" button (E)
What I am trying to accieve next is this:
1. When A is active the AcceptButton (enter) should be linked to B
2. When B or enter is pressed C should become active
3. When C is active the AcceptButton should be linked to D
I realise this is a somewhat big question so don't hesitate to answer just one of the bullet marks if you know the answer.
EDIT: I have solved the implementation of requirement 1 and 3 above, but I am still looking for an answer to the second one. To clarify, when the search is initiated (meaning i have pressed enter on the keyboard or the search button with the mouse) I want focus to shift to the first line in the DataGridView. | When you get the text changed event for textBox set the AcceptButton to be "Search":
```
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = SearchButton;
}
```
There will probably want to be more code in here, checking the length of the string etc.
Then once you've done the search and filled in the DataGridView you can then set the AcceptButton to be "OK".
```
private void dataGridView1_DataMemberChanged(object sender, EventArgs e)
{
this.AcceptButton = OKButton;
}
```
Though you probably wouldn't want to use this event.
"Cancel" is always the CancelButton.
EDIT: OK for part 2 you want the following code:
```
private void SearchButton_Click(object sender, EventArgs e)
{
dataGridView1.Focus();
}
```
This will make it active as soon as the search button is pressed, but you probably want to do it when the DataGridView has been populated - just in case the search returned no results. | Setup handlers to track the `Control.Enter` event for the particular controls. When the enter is reached try:
```
this.AcceptButton = ControlThatShouldBeAcceptButton;
``` | Changing the AcceptButton depending on active control | [
"",
"c#",
".net",
"winforms",
"visual-studio-2008",
""
] |
I have a Java program where I have a JMenu with an arbitrary number of items (in this case, there is one menu item for each dynamic library currently loaded in a different program). I'm running a loop to add JCheckBoxMenuItem s to the menu, since I don't know how many there will be.
How can I set up an action listener for these menu items that is aware of which option called it? Specifically, I want to run the same function but with a different set or parameters for each of the menu items (and a different function again depending on whether the check is being toggled or detoggled).
Could someone point me in the right direction? | While event.getSource() will definitely let you know which particular button the event came from it has the side effect of needing to track the generated buttons or snooping into the button. Also you may want to present a different name of the library to the user (possibly including the version information) than is used to identify the library. Using the "ActionCommand" property of the button may provide a way to separate those issues. So you will need to alter code in the generation of the checkbox menu items and in the listener.
```
ActionListener actionListener = ... // whatever object holds the method, possibly this
String[] libraries = ... // however you get your library names
JMenu parentMenu = ... // the menu you are adding them to
for (String s : libraries) {
// prettyName is a method to make a pretty name, perhaps trimming off
// the leading path
JCheckBoxMenuItem child = new JCheckBoxMenuItem(prettyName(s), true);
child.setActionCommand(s);
parentMenu.acc(child);
}
```
The action handler code would be...
```
public void actionPerformed(ActionEvent evt) {
// the 'current' selection state, i.e. what it is going to be after the event
boolean selected = ((JCheckBoxMenuItem)evt.getSource()).isSelected();
String library = evt.getActionCommand();
... process based on library and state here...
}
``` | Definitely read over this: <http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html>
In short, add ActionListener to the menuItems. In the actionPerformed method, use event.getSource(). You can add the SAME ActionListener to all your menu items if you want. | How can I determine which menu item called an ActionListener? | [
"",
"java",
"swing",
"events",
"menu",
"menuitem",
""
] |
I have a java project that is composed of 3 sub projects that generate a .jar artifact each (and have sub-dependencies among them).
In addition there is a web projects that depends on the first 3 projects and generate a war file. The war file is my final artifact, i.e. what I ship my customers.
Additionally I have a parent module that encompasses all the other projects:
```
<modules>
<module>../core</module>
<module>../commons</module>
<module>../api</module>
<module>../web</module>
</modules>
```
I generate eclipse files (mvn eclipse:eclipse) and work with eclipse. The problem is if I modify one of the non-web projects I must manually install it before deploying the web project to my web container. How can I make that the web project depends directly on the source code of the others and not on the version installed in the repository. | In your web application properties (right clic on the project in the Package explorer, then "properties"), add the three modules (core, commons and api) in the "J2EE Module Dependencies" (the others modules must be opened in the Eclipse workspace). | Do you want to add a dependency on the source jars deployed to the repository?
If so you can do it by adding the *sources* classifier to the dependency. See [this answer](https://stackoverflow.com/questions/1191336/how-to-check-and-access-javadoc-source-for-maven-artifacts/1193313#1193313) for more details.
If not, can you clarify further please. | How do I implement maven source dependency among sibling projects? | [
"",
"java",
"maven-2",
"dependencies",
""
] |
I am running a java program from within a Bash script.
If the java program throws an unchecked exception, I want to stop the bash script rather than the script continuing execution of the next command.
How to do this? My script looks something like the following:
```
#!/bin/bash
javac *.java
java -ea HelloWorld > HelloWorld.txt
mv HelloWorld.txt ./HelloWorldDir
``` | Catch the exception and then call System.exit. Check the return code in the shell script. | In agreement with Tom Hawtin,
To check the exit code of the Java program, within the Bash script:
```
#!/bin/bash
javac *.java
java -ea HelloWorld > HelloWorld.txt
exitValue=$?
if [ $exitValue != 0 ]
then
exit $exitValue
fi
mv HelloWorld.txt ./HelloWorldDir
``` | Stop bash script if unchecked Java Exception is thrown | [
"",
"java",
"bash",
"exception",
""
] |
The app was working fine but now a few weeks later when the new version begun testing, it crashes. Tried it on five of the workstations, it crashes only on two of them. And the only common about them I can find is that those two have Windows installed with English language.
Its a DirectX 8.1 application, written in C++ with Visual Studio 2005. SP2 is installed on all machines.
I have no clue about what could cause this. Surely, the language can't cause an DX app to crash? I'm going to look for more common elements but I just wanted to ask if anyone have seen this before? If the language really is the problem. And how to solve it.
**Edit**: The actual error message is
```
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix the problem.
```
At first we thought it was the Visual Studio Redistributable, but no luck. Something is missing, and I need to figure out what. | Problem solved. And as a note to others having the same problem, I found the answer in this [question](https://stackoverflow.com/questions/265481/application-has-failed-to-start-application-configuration-is-incorrect-vc). We installed the VS2005 CRT alright, but not the SP1 one.
**Edit**: Although, I still have no idea why this only affected the english workstations. Maybe it was a coincidence after all. | Make sure you don't compare string messages when checking for errors. I've seen errors like this in a code that was searching for 'refused' in socket error messages, failing on non-english machines. | Unexplainable crash in DirectX app in Windows XP that uses English language | [
"",
"c++",
"windows-xp",
"directx",
""
] |
So, (seemingly) out of the blue, my project starts getting compiler warning 1685:
> The predefined type
> 'System.Runtime.CompilerServices.ExtensionAttribute'
> is defined in multiple assemblies in
> the global alias; using definition
> from 'c:\Program Files\Reference
> Assemblies\Microsoft\Framework\v3.5\System.Core.dll'
Perplexed, I researched the MSDN article to figure out its cause. Here's the information I found:
> Visual C# Reference: Errors and
> Warnings Compiler Warning (level 1)
> CS1685
>
> Error Message The predefined type
> 'System.type name' is defined in
> multiple assemblies in the global
> alias; using definition from 'File
> Name'
>
> This error occurs when a predefined
> system type such as System.int32 is
> found in two assemblies. One way this
> can happen is if you are referencing
> mscorlib from two different places,
> such as trying to run the.Net
> Framework versions 1.0 and 1.1
> side-by-side.
>
> The compiler will use the definition
> from only one of the assemblies. The
> compiler searches only global aliases,
> does not search libraries defined
> /reference. If you have specified
> /nostdlib, the compiler will search
> for Object, and in the future start
> all searches for predefined types in
> the file where it found Object.
Now I'm really scratching my head.
1. I'm not running two different
versions of the .NET Framework
(unless you count 2.0 and 3.5).
2. I'm not referencing any bizarre
assemblies that might make me
suspicious.
3. I don't recall making any changes to my application that would spur this change.
4. I've verified that all components target .NET Framework version v2.0.50727.
I'm open to suggestions, or ideas on how to correct this. I treat warnings as errors, and it's driving me crazy.
What really bugs me about it is that I don't know *why* it's occurring. Things that happen should have a discernable cause, and I should know why they happened. If I can't explain it, I can't accurately remedy it. Guesswork is never satisfactory.
The application is straightforward, consisting of a class library, and a windows forms application.
* A C# class library DLL providing basic functionality encapsulating database access. This DLL references the following components:
+ System
+ System.Core
+ System.Core.Data
+ System.Data
+ System.Data.DataSetExtensions
+ System.Data.OracleClient
+ System.Drawing
+ System.Windows.Forms
+ System.Xml
+ System.Xml.Linq
* A C# Windows Forms application providing the UI. This application references the following components:
+ CleanCode
+ CleanCodeControls (both of these provide syntax editor support, and are locally built against .NET 3.5).
+ LinqBridge
+ Roswell.Framework (the class library above)
+ System
+ System.Core
+ System.Data
+ System.Data.DataSetExtensions
+ System.Data.OracleClient
+ System.Deployment
+ System.Design
+ System.Drawing
+ System.Windows.Forms
+ System.Xml
+ System.Xml.Linq
Let me know if you need further information and I'll gladly provide it. | LINQBridge makes me immediately suspicious. The entire intent of this is to provide extension attribute/methods etc for 2.0 users. If you have 3.5 (System.Core.dll), don't use LINQBridge. If you *do* need LINQBridge in 3.5 for some obscure reason (and I can't think of one), then you might have to use an extern alias. But I **really** doubt you need it! | Another easy way to verify:
In your code, temporarily use the class somewhere.
Example:
```
System.Runtime.CompilerServices.ExtensionAttribute x = null;
```
When building, this will generate error:
> The type 'System.Runtime.CompilerServices.ExtensionAttribute' exists
> in both 'c:\Program Files\Reference
> Assemblies\Microsoft\Framework\v3.5\System.Core.dll' and .....
And show you immediately the 2 sources causing the conflict. | C# Compiler Warning 1685 | [
"",
"c#",
".net",
"compiler-warnings",
""
] |
I'm trying to create an array of arrays that will be using repeated data, something like below:
```
int[] list1 = new int[4] { 1, 2, 3, 4 };
int[] list2 = new int[4] { 5, 6, 7, 8 };
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4, 4] { list1 , list2 , list3 , list4 };
```
I can't get it to work and so I'm wondering if I'm approaching this wrong.
What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,
```
int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};
for (int i = 0; i < 90; ++i) {
doStuff(lists[i]);
}
```
and have the arrays passed to `doStuff()` in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays? | What you need to do is this:
```
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[][] lists = new int[][] { list1 , list2 , list3 , list4 };
```
Another alternative would be to create a `List<int[]>` type:
```
List<int[]> data=new List<int[]>(){list1,list2,list3,list4};
``` | The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
```
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
```
You could also do
```
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
``` | C# Creating an array of arrays | [
"",
"c#",
"arrays",
""
] |
Perhaps I'm just unaware of the competitors, but it seems when it comes to client-side scripting in the browser and DOM, Javascript is it. I know there's VBScript, but it really isn't even in the same ballpark as JS (not even cross platform, for starters).
I'm just curious about how this came to be. Surely there would be a general desire for a new language to replace Javascript: built from scratch to do all the things Javascript has been bent and moulded into these days (look at the reliance on JS Libraries). | Momentum. JavaScript has been around for 15 or so years, and browser manufacturers have worked for 15 or so years to make it work in their browsers.
If a competitor came along, it would need to really bring something new to the table in order to convince everyone to a) adopt it, b) live with locking out all the users of older browsers like IE7, Firefox 3.0, Chrome 1.0 etc. and c) find replacements for all existing libraries like jQuery, prototype, extJS etc.
In short: we don't need another Standard, let's rather improve JavaScript and build on the rich foundation that already exists instead of starting back from stone age again. | There is! Ones that spring to mind are Flash, ActiveX, and Java... But these all have their drawbacks. Mainly security and integration with the browser/DOM.
Flash and Java live in their own little world, by design (and to address security issues). They can't alter the HTML around them. ActiveX has access to the DOM, but also everything else on your computer.
JavaScript seems to have found a nice balance between flexibility and security, it can trivially interact and alter the pages HTML/CSS, do "safe" networking, has a decent standard library (which has things like JSON, XmlHttpRequest'sih networking, DOM manipulation, and so on). Most importantly, it's available in basically all vaguely-modern browsers, on all platforms, in a consistent manner (compared to CSS)
There are problems with JavaScript, but nothing major. The biggest is the performance. Load a comment page on Digg and watch your CPU usage. Chance are it will be 100% of one CPU core. There are projects to improve this, like [SquirrelFish](http://webkit.org/blog/189/announcing-squirrelfish/), [TraceMonkey](https://wiki.mozilla.org/JavaScript:TraceMonkey), and other strangely named things. But the performance is adequate to do some extremely impressive things (Google Spreadsheet, for example).
Basically, JavaScript is great, and it's drawbacks aren't nearly as big as the other competitors. | Why are there no real competitors to Javascript? | [
"",
"javascript",
""
] |
This is sort of a follow-up to my question here:
[Asp:Label is not shown when visible is set to true?](https://stackoverflow.com/questions/534045/asplabel-is-not-shown-when-visible-is-set-to-true)
In the above question, I had a few controls where the visibility was not being set to false because they were not in an `UpdatePanel`. Once I put the controls inside an `UpdatePanel`, the toggling of visibility worked, but this has caused me another problem. I have an `ImageButton` that exports to excel. When the button was not in an `UpdatePanel`, the click event fired, but now that I put it inside an `UpdatePanel`, the click event does not fire.
I also have a dropdown which works fine. I am thinking it has something to do with the fact that the `ImageButton` does not have an `AutoPostBack` property. | Make sure that you have associated the Image Button to a PostBackTrigger on the UpdatePanel. If you are exporting to Excel using something similar to [Matt Berseth's method](http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html), you have to have this trigger for the export to work.
```
<asp:PostBackTrigger ControlID="ImageButton1"/>
``` | I had the similar problem. In my case, `ImageButtons` are inside a repeater which is bound to a `updatepanel`. But I used `Page.RegisterRequiresRaiseEvent(ImageButton)` in the code behind within `ItemDataBound` method of the repeater and it worked. | ImageButton event not firing inside Update Panel | [
"",
"c#",
"asp.net",
"updatepanel",
""
] |
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:
> ```
> Binary Build date: 03/03/2009 @ 10:00AM
> ```
I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.
Is there a simple way to do this using Visual Studio 2008 in C++. Thanks. | Use preprocessor's `__DATE__` and `__TIME__`.
```
printf("Binary build date: %s @ %s\n", __DATE__, __TIME__);
```
For making sure that cpp file that contains this code is really compiled, I use touch-utility for file as a pre-build step: touch file.cpp
Touch.bat:
```
@copy nul: /b +%1 tmp.$$$
@move tmp.$$$ %1
``` | You can use the macros `__TIME__` and `__DATE__`. Note the double underscores. These are unrolled at compile time and hence you will get the last compile time saved in your file(s). | Print Date and Time In Visual Studio C++ build? | [
"",
"c++",
"visual-studio",
"datetime",
"compiler-construction",
""
] |
I want to learn C++ GUI programming using Visual Studio 2008. I'm not sure where to start though. I learned C++ in high school, but not GUI. I've been doing C# for about 3 years now and thats how I "learned" GUI programming. Now I want to learn how to write GUI's without the use of the .NET framework, so where do I start? | MFC is almost outdated now. I would recommend to use WTL instead .
Well it is also not a good idea just to start programming for GUI in C++ when there are so many good frameworks available like QT cross platform framework. | Charles Petzold's "Programming Windows 5th Edition" is the Bible for Windows programming.
<http://www.charlespetzold.com/pw5/> | Windows GUI C++ Programming | [
"",
"c++",
"user-interface",
"visual-c++",
""
] |
When you long press on something in Android, a context menu comes up. I want to add something to this context menu for all `TextViews` in the system.
For example, the system does this with Copy and Paste. I would want to add my own, and have it appear in every application. | Currently Android does not support this, you cannot override or hook functionality globally at the system level without the particular activity implementing an intent or activity that you expose. Even in the case of publishing an intent it wouldn't matter unless the application running is a consumer... and all the base system applications and obviously all applications prior to yours would not be without updating the app to consume.
Basically as it stands, this is not possible.
What exactly are you trying to accomplish with this global context menu, some sort of global "Search For" or "Send To" functionality that runs through your application? | Add intent-filter in your file android-manifest.xml:
```
<activity
android:name=".ProcessTextActivity"
android:label="@string/process_text_action_name">
<intent-filter>
<action android:name="android.intent.action.PROCESS_TEXT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
```
Get highlighted by user text in activity your app in method onCreate():
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.process_text_main);
CharSequence text = getIntent()
.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT);
// process the text
}
```
More information in the article on [medium](https://medium.com/androiddevelopers/custom-text-selection-actions-with-action-process-text-191f792d2999).
Thanks for user: [YungBlade](https://ru.stackoverflow.com/users/195759/yungblade)
His answer on [ru.stackoverflow.com](https://ru.stackoverflow.com/a/927864/238266) | Android add item to global context menu | [
"",
"java",
"android",
"menu",
"contextmenu",
""
] |
We are looking for an ASP.NET compatible data grid that allows for multi-line editing similar to Excel or a WinForms data grid. It must also support very basic keyboard input (tab, arrow keys, return). Note that we are **not** looking for Excel capabilities (functions, formatting, formulas) ... just a grid for fast data entry.
I've looked at Telerik, Infragistics, ComponentOne, DevExpress, and many others ... all their support teams have said that the controls either do not support multi-line, or do so in such a clunky way that it would be unusable.
Has anyone used any Excel-like grids that they can recommend? The client-side grids seemed closer to what we needed, with Sigma Widgets ( [example](http://www.sigmawidgets.com/products/sigma_grid2/demos/example_column_editor.html) ) being the closest I've found so far. Extjs's grid was too inflexible, and the jQuery grid was too buggy. | We ended up using [Sigma Grid](http://www.sigmawidgets.com/) ... thanks for all the other replies! | It does not exist today. There are products such as those you have mentioned which have tried, but in my experience none of them will make an experienced Excel user happy.
My company makes Excel compatible spreadsheet components for use with Windows Forms and ASP.NET. We have been getting this question for years, so we have of course considered building one because it looks like a good business. But HTML / JavaScript is just not a suitable platform for building something which "feels right" to users who want it to work like Excel - IMO.
We have settled on the idea of building a spreadsheet control for Silverlight. I believe this will give you the best of both worlds - cross platform rich interactive spreadsheet in the browser which any Excel user would be comfortable with. Unfortunately, that is not going to happen this month or next...
At my previous company, we actually built a spreadsheet component as a Netscape Plugin, as an ActiveX control and as a Java Applet. They had a little bit of success, but none of these technologies ever became ubiquitous in the enterprise for various reasons. I believe Microsoft is finally getting it right with Silverlight and that Silverlight will become the gold standard for browser based Line of Business applications in the Enterprise.
EDIT:
I should have mentioned that the product I alluded to above is Formula One / NET (Netscape Plugin released ~1995), Formula One / ActiveX and Formula One for Java - which is now sold by Actuate as e.Spreadsheet. I left in 2002, but AFAIK they still maintain the Java Applet which is probably the best example of an Excel like UI in the browser (I have no interest in the product any more - in fact we compete to some extent with e.Spreadsheet and intend to have a better answer with a Silverlight control in the future). I did not mention it by name in my original answer because it is a Java product - not a .NET product - but it is a potential answer even for an ASP.NET web site.
Lloyd Cotten correctly comments that Google Docs is an example of a spreadsheet built with HTML / JavaScript. Lloyd says Google Docs "definitely 'feels right' in its similarity to Excel". While I respect Lloyd's opinion, in my experience Google Docs does not 'feel right'. Perhaps this is because I'm a spreadsheet guy. I do know that we talk to potential customers almost every day who are trying to solve the problem of the OP, and they have all looked and cannot find one they are happy with - but of course they would not be calling us if they had so we are dealing with a biased sample and I understand that.
So I just want to clarify that there are in fact plenty of examples of HTML / JavaScript grids and spreadsheets which are usable. It's just that I don't want to have to use them because I expect certain keys to do certain things and a particular level of responsiveness which is just not there today with any of the HTML / JavaScript solutions I have tried (and I look at them regularly because my company could definitely sell such a product if it were feasible to build one that we could be proud of). | Good ASP.NET excel-like Grid control? | [
"",
"asp.net",
"javascript",
"grid",
""
] |
> `va_end` - Macro to reset `arg_ptr`.
After accessing a variable argument list, the `arg_ptr` pointer is usually reset with `va_end()`. I understand that it is required if you want to re-iterate the list, but is it really needed if you aren't going to? Is it just good practice, like the rule "always have a `default:` in your `switch`"? | `va_end` is used to do cleanup. You don't want to smash the stack, do you?
From `man va_start`:
> va\_end()
>
> Each invocation of va\_start() must be matched by a corresponding invocation of va\_end() in the same function. After the call va\_end(ap) the variable ap is undefined. Multiple traversals of the list, each bracketed by va\_start() and va\_end() are possible. va\_end() may be a macro or a function.
Note the presence of the word **must**.
The stack could become corrupted because *you don't know what `va_start()` is doing*. The `va_*` macros are meant to be treated as black boxes. Every compiler on every platform can do whatever it wants there. It may do nothing, or it may do a lot.
Some ABIs pass the first few args in registers, and the remainder on the stack. A `va_arg()` there may be more complicated. You can look up how a given implementation does varargs, which may be interesting, but in writing portable code you should treat them as opaque operations. | On Linux x86-64 only one traversal can be done over a `va_list` variable. To do more traversals it has to be copied using `va_copy` first. `man va_copy` explains the details:
> va\_copy()
>
> An obvious implementation would have a va\_list be a pointer to the
> stack frame of the variadic function. In such a setup (by far the most
> common) there seems nothing against an assignment
>
> ```
> va_list aq = ap;
> ```
>
> Unfortunately, there are also systems that make it an array of pointers
> (of length 1), and there one needs
>
> ```
> va_list aq;
> *aq = *ap;
> ```
>
> Finally, on systems where arguments are passed in registers, it may be
> necessary for va\_start() to allocate memory, store the arguments there,
> and also an indication of which argument is next, so that va\_arg() can
> step through the list. Now va\_end() can free the allocated memory
> again. To accommodate this situation, C99 adds a macro va\_copy(), so
> that the above assignment can be replaced by
>
> ```
> va_list aq;
> va_copy(aq, ap);
> ...
> va_end(aq);
> ```
>
> Each invocation of va\_copy() must be matched by a corresponding invoca‐
> tion of va\_end() in the same function. Some systems that do not supply
> va\_copy() have \_\_va\_copy instead, since that was the name used in the
> draft proposal. | What exactly is va_end for? Is it always necessary to call it? | [
"",
"c++",
"c",
"variadic-functions",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.