Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am introducing automated integration testing to a mature application that until now has only been manually tested.
The app is Windows based and talks to a MySQL database.
What is the best way (including details of any tools recommended) to keep tests independent of each other in terms of the database transactions t... | How are you verifying the results?
If you need to query the DB (and it sounds like you probably do) for results then I agree with Kris K, except I would endeavor to rebuild the DB after every test case, not just every suite.
This helps avoid dangerous [interacting tests](http://xunitpatterns.com/Erratic%20Test.html)
... | You can dump/restore the database for each test suite, etc. Since you are automating this, it may be something in the setup/teardown functionality. | Automated integration testing a C++ app with a database | [
"",
"c++",
"database",
"automated-tests",
"integration-testing",
""
] |
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python an... | ```
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
``` | Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.
But more directly to the point, if you throw an exception, you're forcing t... | What's the best way to return multiple values from a function? | [
"",
"python",
"variables",
"return",
""
] |
While answering [Static class variables in Python](https://stackoverflow.com/questions/68645/python-static-variable#81002)
I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?
```
PythonWin 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 199... | My guess is as follows. The PythonWin editor offers autocomplete for an object, i.e. when you type `myobject.` it offers a little popup of all the availble method names. So I think when you type `X().` it's creating an instance of `X` in the background and doing a `dir` or similar to find out the attributes of the obje... | Dave Webb is correct, and you can see this by adding a print statement:
```
>>> class X:
... l = []
... def __init__(self):
... print 'inited'
... self.__class__.l.append(1)
...
```
Then as soon as you type the period in `X().` it prints `inited` prior to offering you the completion po... | PythonWin's python interactive shell calling constructors twice? | [
"",
"python",
"python-2.x",
"activestate",
""
] |
How do I load a Python module given its full path?
Note that the file can be anywhere in the filesystem where the user has access rights.
---
**See also:** [How to import a module given its name as string?](https://stackoverflow.com/questions/301134) | Let's have `MyClass` in `module.name` module defined at `/path/to/file.py`. Below is how we import `MyClass` from this module
For Python 3.5+ use ([docs](https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly)):
```
import importlib.util
import sys
spec = importlib.util.spec_from_file_locat... | The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:
```
import sys
# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py
sys.path.append('/foo/bar/mock-0.3.1')
from testcase import TestCase
from te... | How can I import a module dynamically given the full path? | [
"",
"python",
"python-import",
"python-module",
""
] |
Given:
```
e = 'a' + 'b' + 'c' + 'd'
```
How do I write the above in two lines?
```
e = 'a' + 'b' +
'c' + 'd'
``` | What is the line? You can just have arguments on the next line without any problems:
```
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
```
Otherwise you can do something like this:
```
if (a == True and
b == False):
```
or with explicit line break:
```
if... | From *[PEP 8 -- Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)*:
> **The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.** Long lines can be broken over multiple lines by wrapping expressions in parentheses. These shou... | How can I do a line break (line continuation) in Python (split up a long line of source code)? | [
"",
"python",
"syntax",
"line-breaks",
"long-lines",
""
] |
What database should a beginner use in the C language?
Can I use MySQL?
Thanks | You can use SQLite, MySQL, PostgreSQL, or any other DBMS with a C language binding.
* [SQLite In 5 Minutes Or Less](http://www.sqlite.org/quickstart.html)
* [MySQL C API](http://dev.mysql.com/doc/refman/5.1/en/c.html)
* [PostgreSQL C API](http://www.postgresql.org/docs/8.1/static/libpq.html) | If you question is "What RDBMS do you recommend for beginner?" I agree that MySQL is not a bad choice. It's easy to install and configure. I think that most RDMS can be accessed from C code now days | RDMS for C language newbie? | [
"",
"mysql",
"sql",
"c",
"database",
""
] |
I have an XML that I want to load to objects, manipulate those objects (set values, read values) and then save those XMLs back.
It is important for me to have the XML in the structure (xsd) that I created.
One way to do that is to write my own serializer, but is there a built in support for it or open source in C# tha... | You can generate serializable C# classes from a schema (xsd) using xsd.exe:
```
xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir
```
If the schema has dependencies (included/imported schemas), they must all be included on the same command line. | This code (C# DotNet 1.0 onwards) works quite well to serialize most objects to XML. (and back)
It does not work for objects containing ArrayLists, and if possible stick to using only Arrays
```
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization;
us... | How do I map XML to C# objects | [
"",
"c#",
"xml",
"serialization",
"xml-serialization",
""
] |
Also, how do `LEFT OUTER JOIN`, `RIGHT OUTER JOIN`, and `FULL OUTER JOIN` fit in? | Assuming you're joining on columns with no duplicates, which is a very common case:
* An inner join of A and B gives the result of A intersect B, i.e. the inner part of a [Venn diagram](http://en.wikipedia.org/wiki/Venn_diagram) intersection.
* An outer join of A and B gives the results of A union B, i.e. the outer pa... | The Venn diagrams don't really do it for me.
They don't show any distinction between a cross join and an inner join, for example, or more generally show any distinction between different types of join predicate or provide a framework for reasoning about how they will operate.
There is no substitute for understanding ... | What is the difference between "INNER JOIN" and "OUTER JOIN"? | [
"",
"sql",
"join",
"inner-join",
"outer-join",
""
] |
For my C# app, I don't want to always prompt for elevation on application start, but if they choose an output path that is UAC protected then I need to request elevation.
So, how do I check if a path is UAC protected and then how do I request elevation mid-execution? | The best way to detect if they are unable to perform an action is to attempt it and catch the `UnauthorizedAccessException`.
However as @[DannySmurf](https://stackoverflow.com/users/941/dannysmurf) [correctly points out](https://stackoverflow.com/questions/17533/request-vista-uac-elevation-if-path-is-protected#17544) ... | Requesting elevation mid-execution requires that you either:
1. Use a COM control that's elevated, which will put up a prompt
2. Start a second process that is elevated from the start.
In .NET, there is currently no way to elevate a running process; you have to do one of the hackery things above, but all that does is... | Request Windows Vista UAC elevation if path is protected? | [
"",
"c#",
".net",
"windows-vista",
"uac",
"elevated-privileges",
""
] |
I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.
I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609
[This](https://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience) is the full script that I'm trying to modify... | So I googled [greasemonkey dom ready](http://www.google.com/search?q=greasemonkey%20dom%20ready) and the [first result](http://www.sitepoint.com/article/beat-website-greasemonkey/) seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script... | GreaseMonkey scripts are themselves executed on DOMContentLoaded, so it's unnecessary to add a load event handler - just have your script do whatever it needs to to immediately.
<http://wiki.greasespot.net/DOMContentLoaded> | How to implement "DOM Ready" event in a GreaseMonkey script? | [
"",
"javascript",
"firefox",
"greasemonkey",
""
] |
I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.
IIRC, one of Python's original remits was as a prototyping langua... | Finally a question that I can really put a value answer to :).
I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:
**Disclaimer**: This is my... | I haven't used SWIG or SIP, but I find writing Python wrappers with [boost.python](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html) to be very powerful and relatively easy to use.
I'm not clear on what your requirements are for passing types between C/C++ and python, but you can do that easily by eithe... | Prototyping with Python code before compiling | [
"",
"python",
"swig",
"ctypes",
"prototyping",
"python-sip",
""
] |
I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows.
When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary.
If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Te... | Are you using the C/C++ Development Tools exclusively?
The Spellcheck functionality is dependent upon the Java Development Tools being installed also.
The spelling engine is scheduled to be pushed down from JDT to the Platform,
so you can get rid of the Java related bloat soon enough. :) | The CDT version of Ganymede apparently shipped improperly configured. After playing around for a while, I have come up with the following steps that fix the problem.
1. Export your Eclipse preferences (File > Export > General > Preferences).
2. Open the exported file in a text editor.
3. Find the line that says
``... | Eclipse spelling engine does not exist | [
"",
"c++",
"eclipse",
"spell-checking",
"eclipse-3.4",
"eclipse-cdt",
""
] |
I'm looking for a light version of REST for a Java web application I'm developing.
I've looked at RESTlet (www.restlet.org) and the REST plugin for Struts 2, but I haven't made up my mind. I'm leaning towards RESTlet, as it seems to be lighter.
Has anyone implemented a RESTful layer without any of the the frameworks ... | Well, I've used Enunciate quite a bit. It uses simple annotations to provide either REST and/or SOAP endpoints.
<http://enunciate.codehaus.org>
Plus, Ryan Heaton has always provided top-notch support for things, too. | I'm a huge fan of JAX-RS - I think they've done a great job with that specification. I use it on a number of projects and its been a joy to work with.
JAX-RS lets you create REST resources using POJOs with simple annotations dealing with the URI mappings, HTTP methods and content negotiation all integrated nicely with... | Lightweight REST library for Java | [
"",
"java",
"rest",
""
] |
I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have `/* .. */` comments, and also has its own self-documentation facility which seems to be the pythonic way to document.
Since I'm familiar with Doxygen, how can I use it to produce m... | This is [documented on the doxygen website](http://www.doxygen.nl/manual/docblocks.html#pythonblocks), but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
```
"""@package docstring
Documentation for this module.
More details.
"""
def fu... | The [doxypy](https://pypi.python.org/pypi/doxypy/) input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well. | How to document Python code using Doxygen | [
"",
"python",
"documentation",
"python-sphinx",
"doxygen",
"docstring",
""
] |
Can someone describe what a symbol table is within the context of C and C++? | There are two common and related meaning of symbol tables here.
First, there's the symbol table in your object files. Usually, a C or C++ compiler compiles a single source file into an object file with a .obj or .o extension. This contains a collection of executable code and data that the linker can process into a wor... | Briefly, it is the mapping of the name you assign a variable to its address in memory, including metadata like type, scope, and size. It is used by the compiler.
That's in general, not just C[++]\*. Technically, it doesn't always include direct memory address. It depends on what language, platform, etc. the compiler i... | What is a symbol table? | [
"",
"c++",
"c",
"symbol-table",
""
] |
Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however.... | Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
Some people prefer a "single entry, single exit" approach to all loops. Th... | Labels are like goto's: Use them sparingly, and only when they make your code faster **and** more importantly, more understandable,
> e.g., If you are in big loops six levels deep and you encounter a condition that makes the rest of the loop pointless to complete, there's no sense in having 6 extra trap doors in your ... | Should I avoid using Java Label Statements? | [
"",
"java",
"loops",
""
] |
Let me use the following example to explain my question:
```
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);
```
When I pass the variable `WhatIsMyName` to the `ExampleFunction`, I want to be able to get a str... | **No.** I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called `NamedParameter` with attributes `Name` and `Param`. You then pass this object around as parameters. | What you want isn't possible directly but you can use Expressions in C# 3.0:
```
public void ExampleFunction(Expression<Func<string, string>> f) {
Console.WriteLine((f.Body as MemberExpression).Member.Name);
}
ExampleFunction(x => WhatIsMyName);
```
Note that this relies on unspecified behaviour and while it doe... | How can I get the name of a variable passed into a function? | [
"",
"c#",
"asp.net",
".net",
""
] |
Lets say that you have websites www.xyz.com and www.abc.com.
Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider.
Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pas... | Try using FormAuthentication by setting the web.config authentication section like so:
```
<authentication mode="Forms">
<forms name=".ASPXAUTH" requireSSL="true"
protection="All"
enableCrossAppRedirects="true" />
</authentication>
```
Generate a machine key. Example: [Easiest way to generate MachineK... | If you are using the built in membership system you can do cross sub-domain authentication with forms auth by using some like this in each web.config.
```
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/Login.aspx" path="/"
protection="All"
domain="datasharp.... | How do you pass an authenticated session between app domains | [
"",
"c#",
"asp.net",
"asp.net-membership",
"membership",
""
] |
Using C++ (and Qt), I need to process a big amount of 3D coordinates.
Specifically, when I receive a 3D coordinate (made of 3 doubles), I need to check in a list if this coordinate has already been processed.
If not, then I process it and add it to the list (or container).
The amount of coordinates can become very bi... | Probably the simplest way to speed up such processing is to store the already-processed points in [Octree](http://en.wikipedia.org/wiki/Octree). Checking for duplication will become close to logarithmic.
Also, make sure you tolerate round-off errors by checking the distance between the points, not the equality of the ... | Divide your space into discrete bins. Could be infinitely deep squares, or could be cubes. Store your processed coordinates in a simple linked list, sorted if you like in each bin. When you get a new coordinate, jump to the enclosing bin, and walk the list looking for the new point.
Be wary of floating point compariso... | Fastest way to find if a 3D coordinate is already used | [
"",
"c++",
"performance",
""
] |
Every time I need to work with date and/or timstamps in Java I always feel like I'm doing something wrong and spend endless hours trying to find a better way of working with the APIs without having to code my own Date and Time utility classes. Here's a couple of annoying things I just ran into:
* 0-based months. I rea... | [This post](http://mike-java.blogspot.com/2008/02/java-date-time-api-vs-joda.html) has a good discussion on comparing the Java Date/Time API vs JODA.
I personally just use [Gregorian Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html) and [SimpleDateFormat](http://docs.oracle.com/javas... | # java.time
Java 8 and later now includes the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework. Inspired by [Joda-Time](http://www.joda.org/joda-time/), defined by [JSR 310](http://jcp.org/en/jsr/detail?id=310), extended by the [ThreeTen-Extra](http://www.threeten.org/thre... | What's the best way to manipulate Dates and Timestamps in Java? | [
"",
"java",
"datetime",
""
] |
So I have a "large" number of "very large" ASCII files of numerical data (gigabytes altogether), and my program will need to process the entirety of it sequentially at least once.
Any advice on storing/loading the data? I've thought of converting the files to binary to make them smaller and for faster loading.
Should... | > So then what if the processing requires jumping around in the data for multiple files and multiple buffers? Is constant opening and closing of binary files going to become expensive?
I'm a big fan of *'memory mapped i/o'*, aka *'direct byte buffers'*. In Java they are called **[Mapped Byte Buffers](http://docs.oracl... | You might want to have a look at the entries in the [Wide Finder Project](http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder) (do a google search for ["wide finder" java](http://www.google.com.au/search?q="wide+finder"+java)).
The Wide finder involves reading over lots of lines in log files, so look at the ... | Advice on handling large data volumes | [
"",
"java",
"loading",
"large-files",
"large-data-volumes",
""
] |
I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps.
The command line apps... | I found the programmatic answer that I was looking for. It has to do with stations. Apparently anything running on the desktop will run on a station with a particular name. Anything that isn't on the desktop (i.e. a process started by the task manager when logged off or on a locked workstation) will get started with a ... | You might be able to use SENS (System Event Notification Services). I've never used it myself, but I'm almost positive it will do what you want: give you notification for events like logon, logoff, screen saver, etc.
I know that's pretty vague, but hopefully it will get you started. A quick google search turned up thi... | Testing running condition of a Windows app | [
"",
"c++",
"windows",
"command-line",
""
] |
How can I, as the wiki admin, enter scripting (Javascript) into a Sharepoint wiki page?
I would like to enter a title and, when clicking on that, having displayed under it a small explanation. I usually have done that with javascript, any other idea? | Assuming you're the administrator of the wiki and are willing display this on mouseover instead of on click, you don't need javascript at all -- you can use straight CSS. Here's an example of the styles and markup:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
... | If the wiki authors are wise, there's probably no way to do this.
The problem with user-contributed JavaScript is that it opens the door for all forms of evil-doers to grab data from the unsuspecting.
Let's suppose evil-me posts a script on a public web site:
```
i = new Image();
i.src = 'http://evilme.com/store_coo... | How to enter Javascript into a wiki page? | [
"",
"javascript",
"html",
"sharepoint",
"wiki",
""
] |
Is there a tool or script which easily merges a bunch of [JAR](http://en.wikipedia.org/wiki/JAR_%28file_format%29) files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable.
The concrete case is a [Java restructured text tool](http://jrst.labs.libre-entreprise.org/en/user/fu... | Eclipse 3.4 JDT's Runnable JAR export wizard.
In Eclipse 3.5, this has been extended. Now you can chose how you want to treat your referenced JAR files. | Ant's `zipfileset` does the job
```
<jar id="files" jarfile="all.jar">
<zipfileset src="first.jar" includes="**/*.java **/*.class"/>
<zipfileset src="second.jar" includes="**/*.java **/*.class"/>
</jar>
``` | Easiest way to merge a release into one JAR file | [
"",
"java",
"jar",
"merge",
"restructuredtext",
"uberjar",
""
] |
The log4j network adapter sends events as a serialised java object. I would like to be able to capture this object and deserialise it in a different language (python). Is this possible?
*NOTE* The network capturing is easy; its just a TCP socket and reading in a stream. The difficulty is the deserialising part | Generally, no.
The stream format for Java serialization is defined [in this document](http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf), but you need access to the original class definitions (and a Java runtime to load them into) to turn the stream data back into something approaching the original objects. For example... | *Theoretically*, it's possible. The Java Serialization, like pretty much everything in Javaland, is standardized. So, you *could* implement a deserializer according to that standard in Python. However, the Java Serialization format is not designed for cross-language use, the serialization format is closely tied to the ... | Deserialize in a different language | [
"",
"java",
"serialization",
"log4j",
""
] |
For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online [JavaScript Shell](http://www.squarefree.com/shell/) is really nice, but I'm looking for something local, without the need for an browser.
So far I have tested the standal... | Rhino Shell since 1.7R2 has support for completion as well. You can find more information [here](http://blog.norrisboyd.com/2009/03/rhino-17-r2-released.html). | In Windows, you can run this file from the command prompt in cscript.exe, and it provides an simple interactive shell. No completion.
```
// shell.js
// ------------------------------------------------------------------
//
// implements an interactive javascript shell.
//
// from
// http://kobyk.wordpress.com/2007/09/... | JavaScript interactive shell with completion | [
"",
"javascript",
""
] |
I.e., a web browser client would be written in C++ !!! | There are a two choices. Managed C++ (/clr:oldSyntax, no longer maintained) or C++/CLI (definitely maintained). You'll want to use /clr:safe for in-browser software, because you wnat the browser to be able to verify it. | This was originally known as [Managed C++](http://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B), but as Josh commented, it has been superceded by [C++/CLI](http://en.wikipedia.org/wiki/C%2B%2B/CLI). | Is there a way to compile C++ code to Microsoft .Net CIL (bytecode)? | [
"",
".net",
"c++",
"browser",
"cil",
""
] |
If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debu... | Yes, simple.
say you have
```
char *a = new char[10];
```
writing in the debugger:
```
a,10
```
would show you the content as if it were an array. | There are two methods to view data in an array m4x4:
```
float m4x4[16]={
1.f,0.f,0.f,0.f,
0.f,2.f,0.f,0.f,
0.f,0.f,3.f,0.f,
0.f,0.f,0.f,4.f
};
```
One way is with a Watch window (Debug/Windows/Watch). Add watch =
```
m4x4,16
```
This displays data in a list:
 call that tells you the div is empty. At some point after that the Ajax request is finished and content is actually put into the div. At this point the onSuccess function is execu... | Problem accessing the content of a div when that content came from an Ajax call | [
"",
"javascript",
"dom",
"prototypejs",
""
] |
What is the best way to keep a PHP script running as a daemon, and what's the best way to check if needs restarting.
I have some scripts that need to run 24/7 and for the most part I can run them using [nohup](http://en.wikipedia.org/wiki/Nohup). But if they go down, what's the best way to monitor it so it can be auto... | If you can't use the (proper) init structure to do this (you're on shared hosting, etc.), use cron to run a script (it can be written in whatever language you like) every few minutes that checks to see if they're running, and restarts them if necessary. | The most elegant solution is [reactPHP](http://reactphp.org). | What's the best way to keep a PHP script running as a daemon? | [
"",
"php",
"daemon",
""
] |
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my templa... | The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another... | As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible. | Using Django time/date widgets in custom form | [
"",
"python",
"django",
""
] |
I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code.
The first step of the parsing process splits the file into individual lines by just using a `StreamReader` object and calling `ReadLine` until it's through the file. However, any... | Since this isn't a true CSV file, does it have any sort of schema?
From your example, it looks like you have:
int, int, int, int, string , bool, bool, int
With that making up your record / object.
Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you... | State-machines for doing such a job are made easy using C# 2.0 iterators. Here's hopefully the last CSV parser I'll ever write. The whole file is treated as a enumerable bunch of enumerable strings, i.e. rows/columns. IEnumerable is great because it can then be processed by LINQ operators.
```
public class CsvParser
{... | Looking for Regex to find quoted newlines in a big string (for C#) | [
"",
"c#",
"regex",
""
] |
Using Oracle 10g with our testing server what is the most efficient/easy way to backup and restore a database to a static point, assuming that you always want to go back to the given point once a backup has been created.
A sample use case would be the following
1. install and configure all software
2. Modify data to ... | You do not need to take a backup at your base time. Just enable flashback database, create a guaranteed restore point, run your tests and flashback to the previously created restore point.
The steps for this would be:
1. Startup the instance in mount mode.
startup force mount;
2. Create the restore point.
cre... | You could use a feature in Oracle called [Flashback](http://www.oracle.com/technology/deploy/availability/htdocs/Flashback_Overview.htm) which allows you to create a restore point, which you can easily jump back to after you've done testing.
Quoted from the site,
> Flashback Database is like a 'rewind
> button' for y... | Backup/Restore database for oracle 10g testing using sqlplus or rman | [
"",
"sql",
"oracle",
"backup",
"oracle10g",
"rman",
""
] |
I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert:
```
insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('432... | To me it seems you're missing a `;` between the two statements:
`insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)`
**`;`**
`insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/200... | In .net, when we try to execute a single Oracle SQL statement with a semicolon at the end. The result will be an oracle error: ora-00911: invalid character. OK, you figure that one SQL statement doesn't need the semicolon, but what about executing 2 SQL statement in one string for example:
```
Dim db As Database = Dat... | ORA-00933: SQL command not properly ended | [
"",
"sql",
"oracle",
"ora-00933",
""
] |
I am writing a simple checkers game in Java. When I mouse over the board my processor ramps up to 50% (100% on a core).
I would like to find out what part of my code(assuming its my fault) is executing during this.
I have tried debugging, but step-through debugging doesn't work very well in this case.
Is there any t... | This is called "profiling". Your IDE probably comes with one: see [Open Source Profilers in Java](http://java-source.net/open-source/profilers). | Use a profiler (e.g [yourkit](http://www.yourkit.com) ) | Java: How can I see what parts of my code are running the most? (profiling) | [
"",
"java",
"debugging",
"user-interface",
"profiling",
""
] |
How can I use .NET DataSet.Select method to search records that match a DateTime?
What format should I use to enter my dates in? | The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals.
```
ds.select(DBDate = '15 Sep 2008')
```
You can use the DateFormat function to convert to long date format as well and this will work fine too. | I use the following for the SQL Select:
```
public string BuildSQL()
{
// Format: CAST('2000-05-08 12:35:29' AS datetime)
StringBuilder sb = new StringBuilder("CAST('");
sb.Append(_dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
sb.Append("' AS datetime)");
return sb.ToStri... | DataSet.Select and DateTime | [
"",
"c#",
".net",
"dataset",
""
] |
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.
I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the conta... | Try this simple, specific function:
```
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.c... | What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:
```
div {
position: absolute;
top: 300px;
bottom: 0px;
left: 30px;
right: 30px;
}
```
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with t... | Setting the height of a DIV dynamically | [
"",
"javascript",
"html",
"css",
""
] |
We have hundreds of websites which were developed in asp, .net and java and we are paying lot of money for an external agency to do a penetration testing for our sites to check for security loopholes.
Are there any (good) software (paid or free) to do this?
or.. are there any technical articles which can help me devel... | There are a couple different directions you can go with automated testing tools for web applications.
First, there are the **commercial web scanners**, of which HP WebInspect and Rational AppScan are the two most popular. These are "all-in-one", "fire-and-forget" tools that you download and install on an internal Wind... | I know you asked specifically about pentesting tools, but since those have been amply answered (I usually go with a mix of AppScan and trained pentester), I think it's important to point out that *pentesting is not the only way to "check for security loopholes", and is often **not the most effective**.*
Source code re... | Penetration testing tools | [
"",
"sql",
"security",
"sql-injection",
""
] |
I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java.
I've discovered a wrapper library, [http://www.ch-werner.de/javasqlite](http://www.ch-werner.de/javasqlite/), but are there other more prominent projects available? | The [wiki](http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers) lists some more wrappers:
* Java wrapper (around a SWIG interface): <http://tk-software.home.comcast.net/>
* A good tutorial to use JDBC driver for SQLite. (it works at least !) <http://www.ci.uchicago.edu/wiki/bin/view/VDS/VDSDevelopment/UsingSQLite>
* C... | I found your question while searching for information with [SQLite](http://www.sqlite.org/) and Java. Just thought I'd add my answer which I also posted on my [blog](http://blog.rungeek.com/post/81611917/how-to-use-sqlite-with-java).
I have been coding in Java for a while now. I have also known about SQLite but never ... | Java and SQLite | [
"",
"java",
"sqlite",
""
] |
I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated. | Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query
That way, even if the data in the database changes, you can easily refresh. | SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).
1. Right-click the database in SQL Management Studio
2. Go to Tasks and then Export data, you'll then see an easy to use wizard.
3. Your database will be the source, you can enter your SQL query
... | How do you transfer or export SQL Server 2005 data to Excel | [
"",
"sql",
"sql-server",
""
] |
Can anyone tell me what is the *memory usage overhead associated with PHP opcode cache*?
I've seen a lot of reviews of `opcode cache` but all of them only concentrate on the performance increase. I have a small entry level *VPS and memory limits* are a concern for me. | Most of the memory overhead will come from the opcode cache size. Each opcode cacher has their own default(e.g. 30MB for APC) which you can change through the config file.
Other than the cache size, the actual memory overhead of the cacher itself is negligible. | In todays world: It's neglectible. I think memory consumption was about 50 MB bigger with eAccelerator then it was without when I did my [benchmarks](http://blogs.interdose.com/dominik/2008/04/11/benchmarking-php-eaccelerator-und-andere-opcode-caches/).
If you really need the speed but do have headaches that your RAM ... | Opcode cache impact on memory usage | [
"",
"php",
"opcode-cache",
""
] |
This question is about removing **sequences** from an array, not duplicates in the strict sense.
Consider this sequence of elements in an array;
```
[0] a
[1] a
[2] b
[3] c
[4] c
[5] a
[6] c
[7] d
[8] c
[9] d
```
In this example I want to obtain the following...
```
[0] a
[1] b
[2] c
[3] a
[4] c
[5] d
```
Notice t... | Here's C# app i wrote that solves this problem.
**takes**
aabccacdcd
**outputs**
abcacd
Probably looks pretty messy, took me a bit to get my head around the dynamic pattern length bit.
```
class Program
{
private static List<string> values;
private const int MAX_PATTERN_LENGTH = 4;
static void Main... | **EDIT: made some changes and new suggestions**
What about a sliding window...
```
REMOVE LENGTH 2: (no other length has other matches)
//the lower case letters are the matches
ABCBAbabaBBCbcbcbVbvBCbcbcAB
__ABCBABABABBCBCBCBVBVBCBCBCAB
REMOVE LENGTH 1 (duplicate characters):
//* denote that a string was removed t... | Best way to reduce sequences in an array of strings | [
"",
"c#",
".net",
"algorithm",
""
] |
In C/C++, what an `unsigned char` is used for? How is it different from a regular `char`? | In C++, there are three *distinct* character types:
1. `char`
2. `signed char`
3. `unsigned char`
### 1. `char`
If you are using character types for **text**, use the unqualified `char`:
* it is the type of character literals like `'a'` or `'0'` (in C++ only, in C their type is `int`)
* it is the type that makes up... | This is implementation dependent, as the C standard does NOT define the signed-ness of `char`. Depending on the platform, char may be `signed` or `unsigned`, so you need to explicitly ask for `signed char` or `unsigned char` if your implementation depends on it. Just use `char` if you intend to represent characters fro... | What is an unsigned char? | [
"",
"c++",
"c",
"char",
""
] |
As an example in pseudocode:
```
if ((a mod 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}
``` | Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the *remainder* operator `%`. For your exact example:
```
if ((a % 2) == 0)
{
isEven = true;
}
else
{
isEven = false;
}
```
This can be simplified to a one-liner:
```
isEven = (a % 2) == 0;
``` | Here is the representation of your pseudo-code in minimal Java code;
```
boolean isEven = a % 2 == 0;
```
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values,... | What's the syntax for mod in java | [
"",
"java",
"modulo",
""
] |
I found an example in the [VS2008 Examples](http://msdn2.microsoft.com/en-us/bb330936.aspx) for Dynamic LINQ that allows you to use a SQL-like string (e.g. `OrderBy("Name, Age DESC"))` for ordering. Unfortunately, the method included only works on `IQueryable<T>`. Is there any way to get this functionality on `IEnumera... | Just stumbled into this oldie...
To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.
To get it working with `IEnumerable<T>` you could add some wrapper methods that go via `AsQueryable` - but the code below is the core `Expressio... | Too easy without any complication:
1. Add `using System.Linq.Dynamic;` at the top.
2. Use `vehicles = vehicles.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();`
**Edit**: to save some time, the **System.Linq.Dynamic.Core** (System.Linq.Dynamic is deprecated) assembly is not part of the framework, but can be ins... | Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T> | [
"",
"c#",
"linq",
"ienumerable",
"iqueryable",
"linq-to-objects",
""
] |
I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as ÄÄRITALO!
That is, html uses escaped markup for the special characters, such as Ä
Is there a simple way of reading the html into t... | I would recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for HTML scraping. You also need to tell it to convert HTML entities to the corresponding Unicode characters, like so:
```
>>> from BeautifulSoup import BeautifulSoup
>>> html = "<html>ÄÄRITALO!</html>"
>>> soup = BeautifulS... | Try using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). It should do the trick and give you a nicely formatted DOM to work with as well.
[This blog](http://channel3b.wordpress.com/2007/07/04/how-to-convert-html-entities-to-real-unicode-in-python/) entry seems to have had some success with it. | Getting international characters from a web page? | [
"",
"python",
"html",
"parsing",
"unicode",
""
] |
Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to? | ```
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
```
[User-defined methods:](https://docs.python.org/2.7/reference/datamodel.html#index-40)
> When a user-defined method object is
> created by retrieving a user-defined
> function object... | In python 3 the `__self__` attribute is *only* set on bound methods. It's not set to `None` on plain functions (or unbound methods, which are just plain functions in python 3).
Use something like this:
```
def is_bound(m):
return hasattr(m, '__self__')
``` | How do you check whether a python method is bound or not? | [
"",
"python",
"python-datamodel",
""
] |
While there are 100 ways to solve the conversion problem, I am focusing on performance.
Give that the string only contains binary data, what is the fastest method, in terms of performance, of converting that data to a byte[] (not char[]) under C#?
Clarification: This is not ASCII data, rather binary data that happens... | I'm not sure ASCIIEncoding.GetBytes is going to do it, because it only supports the [range 0x0000 to 0x007F](https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding).
You tell the string contains only bytes. But a .NET string is an array of chars, and 1 char is 2 bytes (because a .NET stores strings as ... | [UTF8Encoding.GetBytes](http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getbytes.aspx) | Using C#, what is the most efficient method of converting a string containing binary data to an array of bytes | [
"",
"c#",
"arrays",
""
] |
Below is my current char\* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?
How can I make this faster?
Compiled with -O3 in g++
```
static const char _hex2asciiU_value[2... | At the cost of more memory you can create a full 256-entry table of the hex codes:
```
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };
```
Then direct index into the table, no bit fiddling required.
```
const char *pHexVal = pHex[*pChar];
pszHex[0] = pHexVa... | This assembly function (based off my previous post here, but I had to modify the concept a bit to get it to actually work) processes 3.3 billion input characters per second (6.6 billion output characters) on one core of a Core 2 Conroe 3Ghz. Penryn is probably faster.
```
%include "x86inc.asm"
SECTION_RODATA
pb_f0: t... | char[] to hex string exercise | [
"",
"c++",
"optimization",
"hex",
""
] |
Here's my problem - I'd like to communicate between two websites and I'm looking for a clean solution. The current solution uses Javascript but there are nasty workarounds because of (understandable) cross-site scripting restrictions.
At the moment, **website A** opens a modal window containing **website B** using a [... | My best suggestion would be to create a webservice on each site that the other could call with the information that needs to get passed. If security is necessary, it's easy to add an SSL-like authentication scheme (or actual SSL even, if you like) to this system to ensure that only the two servers are able to talk to t... | With jQuery newer than 1.2 you can use [JSONP](http://remysharp.com/2007/10/08/what-is-jsonp/) | Communicating between websites (using Javascript or ?) | [
"",
"javascript",
"jquery",
"web",
"xss",
""
] |
In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:
```
::foo();
``` | It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like:
```
void bar(); // this is a global function
class foo {
void some_func() { ::bar(); } // this function is calling th... | A name that begins with the [scope resolution operator](http://en.wikipedia.org/wiki/Scope_resolution_operator) (`::`) is looked up in the global namespace. We can see this by looking at the [draft C++ standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf) section `3.4.3` *Qualified name lookup* p... | scope resolution operator without a scope | [
"",
"c++",
""
] |
How can I detect when an Exception has been thrown anywhere in my application?
I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.
I know I could just explicitly log and notify myself whenever an exception o... | You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there.
In a desktop app there are two places to w... | The new debugging hooks in Java 1.5 let you do this. It enables e.g. "break on any exception" in debuggers.
[Here's the specific Javadoc](http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/com/sun/jdi/event/ExceptionEvent.html) you need. | How can I detect when an Exception's been thrown globally in Java? | [
"",
"java",
"exception",
""
] |
What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light ... | **Code violation detection Tools:**
* [FxCop](https://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx), excellent tool by Microsoft. Check compliance with .NET framework guidelines.
**Edit October 2010:** No longer available as a standalone download. It is now included in the [Windows SDK](http://www.micros... | The tool [NDepend](http://www.ndepend.com/) is quoted as **Quality Metric Tools** but it is pretty much also a **Code violation detection** tool. *Disclaimer: I am one of the developers of the tool*
With NDepend, one can write [Code Rule over LINQ Queries (what we call CQLinq)](http://www.ndepend.com/Features.aspx#CQL... | What static analysis tools are available for C#? | [
"",
"c#",
"code-analysis",
"static-analysis",
""
] |
I have been making a little toy web application in C# along the lines of Rob Connery's Asp.net MVC storefront.
I find that I have a repository interface, call it IFooRepository, with methods, say
```
IQueryable<Foo> GetFoo();
void PersistFoo(Foo foo);
```
And I have three implementations of this: ISqlFooRepository, ... | Create an abstract class that contains concrete versions of the tests and an abstract GetRepository method which returns IFooRepository.
Create three classes that derive from the abstract class, each of which implements GetRepository in a way that returns the appropriate IFooRepository implementation.
Add all three cla... | In MbUnit, you might be able to use the RowTest attribute to specify parameters on your test.
```
[RowTest]
[Row(new ThisRepository())]
[Row(new ThatRepository())]
Public void GetFoo_NotNull_Test(IFooRepository repository)
{
var results = repository.GetFoo();
Assert.IsNotNull(results);
}
``` | Using the same test suite on various implementations of a repository interface | [
"",
"c#",
"unit-testing",
"interface",
"duplication",
""
] |
Is there a way to change the encoding used by the String(byte[]) constructor ?
In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.
```
String src = "with accents: é à";
byte[] bytes = src.getBytes("UTF-8");
System.out.println("UTF-8 decoded: "+ne... | You need to change the locale before launching the JVM; see:
[Java, bug ID 4163515](https://bugs.java.com/bugdatabase/view_bug;jsessionid=6f932817e77b249681417c21bfaf?bug_id=4163515)
Some places seem to imply you can do this by setting the file.encoding variable when launching the JVM, such as
```
java -Dfile.encodi... | Quoted from [defaultCharset()](http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html)
> The default charset is determined
> during virtual-machine startup and
> typically depends upon the locale and
> charset of the underlying operating
> system.
In most OSes you can set the charset using a environmen... | Changing the default encoding for String(byte[]) | [
"",
"java",
"encoding",
""
] |
This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data -- a description on the left side and a corresponding value displayed on the right side. I haven't worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using ta... | If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.
```
Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal handle As IntPtr, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByRef lParam As Integer) As Integer... | Thanks Matt, your solution worked great for me. Here's my version of your code...
```
// This is a better way to pass in what tab stops I want...
SetTabStops(textBox, new int[] { 12,120 });
// And the code for the SetTabsStops method itself...
private const uint EM_SETTABSTOPS = 0x00CB;
[DllImport("User32.dll")]
pri... | Is there an easy way to create two columns in a popup text window? | [
"",
"c#",
"winforms",
"controls",
"formatting",
""
] |
In order for my application (.Net 1.1) to use the system configured proxy server (trough a proxy.pac script) I was using an interop calls to WinHTTP function WinHttpGetProxyForUrl, passing the proxy.pac url I got from the registry.
Unfortunately, I hit a deployment scenario, where this does not work, as the proxy.pac ... | Just a thought: Why not create a micro web server that can serve the local PAC file over a localhost socket. You should use a random URI for the content so that it is difficult to browse this in unexpected ways.
You could then pass a URL like <http://localhost:1234/gfdjklskjgfsdjgklsdfklgfsjkl> to the WinHttpGetProxyF... | FWIW: <https://web.archive.org/web/20150405115150/http://msdn.microsoft.com/en-us/magazine/cc300743.aspx> describes how to use the JScript.NET engine to do this securely.
<https://web.archive.org/web/20090220132508/http://msdn.microsoft.com/en-us/library/aa383910(VS.85).aspx> explains how to use WinINET's implementati... | Autoproxy configuration script parsing in .Net/C# | [
"",
"c#",
"jscript.net",
"autoproxy",
""
] |
What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:
```
Dim x As New System.Web.UI.Control
x.ResolveUrl("~/someUrl")
```
Or C#:
```
System.Web.UI.Control x = new System.Web.UI.Control();
x.ResolveUrl("~/someUrl");
```
But I realize that isn't the best ... | I use [System.Web.VirtualPathUtility.ToAbsolute](http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx). | It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is **not** a perfect replacement for Control.ResolveUrl.
There is at least one significant difference: Control.ResolveUrl handles Query Strings very nicely, but they cause VirtualPathUtility to throw an HttpException. This... | ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function | [
"",
"c#",
"asp.net",
"vb.net",
"static",
"resolveurl",
""
] |
I need to find out the **external** IP of the computer a C# application is running on.
In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?
*(I have edited the question, to be a little more clear. I'm apologize to all kind peo... | I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.
```
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
IMessage request... | This is one of those questions where you have to look deeper and maybe rethink the original problem; in this case, "Why do you need an external IP address?"
The issue is that the computer may not have an external IP address. For example, my laptop has an internal IP address (192.168.x.y) assigned by the router. The ro... | Get external IP address over remoting in C# | [
"",
"c#",
".net",
"remoting",
""
] |
In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears.... | Aupajo has it right. I will, however, point you towards a bookmarklet framework I worked up for our site ([www.iminta.com](http://www.iminta.com)).
The bookmarklet itself reads as follows:
```
javascript:void((function(){
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.... | At it's very basic level it will be using `createElement` to create the elements to insert into the page and `appendChild` or `insertBefore` to insert them into the page. | How to display a form in any site's pages using a bookmarklet (like Note in Google Reader)? | [
"",
"javascript",
"client-side",
"bookmarklet",
"browser",
""
] |
Being relatively new to the .net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections?
For a specific example of a project I'm working on : a list of unique id / name pairs are being retrie... | i dont think the linq you wrote would compile, it'd have to be
```
public string branchName (string branchId)
{
//branchList populated in the constructor
branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault();
return branch_summary == null ? null : branch_summary.name;... | In general, your simple one-line for/foreach loop will be faster than using Linq. Also, Linq doesn't [always] offer significant readability improvements in this case. Here is the general rule I code by:
If the algorithm is simple enough to write and maintain without Linq, and you don't need delayed evaluation, *and* L... | Pros & cons between LINQ and traditional collection based approaches | [
"",
"c#",
".net",
"asp.net",
"linq",
""
] |
In the ContainsIngredients method in the following code, is it possible to cache the *p.Ingredients* value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside *p* eg. *p.InnerObjec... | Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter...
```
private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)
{
return i != null && i.Contains(ingredientType) && i.Get(ing... | Have you considered [Memoization](http://en.wikipedia.org/wiki/Memoization)?
The basic idea is this; if you have an expensive function call, there is a function which will calculate the expensive value on first call, but return a cached version thereafter. The function looks like this;
```
static Func<T> Remember<T>(... | Is it possible to cache a value evaluated in a lambda expression? | [
"",
"c#",
"linq",
"lambda",
"predicate",
""
] |
I have a usercontrol that has several public properties. These properties automatically show up in the properties window of the VS2005 designer under the "Misc" category. Except two of the properties which are enumerations don't show up correctly.
The first on uses the following enum:
```
public enum VerticalControlA... | For starters, the second enum, AutoSizeMode is declared in System.Windows.Forms. So that might cause the designer some issues.
Secondly, you might find the following page on MSDN useful:
<http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx> | I made a little test with your problem (I'm not sure if I understood it correctly), and these properties shows up in the designer correctly, and all enums are shown appropriately. If this isn't what you're looking for, then please explain yourself further.
Don't get hang up on the \_Ugly part thrown in there. I just u... | UserControl Property of type Enum displays in designer as bool or not at all | [
"",
"c#",
"visual-studio",
"enums",
"user-controls",
""
] |
In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class?
So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for section... | A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.
```
class dog(object):
def __init__(self, height, width, lenght):
self.height = height
self.width = width
self.length = length
def revert(se... | Here's another answer kind of like pobk's; it uses the instance's dict to do the work of saving/resetting variables, but doesn't require you to specify the names of them in your code. You can call save() at any time to save the state of the instance and reset() to reset to that state.
```
class MyReset:
def __init... | Classes in Python | [
"",
"python",
"class",
""
] |
I need to calculate `Math.exp()` from java very frequently, is it possible to get a native version to run faster than **java**'s `Math.exp()`??
I tried just jni + C, but it's slower than just plain **java**. | +1 to writing your own exp() implementation. That is, if this is *really* a bottle-neck in your application. If you can deal with a little inaccuracy, there are a number of extremely efficient exponent estimation algorithms out there, some of them dating back centuries. As I understand it, Java's exp() implementation i... | This has already been requested several times (see e.g. [here](https://stackoverflow.com/questions/412019/code-optimizations#412988)). Here is an approximation to Math.exp(), copied from [this blog posting](http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/):
```
public static double exp(dou... | faster Math.exp() via JNI? | [
"",
"java",
"c",
"optimization",
"java-native-interface",
""
] |
I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.
Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted an... | ## Some test results
I've gotten a lot of good answers to this question--thanks folks--so I decided to run some tests and figure out which method is actually fastest. The five methods I tested are these:
* the "ContainsKey" method that I presented in [the question](https://stackoverflow.com/questions/81346/most-effic... | Now there is a shorter way with Java 8 using [`Map::merge`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#merge(K,V,java.util.function.BiFunction)).
```
myMap.merge(key, 1, Integer::sum)
```
or
```
myMap.merge(key, 1L, Long::sum)
```
for longs respectively.
What it does:
* if *ke... | Most efficient way to increment a Map value in Java | [
"",
"java",
"optimization",
"collections",
""
] |
I'm looking for a general solution for upgrading database schema with ORM tools, like JPOX or Hibernate. How do you do it in your projects?
The first solution that comes to my mind is to create my own mechanism for upgrading databases, with SQL scripts doing all the work. But in this case I'll have to remember about c... | [LiquiBase](http://www.liquibase.org) is an interesting open source library for handling database refactorings (upgrades). I have not used it, but will definitely give it a try on my next project where I need to upgrade a db schema. | I don't see why ORM generated schemas are any different to other DB schemas - the problem is the same. Assuming your ORM will spit out a generation script, you can use an external tool to do the diff
I've not tried it but google came back with [SQLCompare](http://www.red-gate.com/products/SQL_Compare/index.htm) as one... | How to upgrade database schema built with an ORM tool? | [
"",
"java",
"database",
"orm",
"migration",
""
] |
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?
For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap? | I've always made those decisions on a case by case basis, depending on the use case, such as:
* Do I need the ordering to remain?
* Will I have null key/values? Dups?
* Will it be accessed by multiple threads
* Do I need a key/value pair
* Will I need random access?
And then I break out my handy 5th edition **Java in... | I really like this cheat sheet from Sergiy Kovalchuk's blog entry, but unfortunately it is offline. However, the Wayback Machine has a [historical copy](https://web.archive.org/web/20200802192003/http://www.sergiy.ca/guide-to-selecting-appropriate-map-collection-in-java/):
 and convert it to the corresponding enumeration value.
In an ideal world, I could do so... | In .NET Core and .NET Framework ≥4.0 [there is a generic parse method](https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx):
```
Enum.TryParse("Active", out StatusEnum myStatus);
```
This also includes C#7's new inline `out` variables, so this does the try-parse, conversion to the explicit enum type ... | Use [`Enum.TryParse<T>(String, T)`](http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.Enum.TryParse%60%601%29;k%28SolutionItemsProject%29;k%28TargetFrameworkMoniker-.NETFramework,Version=v4.5%29;k%28DevLang-csharp%29&rd=true) (≥ .NET 4.0):
```
StatusEnum myStatus;
Enum.TryParse("Active"... | Convert a string to an enum in C# | [
"",
"c#",
"string",
"enums",
""
] |
I am currently loading a lightbox style popup that loads it's HTML from an XHR call. This content is then displayed in a 'modal' popup using `element.innerHTML = content` This works like a charm.
In another section of this website I use a Flickr 'badge' (<http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-do... | In general, script tags aren't executed when using innerHTML. In your case, this is good, because the `document.write` call would wipe out everything that's already in the page. However, that leaves you without whatever HTML document.write was supposed to add.
jQuery's HTML manipulation methods will execute scripts in... | I created a simple test page that illustrates the problem:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Document Write Testcase</title>... | Dynamically inserting javascript into HTML that uses document.write | [
"",
"javascript",
"html",
"ajax",
""
] |
When using Google Chrome, I want to debug some JavaScript code. How can I do that? | Windows: `CTRL`-`SHIFT`-`J` OR F12
Mac: `⌥`-`⌘`-`J`
Also available through the wrench menu (Tools > JavaScript Console):
 | Try adding this to your source:
```
debugger;
```
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint. | How do you launch the JavaScript debugger in Google Chrome? | [
"",
"javascript",
"google-chrome",
"debugging",
"google-chrome-devtools",
""
] |
I have a servlet that is used for many different actions, used in the [Front Controller pattern](http://java.sun.com/blueprints/patterns/FrontController.html). Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"? I can't read the request parameters until I decide th... | Yes, the `Content-type` header in the user agent's request should include `multipart/form-data` as described in (at least) the HTML4 spec:
<http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2> | If you are going to try using the request.getContentType() method presented above, be aware that:
1. request.getContentType() may return null.
2. request.getContentType() may not be *equal* to "multipart/form-data", but may just start with it.
With this in mind, the check you should run is :
```
if (request.getConte... | Can a servlet determine if the posted data is multipart/form-data? | [
"",
"java",
"servlets",
"multipartform-data",
"front-controller",
""
] |
I frequently have problems dealing with `DataRows` returned from `SqlDataAdapters`. When I try to fill in an object using code like this:
```
DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;
```
What is the best way to deal with `DBNull's` in this type of situation. | Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
```
int? value = 5;
```
I would also recommend using the "`as`" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you... | If you aren't using nullable types, the best thing to do is check to see if the column's value is DBNull. If it is DBNull, then set your reference to what you use for null/empty for the corresponding datatype.
```
DataRow row = ds.Tables[0].Rows[0];
string value;
if (row["fooColumn"] == DBNull.Value)
{
value = str... | What is the best way to deal with DBNull's | [
"",
"c#",
".net",
"sql-server",
""
] |
is there a way to abort threads created with QueueUserWorkItem?
Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically? | You don't need to abort them. When your application exits, .NET will kill any threads with IsBackground = true. The .NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it.
Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or... | > However, if you are using unmanaged
> resources in those threads, you may
> end up in a lot of trouble.
That would rather depend how you were using them - if these unmanaged resources were properly wrapped then they'd be dealt with by their wrapper finalization regardless of the mechanism used to kill threads which ... | How to abort threads created with ThreadPool.QueueUserWorkItem | [
"",
"c#",
"multithreading",
""
] |
I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc.
I... | @J D OConal, thanks for the tip, the article you sent me was very outdated, but it did point me towards iText. I found this page that explains how to do exactly what I need:
<http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html>
Thanks for the other answers, but I don't really want to have to spawn other... | I've used [pdftk](http://www.accesspdf.com/pdftk/) to great effect. It's an external application that you'll have to run from your java app. | What's the easiest way to merge (server-side) a collection of PDF documents into one big PDF document in JAVA | [
"",
"java",
"pdf",
"pdf-generation",
""
] |
I'm trying to read a .doc file into a database so that I can index it's contents. Is there an easy way for PHP on Linux to read .doc files? Failing that is it possible to convert .doc files to rtf, pdf or some other 'open' format that is easy to read?
Note, I am not interested in .docx files. | There seems to be a [library for accessing Word documents](http://packages.ubuntu.com/hardy/libwv-1.2-3) but not sure how to access it from PHP. I think the best solution would be to call their [wv command](http://packages.ubuntu.com/hardy/wv) from PHP. | Conor, I'd suggest to look at OpenOffice command line interface / calling macros. It can convert many file formats to many others. Then you can pick something much more parse-able than MS doc.
For instance, to convert to PDF, a command line is:
```
/usr/lib/ooo-2.0/program/soffice.bin -norestore -nofirststart -nologo... | Getting PHP to read .doc files on Linux | [
"",
"php",
"database",
""
] |
Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them **ALL THE TIME**.
I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored p... | > **NOTE** that this is a general look at stored procedures not regulated to a specific
> DBMS. Some DBMS (and even, different
> versions of the same DBMS!) may operate
> contrary to this, so you'll want to
> double-check with your target DBMS
> before assuming all of this still holds.
>
> I've been a Sybase ASE, MySQL... | Reasons for using stored procedures:
* **Reduce network traffic** -- you have to send the SQL statement across the network. With sprocs, you can execute SQL in batches, which is also more efficient.
* **Caching query plan** -- the first time the sproc is executed, SQL Server creates an execution plan, which is cached ... | Are Stored Procedures more efficient, in general, than inline statements on modern RDBMS's? | [
"",
"sql",
"database",
"stored-procedures",
""
] |
I'm working with a large (270+ project) VS.Net solution. Yes, I know this is pushing the friendship with VS but it's inherited and blah blah. Anyway, to speed up the solution load and compile time I've removed all projects that I'm not currently working on... which in turn has removed those project references from the ... | No, there currently isn't a built-in quicker way.
I would suggest not modifying the existing solution and create a new solution with new projects that duplicate (e.g. rename and edit) the projects you want to work on. If you find that the solution with the hundreds of projects is an issue for you then you'll likely ju... | These solutions come to my mind:
* You can try to use [Dependency Walker](http://www.dependencywalker.com) or similar program to analyze dependecies.
* Parse MSBuild files (\*.csproject) to get list of dependencies
**EDIT:**
Just found 2 cool tools [Dependency Visualizer](http://www.codeplex.com/dependencyvisualize... | Locate and add project reference for .Net assembly containing a given type? | [
"",
"c#",
".net",
"visual-studio",
""
] |
Does anyone know of a way to force a nolock hint on all transactions issued by a certain user? I'd like to provide a login for a support team to query the production system, but I want to protect it by forcing a nolock on everything they do. I'm using SQL Server 2005. | This is a painful and hacky way to do it, but it's what we're doing where I work. We're also using classic asp so we're using inline sql calls. we actually wrap the sql call in a function (here you can check for a specific user) and add "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED" to the beginning of the call.
I... | You could configure your support staff's SQL Management Studio to set the default transaction isolation level to READ UNCOMMITTED (Tools->Options->Query Execution->SQL Server->Advanced). This is functionally the same as having NOLOCK hints on everything.
The downsides are that you'd have to do this for each member of ... | How to force nolock hint for sql server logins | [
"",
"sql",
"sql-server",
"security",
"sql-server-2005",
"query-optimization",
""
] |
I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first?
Is there some kind of hash function that can take identical input, but in any order, and still produce the same result? | The easiest way would seem to be to hash each line on the way in, storing the hash and the original data, and then compare each new hash with your collection of existing hashes. If you get a positive, you could compare the actual data, to make sure it's not a false positive - though this would be extremely rare, you co... | Well the problem specification is a bit limited.
As I understand it you wish to see if several strings contain the same elements regardless of order.
For example:
```
A B C
C B A
```
are the same.
The way to do this is to create a set of the values then compare the sets. To create a set do:
```
HashSet set = new ... | Detect changes in random ordered input (hash function?) | [
"",
"java",
"multithreading",
"hash",
""
] |
Are there any open-source libraries that all programmers should know about? I'm thinking
something general, a sort of extension to the standard `java.util` that contains basic functions that are useful for all kinds of application. | * Apache Commons
* Log4j
* Google collections | The [Spring framework](http://www.springframework.org/) is surprisingly general purpose. I started by just using it as a configuration management tool, but then realized how helpful dependency injection is when doing test-driven development. Then I slowly discovered many useful modules hidden in the corners of Spring. | What is the most useful multi-purpose open-source library for java? | [
"",
"java",
"open-source",
""
] |
In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:
```
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
```
This is a m... | I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
```
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
```
Or, you could write a small function:
```
function indexonce(&$ar, $index) {
return $ar[$index];
}
```... | The technical answer is that the ***Grammar*** of the PHP language only allows subscript notation on the end of **variable expressions** and not **expressions** in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that... | PHP: Access Array Value on the Fly | [
"",
"php",
"arrays",
"coding-style",
""
] |
What is the most proper way to sending email of minimal 1000 or more in PHP? Any reliable email queuing technique that is capable to handle that?
| You could just insert your emails into a Mail Queue database table, and have a separate process check the queue and batch send a certain number at once. | There's a tested solution for that: PEAR [Mail\_Queue](http://pear.php.net/package/Mail_Queue)
Works fine for me. | Email queueing in php | [
"",
"php",
"email",
"queue",
""
] |
Is there available any tool for PHP which can be used to generate code for consuming a [web service](http://en.wikipedia.org/wiki/Web_service) based on its [WSDL](http://en.wikipedia.org/wiki/Web_Services_Description_Language)? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin ... | I've had great success with [wsdl2php](https://github.com/jbarciauskas/wsdl2php). It will automatically create wrapper classes for all objects and methods used in your web service. | In PHP 5 you can use [SoapClient](http://www.php.net/manual/en/ref.soap.php) on the WSDL to call the web service functions. [For example](http://www.php.net/manual/en/soapclient.construct.php):
```
$client = new SoapClient("some.wsdl");
```
and $client is now an object which has class methods as defined in some.wsdl.... | How to easily consume a web service from PHP | [
"",
"php",
"web-services",
"visual-studio",
"wsdl",
""
] |
Typical way of creating a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) string (pseudocode):
1. Create a CSV container object (like a StringBuilder in C#).
2. Loop through the strings you want to add appending a comma after each one.
3. After the loop, remove that last superfluous comma.
Code sample:
``... | You could use [LINQ to Objects](http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects):
```
string [] strings = contactList.Select(c => c.Name).ToArray();
string csv = string.Join(",", strings);
```
Obviously that could all be done in one line, but it's a bit clearer on two. | Your code not really compliant with [full CSV format](http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm). If you are just generating CSV from data that has no commas, leading/trailing spaces, tabs, newlines or quotes, it should be fine. However, in most real-world data-exchange scenarios, you do need the full imleme... | CSV string handling | [
"",
"c#",
"csv",
""
] |
I have a table with a 'filename' column.
I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.
How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent row... | The solution is:
```
UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50
```
RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select ... | MattMitchell's answer is correct if the column is a CHAR(20), but is not true if it was a VARCHAR(20) and the spaces hadn't been explicitly entered.
If you do try it on a CHAR field without the RTRIM function you will get a *"String or binary data would be truncated"* error. | What is the easiest way using T-SQL / MS-SQL to append a string to existing table cells? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has go... | First, I would suggest you have a look at "[Rapid Development with Python, Django, and Google App Engine](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine)"
GvR describes a general/standard project layout on page 10 of his [slide presentation](http://sites.google.com/site/io/r... | My usual layout looks something like this:
* app.yaml
* index.yaml
* request.py - contains the basic WSGI app
* lib
+ `__init__.py` - common functionality, including a request handler base class
* controllers - contains all the handlers. request.yaml imports these.
* templates
+ all the django templates, used by t... | Project structure for Google App Engine | [
"",
"python",
"google-app-engine",
""
] |
I am trying to achieve better performance for my Java SWT application, and I just found out it is possible to use OpenGL in SWT. It seems there are more than one Java binding for OpenGL. Which one do you prefer?
Note that I have never used OpenGL before, and that the application needs to work on Windows, Linux and Mac... | [JOGL](http://www.opengl.org/resources/bindings/ "opengl.org")
My reasons can be quoted off the previously linked site:
> JOGL provides full access to the APIs in the OpenGL 2.0 specification as well as nearly all vendor extensions, and integrates with the AWT and Swing widget sets.
Also if you want to have some fun... | I'd suggest checking out [LWJGL](http://lwjgl.org/), the LightWeight Java Game Library. It's got OpenGL bindings, but it also has OpenAL bindings and some great tutorials to get you started.
Just keep in mind that Swing/SWT and OpenGL are generally used for entirely different things. You may end up wanting to use a co... | What is the best OpenGL java binding? | [
"",
"java",
"user-interface",
"opengl",
"performance",
"swt",
""
] |
I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...).
Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks! | Check out this [metadata extractor](https://www.drewnoakes.com/code/exif/). It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.
---
**EDIT** *metadata-extractor* supports .NET too. It's ... | As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:
* [System.Drawing.Image.PropertyItems](http://msdn.microsoft.com/en-us/library/system.drawing.image.propertyitems... | How to get the EXIF data from a file using C# | [
"",
"c#",
"exif",
"photography",
""
] |
I want to create a custom control in C#. But every time I have to fully redraw my control, it flickers, even if I use double buffering (drawing to an Image first, and blitting that).
How do I eliminate flicker when I have to fully redraw? | You could try putting the following in your constructor after the InitiliseComponent call.
```
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
```
EDIT:
If you're giving this a go, if you can, remove your own double buffering code... | I pulled this from a working C# program. Other posters have syntax errors and clearly copied from C++ instead of C#
```
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
``` | How to eliminate flicker in Windows.Forms custom control when scrolling? | [
"",
"c#",
".net",
"winforms",
"gdi+",
""
] |
I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.
in vb.net: `Parent.FindControl(TargetControlName)`
I would like to pass a method to the control in the ASPX markup.
for example: `<c:MyCustomerControl runat=server InitializeStuff... | If you want to be able to pass a method in the ASPX markup, you need to use the `Browsable` attribute in your code on the event.
VB.NET
```
<Browsable(True)> Public Event InitializeStuffCallback
```
C#
```
[Browsable(true)]
public event EventHandler InitializeStuffCallback;
```
Reference:
[Design-Time Attributes f... | Normally you wouldn't need to get the method via reflection. Inside your user control, define a public event (sorry I do not know the vb syntax so this will be in c#)
```
public event EventHandler EventName;
```
Now, inside your aspx page, or whatever container of the user control, define a protected method that matc... | How to pass method name to custom server control in asp.net? | [
"",
"c#",
"asp.net",
"vb.net",
"custom-server-controls",
"web-controls",
""
] |
Currently I am using NetTiers to generate my data access layer and service layer. I have been using NetTiers for over 2 years and have found it to be very useful. At some point I need to look at LINQ so my questions are...
1. Has anyone else gone from NetTiers to LINQ To SQL?
2. Was this switch over a good or bad thin... | 1. No
2. See #1
3. You should beware of standard abstraction overhead. Also it's very SQL Server based in it's current state.
4. Are you using SQL Server, then maybe. If you are using LINQ for other things right now like over XML data (great), Object data, Datasets, then yes you should could switch to have a uniform da... | I tried to use Linq to SQL on a small project, thinking that I wanted something I could generate quickly. I ran into a lot of problems in the designer. For example, anytime you need to add a column to a table you basically have to remove and re-add the table definition in the designer. If you have set any properties on... | Should I start using LINQ To SQL? | [
"",
"c#",
"linq",
"linq-to-sql",
".nettiers",
""
] |
For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents.
Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in t... | After reading the replies so far (Thanks!) I passed the outermost JPanel to the following method:
```
void addTextFocusSelect(JComponent component){
if(component instanceof JTextComponent){
component.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(Foc... | I haven't tried this myself (only dabbled in it a while ago), but you can probably get the current focused component by using:
KeyboardFocusManager (there is a static method getCurrentKeyboardFocusManager())
an adding a PropertyChangeListener to it.
From there, you can find out if the component is a JTextComponent and ... | Is there an easy way to change the behavior of a Java/Swing control when it gets focus? | [
"",
"java",
"user-interface",
"swing",
""
] |
I want to encrypt few files using python what is the best way
I can use gpg/pgp using any standard/famous python libraries? | [PyCrypto](http://www.pycrypto.org) seems to be the best one around. | Try [KeyCzar](http://code.google.com/p/keyczar/)
Very easy to implement. | what is the best/easiest to use encryption library in python | [
"",
"python",
"encryption",
"gnupg",
"pgp",
""
] |
I'm looking for a technique or tool which we can use to obfuscate or somehow secure our compiled c# code. The goal is not for user/data security but to hinder reverse engineering of some of the technology in our software.
This is not for use on the web, but for a desktop application.
So, do you know of any tools avai... | This is a pretty good list of obfuscators from [Visual Studio Marketplace](https://marketplace.visualstudio.com/search?term=.net%20obfuscators&target=VS&category=All%20categories&vsVersion=&sortBy=Relevance)
Obfuscators
* [ArmDot](https://www.armdot.com/)
* [Crypto Obfuscator](http://www.ssware.com/cryptoobfuscator/ob... | There are tools that also 'deobfuscate' obfuscated DLLs - I'd suggest turning the piece that needs to be protected into an unmanaged component. | Best method to obfuscate or secure .Net assemblies | [
"",
"c#",
".net",
".net-2.0",
""
] |
I have a page that uses
```
$(id).show("highlight", {}, 2000);
```
to highlight an element when I start a ajax request, that might fail so that I want to use something like
```
$(id).show("highlight", {color: "#FF0000"}, 2000);
```
in the error handler. The problem is that if the first highlight haven't finished, t... | From the jQuery docs:
<http://docs.jquery.com/Effects/stop>
> *Stop the currently-running animation on the matched elements.*...
>
> When `.stop()` is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with `.slideUp()` when `.stop()` is... | **I listed this as a comment for the accepted answer, but I thought it would be a good idea to post it as a standalone answer as it seems to be helping some people having problems with `.stop()`**
---
FYI - I was looking for this answer as well (trying to stop a Pulsate Effect), but I did have a `.stop()` in my code.... | How do I stop an effect in jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm not sure I'm using all the correct terminology here so be forgiving.
I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code.
It's a shared host and we have another sit... | Hey guys thanks for the answers, it is really appreciated.
After ignoring the issue for a few months it has come up again, I did however find the answer to my problems.
Firstly, as you answers suggested, PHP and the mail() function were working as expected. The mail was getting sent.
The problem lies when the email ... | Yes. It will work just fine. I have a PHP script using the mail() function with the MX records set to Google Apps.
If the two scripts are on different hosts (it's a bit unclear from your post), then make sure that the host doesn't block some of the custom headers. I had issues with this when creating my script, but re... | Does the PHP mail() function work if I don't own the MX record | [
"",
"php",
"dns",
""
] |
Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops.
I first though... | try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well.
here
```
%Temp%\VWDWebCache
```
and possibl... | The above fix (deleting the temp files) did not work for me. I had to delete the `PageName.aspx.designer.cs` file, then right-click my page, and choose "Convert to Web Application" from the context menu.
When Visual Studio attempted to rebuild the designer file, it encountered (and revealed to me) the source of the pr... | ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008 | [
"",
"c#",
"asp.net",
"visual-studio",
""
] |
I use the Boost Test framework for my C++ code but there are two problems with it that are probably common to all C++ test frameworks:
* There is no way to create automatic test stubs (by extracting public functions from selected classes for example).
* You cannot run a single test - you have to run the entire 'suite'... | I just responded to a [very similar question](https://stackoverflow.com/questions/91384/unit-testing-for-c-code-tools-and-methodology#92569). I ended up using Noel Llopis' UnitTest++. I liked it more than boost::test because it didn't insist on implementing the main program of the test harness with a macro - it can plu... | I've just pushed my own framework, [CATCH](http://www.levelofindirection.com/journal/2010/12/28/unit-testing-in-c-and-objective-c-just-got-easier.html), out there. It's still under development but I believe it already surpasses most other frameworks.
Different people have different criteria but I've tried to cover most... | C++ unit testing framework | [
"",
"c++",
"unit-testing",
""
] |
All I want is to update an ListViewItem's text whithout seeing any flickering.
This is my code for updating (called several times):
```
listView.BeginUpdate();
listViewItem.SubItems[0].Text = state.ToString(); // update the state
listViewItem.SubItems[1].Text = progress.ToString(); // update the progress
listView.... | To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to "Brian Gillespie" for giving the solution.
```
public enum ListViewExtendedStyles
{
/// <summary>
/// LVS_EX_GRIDLINES
/// </summary>... | The accepted answer works, but is quite lengthy, and deriving from the control (like mentioned in the other answers) just to enable double buffering is also a bit overdone. But fortunately we have reflection and can also call internal methods if we like to (but be sure what you do!).
Be encapsulating this approach int... | How to prevent flickering in ListView when updating a single ListViewItem's text? | [
"",
"c#",
".net",
"winforms",
"listview",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.