Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
"\u4000\f".TrimEnd(new char[0])
```
is equal to `"\u4000"`.
I am passing an empty array, so according to the MSDN documentation nothing should be removed and `"\u4000\f"` should be returned. Is there a reason for this behaviour?
EDIT: Clarified expected behaviour
EDIT: Apparently, this changed in 3.5, I was loo... | the documentation says "If trimChars is null (Nothing in Visual Basic) or an *empty array*, white-space characters are removed instead. "
So no, not a bug. | The [documentation](http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx) is clear:
> Removes all trailing occurrences of a
> set of characters specified in an
> array from the current String object.
>
> Return Value Type: System..::.String
> The string that remains after all
> occurrences of the charact... | Is this a bug in string.TrimEnd? | [
"",
"c#",
"string",
""
] |
This is an incredibly simple question (I'm new to Python).
I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.
As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out... | Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:
```
d = {}
for row in rows:
c = list_of_categories.index(row["id"])
print c
d[c] = row["name"]
```
... or more compactly:
```
d = dict((list_of_categories.index(row['id']), row['name']) for row in ro... | If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:
```
n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array
```
This prints:
```
[None, None, None]
[42, 47, 11]
``` | How do you create a list like PHP's in Python? | [
"",
"python",
"list",
""
] |
I have a Python function that takes a numeric argument that **must** be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?
My first reaction is to do something like this:
```
def isInteger(n):
return int(n) == n
```
But I can't help thinking that this is 1) expens... | ```
isinstance(n, int)
```
If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this):
```
type(n) is int
```
this:
```
return int(n) == n
```
isn't such a good idea, as cross-type comparisons can be true - notably `int(3.0)==3.0` | Yeah, as Evan said, don't type check. Just try to use the value:
```
def myintfunction(value):
""" Please pass an integer """
return 2 + value
```
That doesn't have a typecheck. It is much better! Let's see what happens when I try it:
```
>>> myintfunction(5)
7
```
That works, because it is an integer. Hm. Le... | How can I type-check variables in Python? | [
"",
"python",
"typing",
"dynamic-typing",
""
] |
I'm trying to access a large Oracle database through SQL Server using OPENROWSET in client-side Javascript, and not having much luck. Here are the particulars:
* A SQL Server view that accesses the Oracle database using OPENROWSET works perfectly, so I know I have valid connection string parameters. However, the new r... | I'm answering this myself. I found the answer, and I'm not happy with the results. The functions that have worked are being run under my personal user id, and I have db-owner privileges. For the *ad hoc* access to work, I need to either set the `DisallowAdhocAccess` registry setting to 0, or give db-owner privileges to... | Opening client-side ADO connections to a database is a huge security no-no. You’re essentially giving the user the connection credentials to your database and daring them to find a hole in your database security. Even if your audience is internal to your company you can run into problems with them not having the oracle... | Accessing Oracle DB through SQL Server using OPENROWSET | [
"",
"javascript",
"sql-server",
"oracle",
"openrowset",
""
] |
From a strictly implementation and computer science point of view how would you classify the Php array datastructure? Is it an associative array? a hash? a dictionary? ... ? | From the [PHP manual](https://www.php.net/manual/en/language.types.array.php):
> An array in PHP is actually an ordered
> map. A map is a type that associates
> values to keys. This type is optimized
> for several different uses; it can be
> treated as an array, list (vector),
> hash table (an implementation of a
> ma... | Well, it depends on how you wish to classify it. I'd opt for classification by the performance of operations.
For example, a true array in Computer Science terms has an O(1) lookup time, while a linked list has an O(n) lookup time. Insertion and deletion are O(1) in a linked list while they are O(n) in an array.
I am... | What is the CS definition of a Php Array? | [
"",
"php",
"data-structures",
"computer-science",
""
] |
I need to add the "Run when Windows starts" option to my program CintaNotes, but do not want to sacrifice the "cleanness" of it: it is a 100% portable freeware and should not leave traces in the system.
I've come up with the idea to autodetect running from the Startup shortcut and automatically minimizing to the system... | Your "cleanness" appears to be an artificial construct at best. If you're telling the user to create a shortcut in the start-up folder, you're already leaving a footprint (and, to be honest, there's little difference between "myprog.exe" and "myprog.exe -m"). In that case, there are some easier approaches than automagi... | Even though you have already solver the problem I just wanted to say that it's possible to detect if the program was launched from shortcut. Once you have the shortcut path you can compare it to startup folder.
See the section "Detect if an executable was started from a Short-Cut
" at [Undocumented CreateProcess](http... | How to detect launching from a "Startup"-folder shortcut? | [
"",
"c++",
"windows",
"winapi",
"startup",
"windows-shell",
""
] |
When doing thread synchronization in C# should I also lock an object when I read a value or just changing it?
for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count? | From MSDN:
> A Queue<(Of <(T>)>) can support
> multiple readers concurrently, as long
> as the collection is not modified.
> Even so, enumerating through a
> collection is intrinsically not a
> thread-safe procedure. To guarantee
> thread safety during enumeration, you
> can lock the collection during the
> entire enu... | Depends on what you want to do with lock. Usually this kind of locking needs a reader/writer locking mechanism.
Readers/writers locking means that readers share a lock, so you can have multiple readers reading the collection simultaneously, but to write, you should acquire an exclusive lock. | Should you lock resources when reading values? | [
"",
"c#",
".net",
"multithreading",
"synchronization",
""
] |
Does anyone know of any libraries for .net that allow you to use graphics tablets?
specifically i am after the pressure sensitivity of the pen, but the 'eraser' and buttons on the pen would be useful too.
thanks | Have a look at the source for [Paint.NET](http://getpaint.net)
**EDIT**: There should also be a DLL there... | I have also discovered that WPF also has an `InkCanvas`, which has everything built into it. | Graphics tablet/stylus library | [
"",
"c#",
".net",
"input",
""
] |
I am new to Swing. I am trying to develop an application using Swing. I have managed to create the first page of my application. Now what I want to do is to traverse to a new page, using the next button. But am not able to find a way to do it using Swing. Also, if I click the previous button, would I be able to get the... | This one is old but might just get you started: <http://java.sun.com/developer/technicalArticles/GUI/swing/wizard/> | I assume you're trying to build a wizard-style swing dialog? swing does not offer an out-of-the-box framework for this type of task (but of course it offers all UI elements/controls that you will need to create one). just google for "swing wizard framework" and you will find plenty of inspiration -- unfortunately, i ca... | How can I travese to a next / previous page in a swing GUI | [
"",
"java",
"swing",
""
] |
My problem is ::
From a string like "/usr/folder1/folder2/filename.ext"
* I have to extract out file name only for display (filename.ext only).
+ My question would be how should I do it? Splitting on "/" and taking the last element is one way but doesn't smell nice to me.
* I have to create a hyperlink which uses U... | You could try something like this:
```
File file = new File("/usr/folder1/folder2/filename.ext");
System.out.println(file.getName());
```
I wasn't sure whether this would work if the file does not exist, but have just tried it and it appears to work OK. | [CommonsIO](http://commons.apache.org/proper/commons-io/) provides solutions for this problem: [`FilenameUtils.getName()`](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FilenameUtils.html#getName%28java.lang.String%29), returns the file name + extension.
```
String filename = ... | How to extract the file name from a file URI and create a link for the same? | [
"",
"java",
"filepath",
""
] |
I'm using VB9 (VS2008).
I've created a Windows Service that indexes some folders regularly.
Is there a way I can put an upper limit on the CPU usage depending upon the current system state, i.e., if the system is idle, the thread can use the CPU as much as it needs, but if there are other programs/processes running t... | You can reduce the priority of the thread, in .Net via [Thread.Priority](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx)
Setting it to BelowNormal will mean that other threads will be scheduled in front of it.
This can lead to the thread being starved, but it sounds like this is an acce... | On XP, ShuggyCoUk is correct. The first thing to do is simply lower the thread priority to something below 8. This will mean that any other thread or process that is running with priority 8 or greater will always run instead of your thread. Note, I do not recommend simply setting your process priority to <8, just the t... | Programmatically limit CPU Usage of a Thread running inside a Service | [
"",
"c#",
"multithreading",
"windows-services",
"service",
""
] |
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;
```
<__main__.evolutions instance at 0x01B8EA08>
```
but instead to show a selected attribute o... | If you want to just display a particular attribute of each class instance, you can do
```
print([obj.attr for obj in my_list_of_objs])
```
Which will print out the `attr` attribute of each object in the list `my_list_of_objs`. Alternatively, you can define the `__str__()` method for your class, which specifies how to... | Checkout the \_\_str\_\_() and \_\_repr\_\_() methods.
See <http://docs.python.org/reference/datamodel.html#object.__repr__> | python - readable list of objects | [
"",
"python",
"list",
""
] |
Does anyone know if the following expression will be possible in the next version(s) of PHP?
```
(new A())->a(); // Causes a syntax error
```
I find very annoying that currently one must write 2 lines instead of 1:
```
$c = new A();
$c->a();
``` | The first version does not cause a parse error, it is perfectly valid. The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards.
If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature... | A new-expression can be used as a function argument. A function call can be used as the left-hand side of the member access operator. Therefore, you just need to define a single function:
```
function with($object) { return $object; }
with(new A()) -> a();
```
No additional efforts required on a per-class basis. | Chaining a constructor with an object function call in PHP | [
"",
"php",
""
] |
Is it possible to know whether a Java class has been loaded, *without* attempting to load it? `Class.forName` attempts to load the class, but I don't want this side effect. Is there another way?
(I don't want to override the class loader. I'm looking for a relatively simple method.) | (Thanks to Aleksi) This code:
```
public class TestLoaded {
public static void main(String[] args) throws Exception {
java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
m.setAccessible(true);
ClassLoader cl = ClassLoader... | You can use the [findLoadedClass(String)](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#findLoadedClass(java.lang.String)) method in ClassLoader. It returns null if the class is not loaded. | In Java, is it possible to know whether a class has already been loaded? | [
"",
"java",
"classloader",
""
] |
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening here... | Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for that... | Another option is to put the code in the cpp file and in the same cpp file add explicit instantiations of the template with the types you expect to be using. This is useful if you know you're only going to be using it for a couple of types you know in advance. | Why do I get "unresolved external symbol" errors when using templates? | [
"",
"c++",
"templates",
"linker",
""
] |
How can I call a method asynchronously ? | How to call a Visual C# method asynchronously:
<http://support.microsoft.com/kb/315582> | You should probably use `ThreadPool.QueueUserWorkItem` ([ThreadPool.QueueUserWorkItem Method](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx)) | Async Method Call | [
"",
"c#",
".net",
""
] |
I have an array of Foo objects. How do I remove the second element of the array?
I need something similar to `RemoveAt()` but for a regular array. | If you don't want to use List:
```
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
```
You could try this extension method that I haven't actually tested:
```
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
... | The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array. | Remove element of a regular array | [
"",
"c#",
".net",
"arrays",
""
] |
I have a SWF Video player on my webpage. I want to draw a div tag over it with a high z-index to act as a popup on it . Its a very generic popup. Hence I cannot make it as a part of swf. but, SWF seems to have very high zIndex and would not allow any HTMLO entity to sit over it. How do I achieve this or is there an alt... | There are some arguments that have to be passed to the SWF file in order to be able to achieve that. In the HTML representation, inside the object tag you should put:
```
<param name="wmode" value="transparent">
```
and...
```
<embed wmode="transparent" ...
```
A similar value should apply if you're using a JS libr... | You need to add a param to the flash object `<param NAME="wmode" VALUE="transparent">` this puts it back in the "flow" and allows other html elements to go on top
oh and add the wmode="transparent" to th embed tag | HTML Object over a SWF | [
"",
"javascript",
"html",
"flash",
""
] |
I want to write a service (probably in c#) that monitors a database table. When a record is inserted into the table I want the service to grab the newly inserted data, and perform some complex business logic with it (too complex for TSQL).
One option is to have the service periodically check the table to see if new re... | Probably you should de-couple postprocessing from inserting:
In the Insert trigger, add the record's PK into a queue table.
In a separate service, read from the queue table and do your complex operation. When finished, mark the record as processed (together with error/status info), or delete the record from the queue... | What you are describing is sometimes called a Job Queue or a Message Queue. There are several threads about using a DBMS table (as well as other techniques) for doing this that you can find by searching.
I would consider doing anything iike this with a Trigger as being an inappropriate use of a database feature that's... | Can SQL CLR triggers do this? Or is there a better way? | [
"",
"sql",
"sql-server",
"t-sql",
"triggers",
"sqlclr",
""
] |
Are there any built-in functions in .Net that allow to capitalize strings, or handling proper casing? I know there are some somewhere in the Microsoft.VB namespace, but I want to avoid those if possible.
I'm aware of functions like string.ToUpper and string.ToLower() functions however it affects the entire string. I a... | Just to throw another option into the mix. This will capitalize every word in the given string:
```
public static string ToTitleCase(string inputString)
{
System.Globalization.CultureInfo cultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo... | There's
```
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(string str)
```
to capitalize every word in a string. [ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) | Built-In Character Casing functions in .Net | [
"",
"c#",
".net",
"string",
""
] |
Most references I've seen, and my IDE's code completion all have my specifying a Generic type on both a variables type and its implementation eg.
```
List<String> string = new ArrayList<String>();
```
Recently I've started skipping the generic type on the implementation eg.
```
List<String> strings = new ArrayList()... | > Is there a reason to include the generic type on the implementation?
It's required as it won't necessarily be the same:
```
List<? extends Number> numbers = new ArrayList<Integer>();
```
One way of avoiding it for common cases is to have static utility methods, and let the compiler's type inference do the rest:
`... | The compiler may allow you to write code with such assignments (depending on your warnings/errors settings) but it is unsafe. Here's an example:
```
List<Date> dates = new ArrayList<Date>();
List list = dates;
List<String> strings = list;
strings.add("a");
Date d = dates.get(0); // Boom!!
``` | Java: Specifying generics on Type AND Implementation | [
"",
"java",
"generics",
""
] |
I'm soon going to check in the very first commit of a new Java project. I work with Eclipse Ganymede and a bunch of plug ins are making things a little bit easier.
Previously I've been part of projects where the entire Eclipse project was checked in. It's quite convenient to get the project settings after a check out.... | At a minimum you should be check-in the `.project` and `.classpath` files. If anybody on your team is hard-coding an external JAR location in the `.classpath` you should put them up against the wall and shoot them. I use Maven to manage my dependencies but if you are not using maven you should create user libraries for... | I recommend to use [maven](http://maven.apache.org) so that the entire life cycle is outside of any IDE. You can easily create an eclipse project with it on the command line and you can use whatever you want, if it's not eclipse. It has it's quirks but takes out a lot of bitterness when it comes to dependencies and bui... | To check in, or not check in, the entire Eclipse project? | [
"",
"java",
"eclipse",
"version-control",
"netbeans",
""
] |
According to this <http://www.cplusplus.com/reference/clibrary/csignal/signal.html>
`SIGINT` is generally used/cause by the user. How do i cause a `SIGINT` in c++? i seen an example using `kill(pid, SIGINT);` but i rather cause it another way. Also i am using windows. | C89 and C99 define raise() in signal.h:
```
#include <signal.h>
int raise(int sig);
```
This function sends a signal to the calling process, and is equivalent to
```
kill(getpid(), sig);
```
If the platform supports threads, then the call is equivalent to
```
pthread_kill(pthread_self(), sig);
```
The return val... | You cause a `SIGINT` by pressing `Ctrl+C`.
Example code:
```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void siginthandler(int param)
{
printf("User pressed Ctrl+C\n");
exit(1);
}
int main()
{
signal(SIGINT, siginthandler);
while(1);
return 0;
}
```
When run:
```
$ ./a.out
^CUser presse... | Using SIGINT | [
"",
"c++",
"windows",
"signals",
""
] |
I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body
```
class Body
```
from which I'll be deriving various implementations of a physics simulation. My game object class then looks like
```
class GameObject {
pu... | The idea of the law of Demeter is that your `GameObject` isn't supposed to have functions like `GetPosition()`. Instead it's supposed to have `MoveForward(int)` or `TurnLeft()` functions that may call `GetPosition()` (along with other functions) internally. Essentially they translate one interface into another.
If you... | One approach you could take is to split the `Body` interface into multiple interfaces, each with a different purpose and give `GameObject` ownership of only the interfaces that it would have to expose.
```
class Positionable;
class Movable;
class Collidable;
//etc.
```
The concrete `Body` implementations would probab... | How to restructure this code hierarchy (relating to the Law of Demeter) | [
"",
"c++",
"oop",
"refactoring",
"law-of-demeter",
""
] |
I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell.
I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks
```
JComboBox cb1 = new JComboBox(...);
JComboBox cb2 = n... | The easiest way is to implement your own [TableModel](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html)
```
public class MyModel extends AbstractTableModel {
List rows;
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
return 4;
... | Extend JTable with this code:
```
@Override
public TableCellEditor getCellEditor(int row, int column) {
Object value = super.getValueAt(row, column);
if(value != null) {
if(value instanceof JComboBox) {
return new DefaultCellEditor((JComboBox)value);
}
return getDefaultEditor(v... | Putting JComboBox into JTable | [
"",
"java",
"jtable",
"jcombobox",
""
] |
Is there a good C++ framework to implement XA distributed transactions?
With the term "good" I mean usable, simple (doesn't imply "easy"), well-structured.
Due to study reasons, at the moment I'm proceeding with a personal implementation, following X/Open XA specification.
Thank you in advance. | I am not aware of an open-source or free transaction monitor that has any degree of maturity, although [This link](http://linuxfinances.info/info/tpmonitor.html) does have some fan-out. The incumbent commercial ones are [BEA's Tuxedo,](http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/tux/) Tibco's [E... | Maybe quite late for your task, but it can be useful for other users: [LIXA](https://sourceforge.net/projects/lixa/) is not a "framework", but it provides an implementation for the TX Transaction Demarcation specification and supports most of the XA features.
The TX specification is for C and COBOL languages, but the i... | XA distributed transactions in C++ | [
"",
"c++",
"xa",
""
] |
Why I can use `Object Initializers` in Visual Studio 2008 Windows projects, etc targeted to .NET 2.0 but cannot - in ASP.NET projects targeted to .NET 2.0 ?
I understand that this is C# 3.0 features, but don't - why this possible to use in .NET 2.0 projects. | Probably because the ASP.Net stuff targeting the 2.0 framework assumes it will run in a mode where it may have to compile some code on the fly. Since it is running in 2.0 mode it will get the 2.0 compiler at that stage (thus anything relying on the 3.0 compiler will fail)
When targeting the 2.0 codebase from a 'normal... | When you target the .NET 2.0 runtime, you are also targeting the C# 2.0 compiler. That version of the compiler does not understand the 3.0 features. | Why I cannot use Object Initializers in ASP.NET 2.0? | [
"",
"c#",
"asp.net",
"object-initializers",
""
] |
I am storing the response to various rpc calls in a mysql table with the following fields:
```
Table: rpc_responses
timestamp (date)
method (varchar)
id (varchar)
response (mediumtext)
PRIMARY KEY(timestamp,method,id)
```
What is the best method of selecting the most recent responses for all exis... | Self answered, but I'm not sure that it will be an efficient enough solution as the table grows:
```
SELECT timestamp,method,id,response FROM rpc_responses
INNER JOIN
(SELECT max(timestamp) as timestamp,method,id FROM rpc_responses GROUP BY method,id) latest
USING (timestamp,method,id);
``` | > This solution was updated recently.
> Comments below may be outdated
This can query may perform well, because there are no joins.
```
SELECT * FROM (
SELECT *,if(@last_method=method,0,1) as new_method_group,@last_method:=method
FROM rpc_responses
ORDER BY method,timestamp DESC
) as t1
WHERE new_meth... | How to select the most recent set of dated records from a mysql table | [
"",
"mysql",
"sql",
"date",
"greatest-n-per-group",
""
] |
I'm a newbie when it comes to LINQ...
I have an IEnumerable generic list that contains answers with different versions (each with an FK to the question). From this list I need to get a dictionary of latest version answers only.
A very simplified class diagram:
Question
-ID
-question
- ...other properties
Answ... | How about something like....
```
private void button1_Click(object sender, EventArgs e)
{
List<Answer> list = GetAnswers();
var dict = (from a in list
group a by a.QuestionID into grp
from g in grp
where g.Version == grp.Max(m => m.Version)
... | ```
latestVersionAnswers = answers
.GroupBy(e => e.Question.ID)
.Select(g => g.OrderByDescending(e => e.Version).First())
.ToDictionary(e => e.Question.ID);
```
Or, if you prefer the selecting overload of ToDictionary:
```
latestVersionAnswers = answers
.GroupBy(e => e.Question.ID)
.ToDictionary(
g => g... | LINQ with subselect and groupby to get only the latest version of each item in a list | [
"",
"c#",
"linq",
"lambda",
""
] |
I was using [xampp](http://www.apachefriends.org/en/xampp.html) to develop locally and then I installed the PHP from the direct installer. Now in some of my PHP code, only PHP code that starts with `"<?php`" is correctly parsed. Anything that starts with "`<?`" or "`<?=`" is completely ignored and just left as is.
How... | This is a php.ini setting named
```
short_open_tag = 1 # (enabled)
``` | I recommend you to disable [`short_open_tag`](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) and only work with `<?php`. When `short_open_tag` is enabled, it can collide with the [XML processing instruction](http://www.w3.org/TR/REC-xml/#sec-pi) `<?xml` as both the PHP open tag and XML PI start with a `<... | Why is "<?" no longer working and instead only "<?php" works? | [
"",
"php",
"xampp",
""
] |
In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? | suppose you're posting a html form with this:
```
<input type="text" name="username">
```
If using [raw cgi](http://docs.python.org/library/cgi.html):
```
import cgi
form = cgi.FieldStorage()
print form["username"]
```
If using [Django](http://docs.djangoproject.com/), [Pylons](http://pylonshq.com/), [Flask](http:/... | I know this is an old question. Yet it's surprising that no good answer was given.
First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conve... | How are POST and GET variables handled in Python? | [
"",
"python",
"post",
"get",
""
] |
I need to add line breaks in the positions that the browser naturally adds a newline in a paragraph of text.
For example:
<p>This is some very long text **\n** that spans a number of lines in the paragraph.</p>
This is a paragraph that the browser chose to break at the position of the **\n**
I need to find this pos... | I would suggest wrapping all spaces in a span tag and finding the coordinates of each tag. When the Y-value changes, you're on a new line. | I don't think there's going to be a very clean solution to this one, if any at all. The browser will flow a paragraph to fit the available space, linebreaking where needed. Consider that if a user resizes the browser window, all the paragraphs will be rerendered and almost certainly will change their break positions. I... | How to find where browser breaks a paragraph of text | [
"",
"javascript",
"html",
""
] |
I'm trying to use this code to replace spaces with \_, it works for the first space in the string but all the other instances of spaces remain unchanged. Anybody know why?
```
function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}
``` | Try `.replace(/ /g,"_");`
*Edit*: or `.split(' ').join('_')` if you have an aversion to REs
*Edit*: [John Resig said](http://ejohn.org/blog/javascript-micro-templating/):
> If you're searching and replacing
> through a string with a static search
> and a static replace it's faster to
> perform the action with
> .spl... | try this:
```
key=key.replace(/ /g,"_");
```
that'll do a global find/replace
[javascript replace](http://www.w3schools.com/jsref/jsref_replace.asp) | Replacing spaces with underscores in JavaScript? | [
"",
"javascript",
"string",
""
] |
What do you recommend for setting the MAMP development stack?
I've seen the quickstart thing at <http://www.mamp.info>, but I don't really like that approach. I'd rather have a full-fledged Apache that I can install any number of modules into. I remember seeing in the OS X v10.5 (Leopard) Server demo a really slick GU... | OS X already comes with Apache, PHP, Perl and Python. Just install MySQL and edit the Apache config file as needed and you should be golden. | You could use [Darwin Ports](http://darwinports.com/) or [Fink](http://www.finkproject.org/) to install everything from scratch. | How can I get started with Apache, MySQL, and (PHP, Perl, Python) on a Mac? | [
"",
"php",
"mysql",
"perl",
"apache",
"macos",
""
] |
I overloaded the 6 signals listed on this site <http://www.cplusplus.com/reference/clibrary/csignal/signal.html>
Then i ran my app (double click not ran through IDE) and tried 1) end task 2) X on topright and 3) kill process. I expected the first two to cause some kind of signal (i am on XP) but alas i got nothing. Am... | Win32 does not provide an option to intercept your program being killed with `TerminateProcess` (which is what will happen when you "End Task" from Task Manager or click on the [X]).
You can catch the SIGSEGV signal because the C runtime library provides an emulation of this signal when running on Windows. When your p... | You can catch runtime error like an access violation if you override the default exception handler calling SetUnhandledExceptionFilter (this is a win32 function and as such doesn't rely on C library emulation). This is the method can used to provide "minidumps" when a program crashes.
But this exception handler will n... | signal when user kills process? | [
"",
"c++",
"windows-xp",
"crash",
"signals",
"kill-process",
""
] |
I have the following code:
```
// Obtain the string names of all the elements within myEnum
String[] names = Enum.GetNames( typeof( myEnum ) );
// Obtain the values of all the elements within myEnum
Array values = Enum.GetValues( typeof( myEnum ) );
// Print the names and values to file
for ( int i = 0; i < names.... | ```
Array values = Enum.GetValues(typeof(myEnum));
foreach( MyEnum val in values )
{
Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}
```
Or, you can cast the System.Array that is returned:
```
string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum... | You need to cast the array - the returned array is actually of the requested type, i.e. `myEnum[]` if you ask for `typeof(myEnum)`:
```
myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));
```
Then `values[0]` etc | C# Iterating through an enum? (Indexing a System.Array) | [
"",
"c#",
"enums",
"iteration",
"system.array",
""
] |
Given a dictionary like so:
```
my_map = {'a': 1, 'b': 2}
```
How can one invert this map to get:
```
inv_map = {1: 'a', 2: 'b'}
``` | Python 3+:
```
inv_map = {v: k for k, v in my_map.items()}
```
Python 2:
```
inv_map = {v: k for k, v in my_map.iteritems()}
``` | Assuming that the values in the dict are unique:
Python 3:
```
dict((v, k) for k, v in my_map.items())
```
Python 2:
```
dict((v, k) for k, v in my_map.iteritems())
``` | Reverse / invert a dictionary mapping | [
"",
"python",
"dictionary",
"mapping",
"reverse",
""
] |
I want to use a string that I have been using in one aspx.cs file over to another. I know this is easy, but how do I go about doing that? | You can do it in a query string. On your first page:
```
Response.Redirect("Second.aspx?book=codecomplete");
```
and on the second page
```
string book = Request["book"];
```
This method will allow your users to see what you are passing to a second page. Alternatively you can place it in session object. To place it... | You can either send it using a querystring or you can define a session variable to store it.
The best option depends on what you want to use that string for. | How do I bring a string from one aspx.cs page to another? | [
"",
"c#",
".net",
"asp.net",
""
] |
Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use 'larger' enum element names. Still, the namespace solution has two possible implementations: a dummy class with nested enum, or a full blown namespace.
I'm looking for pros a... | **Original C++03 answer:**
The *benefit* from a `namespace` (over a `class`) is that you can use `using` declarations when you want.
The *problem* with using a `namespace` is that namespaces can be expanded elsewhere in the code. In a large project, you would not be guaranteed that two distinct enums don't both think... | FYI In C++0x there is a new syntax for cases like what you mentioned (see [C++0x wiki page](http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations))
```
enum class eColors { ... };
enum class eFeelings { ... };
``` | namespaces for enum types - best practices | [
"",
"c++",
"enums",
"scope",
"nested",
""
] |
For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than the ... | While C is a pure procedural language, C++ is a *multi-paradigm* language. It supports
* Generic programming: Allowing to write code once, and use it with different data-structures.
* Meta programming: Allowing to utilize templates to generate efficient code at compile time.
* Inspection: Allows to inspect certain pro... | C++ is 99% a superset of C. It's a little more strict in syntax, with a few very minute differences in terms of things changing.
The biggest difference is that C++ makes an attempt at being object oriented. There's native support for classes.
There's a few other perks in C++: templates, stream operators, pass-by-refe... | What are the major differences between C and C++ and when would you choose one over the other? | [
"",
"c++",
"c",
"programming-languages",
""
] |
I have good knowledge on the working of a "traditional" `.dll`. Also the differences between `dynamic loading` and `static loading`, etc.
But I have the following doubts about the working of COM objects,
* Is it mandatory to register COM objects with `regsvr32`?
* can I have two versions of a registered `COM object` ... | 1) No - it is NOT necessary to register COM *objects*. Registration is needed to create *new* COM objects. There are many interfaces (COM or native functions) that want a COM object. Their API tells you which interface your COM object should support. Since you pass in an existing COM object, they don't need registratio... | Yes, COM assemblies are registered so that the COM infrastructure knows they exist. The DLLs are found by registration of a CLSID, not by path.
Two versions could co-exist if they have different names (you can't have the same named file in a folder, obviously).
All COM objects implement specific interfaces (IUnknown,... | Questions about COM/ActiveX objects | [
"",
"c++",
"c",
"com",
"dll",
"activex",
""
] |
Is it bad practice to have a string like
"name=Gina;postion= HouseMatriarch;id=1234" to hold state data in an application.I know that I could just as well have a struct , class or hashtable to hold this info.
Is it acceptable practice to hold delimited key/value pairs in a database field– just for use in where the dat... | Yes, holding your data in a string like "name=Gina;postion= HouseMatriarch;id=1234" is very bad practice. This data structure should be stored in structs or objects, because it is hard to access, validate and process the data in a string. It will take you much more time to write the code to parse your string to get at ... | Well, if your application only passes this data between other systems, I don't see any problems in treating it as a string. However, if you need to use the data, I would definitely introduce the necessary types to handle that. | C# Is holding data in a delimited string bad practice | [
"",
"c#",
""
] |
In my application I am running the same winform in different contexts to control visibility of buttons, enabeling of text fields and the winform header text.
The way I decided to do this is simply by passing a string to the form constructor and check it with a couple of if statements that in turn contain the desired wi... | A virtual member call in the base class ctor *could* cause some logic to run in the subclass before the subclass' ctor is called (and thus before the object gets a chance to initialize itself to a consistent state).
It's just a nice reminder so you know you are doing something that could potentially cause some nasty u... | In addition to the existing answers, for forms you could add a Load event handler:
```
Load += delegate
{
if (formContext == "add")
{
Text = "Add member";
}
if (formContext == "edit")
{
Text = "Change role";
userTextBox.Enabled = false;
searchkButton.Visible = false;... | Virtual member call in constructor | [
"",
"c#",
"visual-studio-2008",
"resharper",
""
] |
I created a new email box for general support questions. When I try to send an email through SMTP I receive the following error:
> Mailbox unavailable. The server response was: No such recipient
I am able to email the box through Outlook and SMTP works when I send to other email address in the same domain. | The great thing about SMTP is that it's easy to spoof the conversation. The terrible thing about SMTP is also that it's easy to spoof the conversation. What makes this great is that if you want to figure out what's going wrong in a SMTP connection you can just "telnet mailhost 25" and start issuing SMTP commands like:
... | Is your DNS configured properly? You need an MX record specifying which host handles incoming messages for that domain.
Btw, your post is missing some details, like which server you are using etc. That makes it hard to find where the problem is. | SMTP Email: Mailbox unavailable. The server response was: No such recipient | [
"",
"c#",
"email",
"smtp",
""
] |
**How does one performance tune a SQL Query?**
* What tricks/tools/concepts can be used to change the performance of a SQL Query?
* How can the benefits be Quantified?
* What does one need to be careful of?
**What tricks/tools/concepts can be used to change the performance of a SQL Query?**
* Using Indexes? How do t... | I really like the book "Professional SQL Server 2005 Performance Tuning" to answer this. It's Wiley/Wrox, and no, I'm not an author, heh. But it explains a lot of the things you ask for here, plus hardware issues.
But yes, this question is way, way beyond the scope of something that can be answered in a comment box li... | Writing sargable queries is one of the things needed, if you don't write sargable queries then the optimizer can't take advantage of the indexes. Here is one example [Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-... | Performance Tuning SQL - How? | [
"",
"sql",
"performance",
""
] |
How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
Let's say I have 80 seconds; are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like `Convert.ToDateTime` or something? | For **.Net <= 4.0** Use the TimeSpan class.
```
TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
```
(As noted by Inder Kumar Rathore) For **... | For **.NET > 4.0** you can use
```
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
```
or if you want date time format then you can also do this
```
Tim... | How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time? | [
"",
"c#",
"datetime",
""
] |
I'm looking for some clarity on the SQL Server log file. I have a largish database (2GB) which lately wasn't backed up for whatever reason. The log file for the database grew to around 11GB which from my understanding is all the transactions and statements that occurred in the database.
My questions:
What causes the ... | Once you backup the transaction log, those transactions are truncated from the log but the space used by the operation is not automatically recovered. If you are doing regular transaction log backups, this can be a good thing. The assumption being that the space being used for transactions and will be needed again in t... | A backup usually clears the transaction log. The transaction log keeps all changes since the last backup. Depending on how you backup the database you may not need to keep a full transaction log at all. If you are using MS SQL2000/MS SQL2005 setting the recovery mode to **Simple** does away with the transaction log.
O... | SQL Server Log File Confusion | [
"",
"sql",
"sql-server",
"flush",
""
] |
I am using C# to write a method that returns the following information about a table:
column names, column types, column sizes, foreign keys.
Can someone point me in the right direction on how to accomplish this ? | To get the FK and Schema you should be able to use:
```
DA.FillSchema()
DS.Table("Name").PrimaryKey
```
OR calling **sp\_fkey** using the method demonstrated below
Code Snippet [from](http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/fad53def-d4d3-4a46-9fe2-f7d2f1251b42/) AND [Another Link]... | This really depends on how you communicate with your database. If you are using LinqToSQL or another similar ORM this would be pretty easy but if you want to get these values via a query I'd suggest you use the INFORMATION\_SCHEMA views as these are fast and easy to query.
e.g.
```
select * from information_schema.co... | ADO.Net : Get table definition from SQL server tables | [
"",
"c#",
"sql-server",
"ado.net",
""
] |
**Here is my situation:**
I have an application that use a configuration file. The configuration file applies to all users of the system and all users can make change to the configuration.
I decided to put the configuration file in "All Users\Application Data" folder.
The problem is that the file is writable only by... | I wouldn't even bother with COM. Named pipes to your service work fine, too, and it's a lot easier to secure those with ACLs. The service will be so simple I wouldn't even bother with MFC or .NET, pure C++ should be fine. All the heavy lifting is done by your real app; the service just checks if the request piped in ar... | This is not the right approach. If you're putting the file in All Users\Application Data, then it should be writable by all users. When you create it, create it with write permissions for all users. Setting the creation permissions isn't that hard. | Windows service to control access to a file in "All Users\Application Data" | [
"",
"c++",
"windows",
"mfc",
""
] |
Basically I'm asking the same question as this guy: [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python)
But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doin... | ```
main.py
setup.py
app/ ->
__init__.py
package_a/ ->
__init__.py
module_a.py
package_b/ ->
__init__.py
module_b.py
```
1. You run `python main.py`.
2. `main.py` does: `import app.package_a.module_a`
3. `module_a.py` does `import app.package_b.module_b`
Alternatively 2 or 3 co... | If I'm [reading](http://www.python.org/dev/peps/pep-0328/) [correctly](http://docs.python.org/whatsnew/2.5.html), in Python 2.5 or higher:
```
from ..Module_B import Module_B
```
I thought I was well-versed in Python but I had no idea that was possible in version 2.5. | Python - Doing absolute imports from a subfolder | [
"",
"python",
"python-import",
""
] |
I would like to dynamically add fields to an ASP.NET MVC form with JQuery.
Example:
```
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
AddWidget();
});
function AddWidget() {
$('#widgets').append("<li><input type... | My solution could be something like this (pseudo-code):
```
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
<% for each value in ViewData("WidgetValues") %>
AddWidget(<%= value %>);
<% next %>
});
func... | i might be missing the point here, but, do you need to actually post the data back to the controller via a form action? why not make an ajax call using jquery to post the data to the controller...or better yet a web service? send the data async and no need to rebuild the view with the data values sent in.
This works f... | ASP.NET MVC & JQuery Dynamic Form Content | [
"",
"c#",
"jquery",
"asp.net-mvc",
""
] |
Not entirely sure how to phrase the question, because it's a "why doesn't this work?" type of query.
I've reduced my particular issue down to this code:
```
public interface IFoo
{
}
public class Foo : IFoo
{
}
public class Bar<T> where T : IFoo
{
public Bar(T t)
{
}
public Bar()
: this(new... | You could also have a Fiz that implements IFoo that is not related to Foo in any other way:
```
public interface IFoo
{
}
public class Foo : IFoo
{
}
public class Fiz : IFoo
{
}
Foo foo = new Foo();
Fiz fiz = foo; // Not gonna compile.
```
What you want is probably more like:
```
public class Bar<T> where T : IFo... | If you create a class Baz and then the generic type Bar baz = new Bar(), new Foo() as defined by your constructor overload, would not be of type T, in this case Baz. | Generic constraints and interface implementation/inheritance | [
"",
"c#",
"generics",
""
] |
After reading this on the question [How do I uniquely identify computers visiting my web site?](https://stackoverflow.com/questions/216542/how-do-i-uniquely-identify-computers-visiting-my-web-site#216599)
:
> A possibility is using flash cookies:
>
> ```
> Ubiquitous availability (95 percent of visitors will probably ... | To build on what *rmeador* said, and to help get you started, you are going to need to know how to use two classes in the FLEX3 API, [SharedObject](http://livedocs.adobe.com/flex/3/langref/) and [ExternalInterface](http://livedocs.adobe.com/flex/3/langref/).
**SharedObject** will allow you to store and retrive data fr... | I'm hesitant to answer your question, because it sounds like this is straying dangerously close to Evil... Also, it's doomed to failure. If you really want to prevent a user from answering a quiz multiple times, the best thing you can do is have them register a user account. If you want to prevent them from registering... | Javascript bridge to Flash to store SO "cookies" within flash | [
"",
"javascript",
"flash",
"cookies",
""
] |
I've tried my best to be a purist with my usage of Javascript/Ajax techniques, ensuring that all Ajax-y behavior is an enhancement of base functionality, while the site is also fully functional when Javascript is disabled. However, this causes some problems.
In some cases, a DOM node should only be visible when Javasc... | How about combining some of these solutions:
```
<style type="text/javascript">
.only-without-script {
display: none;
}
</style>
<noscript>
<style type="text/javascript">
.only-with-script {
display: none;
}
.only-without-script {
display: block;
... | For situations identical to yours, I usually put the submit button around a [`<noscript>`](http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.1) tag. No one has suggested it, so I am not sure if it is considered bad practice around these parts, but it is what I use and it works for me.
If you only want a nod... | How to eliminate post-render "flicker"? | [
"",
"javascript",
"jquery",
"html",
"ajax",
"dom",
""
] |
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?
If you're unfamiliar with the rules, there's a description of semicolon insertion on the [Mozilla site](http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html). Here's the ... | Yes, you should use semicolons after every statement in JavaScript. | An ambiguous case that breaks in the absence of a semicolon:
```
// define a function
var fn = function () {
//...
} // semicolon missing at this line
// then execute some code inside a closure
(function () {
//...
})();
```
This will be interpreted as:
```
var fn = function () {
//...
}(function () {
... | Do you recommend using semicolons after every statement in JavaScript? | [
"",
"javascript",
""
] |
When doing an ALTER TABLE statement in MySQL, the whole table is read-locked (allowing concurrent reads, but prohibiting concurrent writes) for the duration of the statement. If it's a big table, INSERT or UPDATE statements could be blocked for a looooong time. Is there a way to do a "hot alter", like adding a column i... | The only other option is to do manually what many RDBMS systems do anyway...
- Create a new table
You can then copy the contents of the old table over a chunk at a time. Whilst always being cautious of any INSERT/UPDATE/DELETE on the source table. (Could be managed by a trigger. Although this would cause a slow down... | Percona makes a tool called [pt-online-schema-change](https://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html) that allows this to be done.
It essentially makes a copy of the table and modifies the new table. To keep the new table in sync with the original it uses triggers to update. This allows t... | ALTER TABLE without locking the table? | [
"",
"sql",
"mysql",
"ddl",
"alter-table",
""
] |
I'm working on an application that allows users to add their own RSS feeds to a simple reader of sorts.
Currently, I'm using `xml_domit_rss` as the parser but I'm unsure if it's actually validating the URL before parsing.
From what I can gather online, it looks as if validating is separate from the parse, either by u... | It's simple, You can do that using **[SyndicationFeed](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx)**.
It supports [Atom 1.0](http://www.ietf.org/rfc/rfc4287.txt) and [RSS 2.0](http://validator.w3.org/feed/docs/rss2.html) versions.
```
try
{
SyndicationFeed fetched... | You could validate the RSS with a RelaxNG schema. Schemas for all the different feed formats should be available online... | Validating an RSS feed | [
"",
"php",
"xml",
"rss",
"feed",
"validation",
""
] |
In [this blog article](http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/) they use the construct:
```
@measured
def some_func():
#...
# Presumably outputs something like "some_func() is finished in 121.333 s" somewhere
```
This `@measured` directive doesn't seem to work with raw py... | `@measured` decorates the some\_func() function, using a function or class named `measured`. The `@` is the decorator syntax, `measured` is the decorator function name.
Decorators can be a bit hard to understand, but they are basically used to either wrap code around a function, or inject code into one.
For example t... | Yes it's real. It's a function decorator.
Function decorators in Python are functions that take a function as it's single argument, and return a new function in it's place.
`@classmethod` and `@staticmethod` are two built in function decorators.
[Read more »](http://www.python.org/dev/peps/pep-0318/) | Is @measured a standard decorator? What library is it in? | [
"",
"python",
"decorator",
""
] |
What's wrong with this query:
```
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
```
It works without the `WHERE` clause. I've seemed to have forgot my SQL. | MySQL [INSERT Syntax](http://dev.mysql.com/doc/refman/5.5/en/insert.html) does not support the WHERE clause so your query as it stands will fail. Assuming your `id` column is unique or primary key:
If you're trying to insert a new row with ID 1 you should be using:
```
INSERT INTO Users(id, weight, desiredWeight) VAL... | You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-
1. INSERT specifying values
```
INSERT INTO Users(weight, desiredWeight)
VALUES (160,145)
```
2. INSERT using a SELECT statement
```
INSERT INTO Users(weight, desiredWeight)
SELECT weight, desired... | MySQL Insert query doesn't work with WHERE clause | [
"",
"sql",
"mysql",
""
] |
Say I have an array of values:
```
string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };
```
Then I have a basic loop:
```
for (int i = 0; i <= 30; i++)
{
Console.WriteLine(i + " = " + text[i])
}
```
Obviously, this will cause an out of bounds exception, so what I want to do is when the count... | You could use the modulus operator:
```
Console.WriteLine(i + " = " + text[i % 5])
``` | Take the modulus of the array length:
```
for (int i = 0; i < 30; ++i)
{
Console.WriteLine(i + " = " + text[i % text.Length]);
}
``` | Looping through an array without throwing exception | [
"",
"c#",
"arrays",
"loops",
""
] |
I have a Linq to SQL query that was working just fine with SQL Server 2005 but, I have to deploy the web app with a SQL Server 2000 and, when executing that query, I get his error:
"System.Data.SqlClient.SqlException: The column prefix 't0' does not match with a table name or alias name used in the query."
I have mor... | after several testing and review the DB, I found that the problem was a **legacy table** I was working on: that table has **"text" type fields**. Also, I had to **remove** some "**Distinct**" instructions in a nested query I had.
I found [this](http://msdn.microsoft.com/en-us/library/bb399342.aspx) and, after review t... | My Linq statement worked on SQL2008 but broke with the exact same error message on SQL2000.
Had a very similar Linq query that worked on both, the only real difference was that before calling .ToList() I called the .OrderBy() clause.
Ex:
var query = from t1 in table1 ...
...;
list = query.OrderBy(o => o.Field).ToList(... | LINQ Incompatibility Issue with SQL Server 2000 | [
"",
"sql",
"linq",
"sql-server-2000",
""
] |
I would like to call `FindLast` on a collection which implements `IEnumerable`, but `FindLast` is only available for `List`. What is the best solution? | The equivalent to:
```
var last = list.FindLast(predicate);
```
is
```
var last = sequence.Where(predicate).LastOrDefault();
```
(The latter will have to check *all* items in the sequence, however...)
Effectively the "Where()" is the Find part, and the "Last()" is the Last part of "FindLast" respectively. Similarl... | How about with LINQ-to-Objects:
```
var item = data.LastOrDefault(x=>x.Whatever == "abc"); // etc
```
If you only have C# 2, you can use a utility method instead:
```
using System;
using System.Collections.Generic;
static class Program {
static void Main() {
int[] data = { 1, 2, 3, 4, 5, 6 };
in... | FindLast on IEnumerable | [
"",
"c#",
"ienumerable",
"ilist",
""
] |
With valid HTML the following finds the object as expected in all browsers but gets NULL in IE (6 & 7).
```
$(document).ready(function() {
alert( '$(.rollover):\n' + $('.rollover'));
});
```
I've tried by switching it to something simpler like $('a') but I always get NULL in IE.
**Update:**
After running the pag... | If you're having $ conflicts there are many way to avoid this as documented [here](http://docs.jquery.com/Using_jQuery_with_Other_Libraries). | It seems that it is AjaxCFC's JavaScript includes that are causing a problem, more specifically the ajaxCFC util.js which seems to define it's own $.
Moving those includes before that of the JQuery lib fixed the above issues I was having. | Why isn't jQuery $('.classname') working in IE? | [
"",
"javascript",
"jquery",
""
] |
I've written the following routine to manually traverse through a directory and calculate its size in C#/.NET:
```
protected static float CalculateFolderSize(string folder)
{
float folderSize = 0.0f;
try
{
//Checks if the path is valid or not
if (!Directory.Exists(folder))
retur... | I do not believe there is a Win32 API to calculate the space consumed by a directory, although I stand to be corrected on this. If there were then I would assume Explorer would use it. If you get the Properties of a large directory in Explorer, the time it takes to give you the folder size is proportional to the number... | No, this looks like the [recommended way](https://msdn.microsoft.com/en-us/library/system.io.directory(v=vs.100).aspx) to calculate directory size, the relevent method included below:
```
public static long DirSize(DirectoryInfo d)
{
long size = 0;
// Add file sizes.
FileInfo[] fis = d.GetFiles();... | What's the best way to calculate the size of a directory in .NET? | [
"",
"c#",
".net",
"windows",
""
] |
How can I create a Java/Swing text component that is both styled and has a custom font? I want to highlight a small portion of the text in red, but at the same time use a custom (embedded via `Font.createFont`) font. JLabel accepts HTML text, which allows me to highlight a portion of the text, but it ignores font setti... | OK, I see the problem better now.
After checking some Swing source code, it is clear you cannot use the `DefaultStyledDocument` and have it use a physical font (one you created yourself with `createFont`) out of the box.
However, what I think you could do is implement your own `StyleContext` this way:
```
public cla... | jfpoilpret's solution worked perfectly! For posterity's sake, here's a working code snippet:
```
JTextPane textPane = new JTextPane();
textPane.setStyledDocument(new DefaultStyledDocument(new StyleContext() {
@Override
public Font getFont(AttributeSet attr) {
return myCustomFont;
... | How can I create a Java/Swing text component that is both styled and has a custom font? | [
"",
"java",
"swing",
"fonts",
""
] |
I am not sure what the problem is but I keep receiving this error when I try to use a while statement in my code.
> Invalid token 'while' in class,
> struct, or interface member
> declaration
I want to use a while loop to have something continuously update while a statement is true.
The rest of my code is rather lon... | Based on the error, it sounds like the compiler thinks this code is typed directly in the body of a class/struct/interface declaration. Statements while/if/for/etc ... must appear with in a method.
Try moving this code into a method to fix the problem. If it's in a method, you likely have a mismatched brace problem. | There's nothing wrong with the while, it's something above it that's the problem.
Check for mismatched braces and semicolons in a comment or something like that. | Invalid token 'while' in class, struct, or interface member declaration in very simple code | [
"",
"c#",
"loops",
"while-loop",
""
] |
I need to write a simple command-line application in Java. It would be nice to use a library that takes care of parsing commands and takes care of things like flags and optional/mandatory parameters...
**UPDATE**
Something that has built-in TAB completion would be particularly great. | I've used the [Apache Commons CLI library](http://commons.apache.org/cli/) for command-line argument parsing. It's fairly easy to use and has [reasonably good documentation](http://commons.apache.org/cli/introduction.html).
Which library you choose probably comes down to which style of options you prefer ("--gnu-style... | [JLine](https://github.com/jline/jline3/) looks helpful.
> JLine is a Java library for handling console input. It is similar in functionality to BSD editline and GNU readline. People familiar with the readline/editline capabilities for modern shells (such as bash and tcsh) will find most of the command editing feature... | Are there good Java libraries that facilitate building command-line applications? | [
"",
"java",
"shell",
"command-line",
"interactive",
""
] |
Alright, so I'm trying out C++ for the first time, as it looks like I'll have to use it for an upcoming course in college. I have a couple years of programming under my belt, but not much in the non-garbage-collected world.
I have a class, a Node for use in a doubly linked list. So basically it has a value and two poi... | First of all, I'm not really sure how the objective of the exercise should be understood. How deep should the copy be? In a solution like yours, `this->next->next` and `other.next->next` would be still the same thing. Should this object also be duplicated? And the rest of the list? Where does it end? One could of cours... | Usually "deep copy" involves traversing the data structure and copying the entire thing. In your case, given a Node, make a complete copy of the list. | Newbie question about manual memory management and deep copying | [
"",
"c++",
"memory-management",
"deep-copy",
""
] |
Im runing mySQL in a server where i need to drop tons of databases (after some testing with the server). All databases that i need to drop have the same prefix "Whatever\_".
After the prefix, the names are random. So you have your Whatever\_something, Whatever\_232, Whatever\_blabla, .... , Whatever\_imthelast.
I wil... | The basic idea is to run "show tables" in your database, and use the results from that to select the
tables you want. I don't think MySQL lets you do anything with the resultset from "show tables",
but I'm probably wrong.
Here's a quick-and-dirty solution using the shell:
```
mysql -u your_user -D your_database_name ... | The principle of the answer by **scraimer** is correct, but since the question was about dropping a database not a table in a database, the correct command should be:
```
mysql -u your_username -p'your password' -e 'show databases'
| grep Whatever_*
| xargs -I "@@" mysql -u your_username -p'your password' -e "DROP d... | Drop MySQL databases matching some wildcard? | [
"",
"mysql",
"sql",
""
] |
Using a DB with C++ is a real mess and it was refreshing when I moved to Java to be able to use a unified system to abstract the whole layer away (aka Hibernate).
There are a couple of C++ abstract layers for DB's out there but they are usually vendor specific and only a thin layer that wraps the real C API. Has anybo... | I don't know of any C++ library like Hibernate, but certainly there are non-vendor specific libs: [SOCI](http://sourceforge.net/projects/soci/) and [DTL](http://dtemplatelib.sourceforge.net/) | I feel your pain. You'll quickly be using separate libraries for database access, XML processing, threading, and everything else applications commonly need. For this reason I often use Qt, which provides most common functionality often need in programs (database access, XML processing, threading, GUI widgets, etc.). Th... | Hibernate like layer for C++ | [
"",
"c++",
"hibernate",
"persistence",
"freeze-thaw",
""
] |
I feel like I am always reinventing the wheel for each application when it needs to load/save general settings to an xml file. What is the best way to manage basic application settings that the user can adjust and need to be saved/restored? | I like the use of [custom configuration sections](http://www.renevo.com/blogs/dotnet/archive/2009/01/08/custom-configuration-sections-in-application-config-files.aspx) in .config files coupled with [loading external .config](http://www.renevo.com/blogs/dotnet/archive/2008/01/31/loading-config-files-from-non-default-loc... | Are you using Visual Studio? There's a built-in settings manager and I find it works well for most situations. Just don't forget to call `Settings.Save()` before the application quits. | C# Settings Management | [
"",
"c#",
"xml",
"settings",
""
] |
I am writing an application in Java using Swing. I am trying to implement functionality to save and load simulation states for at simulation i am running. The entire simulation is kept as an object, disconnected from Swing. I am trying to serialize my Simulation class with this code:
```
public void saveSimulationStat... | Interesting post from Chen:
[When debugging a stack overflow, you want to focus on the repeating recursive part](https://web.archive.org/web/20140424233104/http://blogs.msdn.com/b/oldnewthing/archive/2009/01/07/9286576.aspx)
In your case:
```
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:... | You should consider reimplementing the `writeObject` / `readObject` methods of your Simulation class in order to serialize only the relevant data (and not the entire contained object structure by default) or tagging transient your not to be serialized objects.
You can also use the `Externalizable` interface if needed.
... | StackOverflowError when serializing an object in Java | [
"",
"java",
"swing",
"serialization",
"stack-overflow",
""
] |
I have a series of interlinked web pages, and I want to restrict access to these pages by asking the user to provide a login and password. However, my hosting account currently does not provide any facility for server side scripting - is there any way I can accomplish this objective using only client side scripts?
I w... | There is no way to create a secure clientside script. If the user has access to it, it's insecure.
If your host is running apache you can secure folders using .htaccess, on IIS you can do the same through directory security. | Below is a **working solution to this problem** that uses encryption, which I implemented myself.
A few users here have suggested using an encryption-based approach to client-side password protection. I needed this functionality too, so I implemented it myself. The password is hashed using PBKDF2 and then used to encr... | Is there a way to password protect HTML pages without using a server side language? | [
"",
"javascript",
"html",
"client",
"passwords",
""
] |
I am writing my form validation class using CodeIgniter. Is there any way so that I can get error messages in name value pair? For example, in a sample form there are four fields: `user_name`, `password`, `password_conf`, and `timezone`. Among them `user_name` and `password` validation has failed after executing the fo... | I have found one way myself by looking into the CodeIgniter code:
I have extended the library CI\_Form\_validation like: -
```
class MY_Form_validation extends CI_Form_validation
{
public function getErrorsArray()
{
return $this->_error_array;
}
}
```
I know, this is a hack, but will serve my need... | You can simply use,
`$this->form_validation->error_array();`
This is from the [class reference documentation](https://www.codeigniter.com/userguide3/libraries/form_validation.html#class-reference) of CodeIgniter. | CodeIgniter Form Validation - Get the Result as "array" Instead of "string" | [
"",
"php",
"codeigniter",
""
] |
Does anyone know what advantages (memory/speed) there are by using a class generated by the XSD tool to explore a deserialized XML file as opposed to XPATH? | I'd say the advantage is that you get a strongly typed class which is more convenient to use, and also the constructor for the class will throw an exception if the XML data in the file is invalid for creating the object, so you get a minimal data validation for free. | If you don't want to write boilerplate code, and you need to check ANY values of your XML on the way through, you can't go wrong with the XSD.exe generated classes. | DeSerializing an XML file to a C# class | [
"",
"c#",
"xml",
"xsd.exe",
""
] |
I am having trouble with [FxCop warning CA1006](http://msdn.microsoft.com/en-us/library/ms182144.aspx "FxCop warning CA1006"), Microsoft.Design "DoNotNestGenericTypesInMemberSignatures". Specifically, I am designing a `ReportCollection<T>` class that inherits from `ReadOnlyCollection<Report<T>>`, and its `public` const... | I agree, another good time to ignore this rule is when you need to say:
```
Func<IEnumerable<T>>
```
of course you could use the non-generic IEnumerable, but then any type can be used as long as it implements IEnumerable (non-generic). The purpose of generics (in part) is to restrict the types that are permisable to ... | I would take FxCop's warnings as if they were suggestions from an extremely anal-retentive coworker. It's perfectly ok to ignore (suppress) some of the things it suggests. | Are there any good workarounds for FxCop warning CA1006? | [
"",
"c#",
".net",
"fxcop",
""
] |
This is what I understand about IDisposable and finalizers from "CLR via C#", "Effective C#" and other resources:
* IDisposable is for cleaning up managed and unmanaged resources deterministically.
* Classes that are responsible for unmanaged resources (e.g. file handles) should implement IDisposable and provide a fin... | If the unmanaged resource is released only on application exit you don't even need to worry with a finalizer since the process unload should deal with this for you anyway.
If you have multiple app domains and you want to deal with an app domain unload that's one possible issue but possibly one you don't need to care a... | I'd first mention that Object Oriented design patterns and their consequences do not always influence every language decision, even in Object Oriented languages. You can certainly find classic design patterns that are easier to implement in one language (Smalltalk) as opposed to another (C++).
That being said, I'm not... | Singleton with finalizer but not IDisposable | [
"",
"c#",
".net",
"singleton",
"idisposable",
""
] |
I have 3 variables like this:
$first = 2;
$second = 5;
$operation = '\*';
how can I programaticly assign the solution to this math problem to the $answer variable?
I have tried eval(), but that does not work. | eval() should work perfectly fine for something like this. Remember that eval() returns NULL though, unless you tell it to return something.
```
<?php
$first = 3;
$second = 4;
$operation = "*";
$answer = eval('return '.$first.$operation.$second.';');
echo $answer;
?>
``` | ```
function add($a, $b) {
return $a + $b;
}
function multiply($a, $b) {
return $a * $b;
}
function divide($a, $b) {
return $a / $b;
}
$operations = array(
'+' => 'add',
'*' => 'multiply',
'/' => 'divide',
);
$a = 2;
$b = 5;
$operation = '*';
echo $operations[$operation]($a, $b);
``` | Preforming math stored in variables | [
"",
"php",
""
] |
I need a CSVParser class file
A Class File which parses csv and returns a dataSet as a result ASP.Net | I'm pretty sure that [CSVReader](http://www.codeproject.com/KB/database/CsvReader.aspx) (CodeProject) can read to `DataTable`.
```
DataTable table = new DataTable();
// set up schema... (Columns.Add)
using(TextReader text = File.OpenText(path))
using(CsvReader csv = new CsvReader(text, ... | Simple google gives plenty of [results](http://windowsclient.net/blogs/faqs/archive/2006/05/30/how-do-i-load-a-csv-file-into-a-datatable.aspx). | Howto parse csv and returns a dataSet as a result | [
"",
"c#",
"asp.net",
"csv",
"parsing",
""
] |
Currentaly I am using a gridView and on RowCommand event of gridview the details of selected row are displayed below the Gridview. But now I have to display the details just below the row clicked. Means it will be displayed in between the selected row and next row of it. The gridview code is as
```
<asp:GridView I... | Please refer to the following artice, that describes exactly what you want:
[DataGrid and Details Using
ASP.NET, C#, and JavaScript (Expand / Collapse Rows)](http://www.progtalk.com/ViewArticle.aspx?ArticleID=1) | You probably want to use a Repeater and build the table yourself. I don't think that you'll be able to get a GridView to work as you can only control what goes in each row and what you want to do is alternate rows between general and detailed information. More information on how to connect it to your data source and ha... | Is it possible to display a panel or div in between gridview rows on RowCommand event | [
"",
"c#",
"asp.net",
"gridview",
""
] |
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?
```
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
``` | You can reload a module when it has already been imported by using [`importlib.reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload):
```
from importlib import reload # Python 3.4+
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
```
In Python 2,... | In Python 3.0–3.3 you would use: [`imp.reload(module)`](http://docs.python.org/3.3/library/imp.html?highlight=imp#imp.reload)
The [BDFL](http://docs.python.org/3.3/glossary.html#term-bdfl) has [answered](http://mail.python.org/pipermail/edu-sig/2008-February/008421.html) this question.
However, [`imp` was deprecated ... | How do I unload (reload) a Python module? | [
"",
"python",
"module",
"reload",
"python-import",
""
] |
I can drop a table if it exists using the following code but do not know how to do the same with a constraint:
```
IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'TableName') AND type = (N'U')) DROP TABLE TableName
go
```
I also add the constraint using this code:
```
ALTER TABLE [dbo].[TableName] ... | The more simple solution is provided in [Eric Isaacs's](https://stackoverflow.com/a/13186918) answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this:
```
IF EXISTS (SELECT *
FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'FK_Table... | This is a lot simpler than the current proposed solution:
```
IF (OBJECT_ID('dbo.FK_ConstraintName', 'F') IS NOT NULL)
BEGIN
ALTER TABLE dbo.TableName DROP CONSTRAINT FK_ConstraintName
END
```
If you need to drop another type of constraint, these are the applicable codes to pass into the OBJECT\_ID() function in ... | How do I drop a foreign key constraint only if it exists in sql server? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
Is it possible to use a C# assembly from Clarion? If not. Is it possible to run a simple console application written in C# and read the output from it back into Clarion? In both cases, how would you do it? In the case of the assembly, would you have to do something special with it for Clarion to get access to it? In bo... | Clarion is a programming language. Don't know it myself. Parts of the old system where I work is made with it, and we are working on porting it to C# .NET. So for a while they have to live side by side. We found a work around so it is no longer needed though. But thanks for info :) Maybe we will need it further down th... | Unless you need to display a .Net UserControl in your clarion program I would recommend using the technique described here:
Robert Giesecke - [C# Project Template for Unmanaged Exports](http://sites.google.com/site/robertgiesecke/Home/uploads/csharpprojecttemplateforunmanagedexports)
On the Clarion side you then just... | Clarion: Possible to use a C# Assembly? | [
"",
"c#",
"dll",
"clarion",
""
] |
I need to write a query that will group a large number of records by periods of time from Year to Hour.
My initial approach has been to decide the periods procedurally in C#, iterate through each and run the SQL to get the data for that period, building up the dataset as I go.
```
SELECT Sum(someValues)
FROM table1
W... | As with anything performance related **Measure**
Checking the query plan up for the second approach will tell you any obvious problems in advance (a full table scan when you know one is not needed) but there is no substitute for measuring. In SQL performance testing that measurement should be done with appropriate siz... | If you put a formula into the field part of a comparison, **you get a table scan**.
The index is on field, not on datepart(field), **so ALL fields must be calculated** - so I think your hunch is right. | SQL Group By Year, Month, Week, Day, Hour SQL vs Procedural Performance | [
"",
"sql",
"sql-server",
"performance",
""
] |
I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.
As I was googling, it turned out, that mod\_python, for some reasons, will not be able to support python 3.0.
The only othe... | Binaries for Windows are now being supplied from the mod\_wsgi site for Apache 2.2 and Python 2.6 and 3.0. Python 3.0 is only supported for mod\_wsgi 3.0 onwards. See:
<http://code.google.com/p/modwsgi/downloads/list>
---
UPDATE July 2015
The above link is no longer valid. Instead see:
* <https://github.com/Graham... | I would like to find either 2.6 (preferable) or 3.0 (okay) Windows binaries myself, and have looked into this a bit.
There are Windows build steps for mod\_wsgi buried deep in the Google Group for it. I think they're out of date; only one person appears to have ever done it and told the world how well it worked out. T... | Where to get/How to build Windows binary of mod_wsgi with python 3.0 support? | [
"",
"python",
"apache",
"visual-c++",
"mod-wsgi",
""
] |
Is there any way to convert a string to Title case, using JSTL tags?
Thanks in Advance. | An alternative to transforming the string on the server is to [let CSS do the work](http://www.w3.org/TR/CSS2/text.html#caps-prop):
```
text-transform: capitalize
``` | An idea:
In a class, create a simple method that uses the WordUtils from Apache Commons Lang that will manipulate your String:
```
import org.apache.commons.lang.WordUtils;
...
public static String titleCase(String input){
return WordUtils.capitalize(input);;
}
```
And now, create your own tag (in a function.tl... | converting strings to Title case in JSTL | [
"",
"java",
"string",
"jstl",
""
] |
Digital commercial products that customers pay for download link.
I have put all the zipped files (products) outside of web document root and buyers download them via a php script which is integrated with paypal IPN to make sure the downloader is a paying buyer.
Sort of like: <http://www.mysite.com/download.php?buyer... | You'd be better off just using [`readfile()`](http://www.php.net/readfile). Unless you have ignore\_user\_abort on, then the script will terminate automatically if the user cancels anyway.
If you're still having problems, load the file up in a hex editor and compare the first few characters and the last few characters... | I would suggest changing this:
```
$fp = @fopen($path,"rb");
if ($fp) {
while(!feof($fp)) {
print(fread($fp, 1024*8));
flush();
if (connection_status()!=0) {
@fclose($fp);
die();
}
}
@fclose($fp);
}
```
to this
```
readfile($path);
```
You can find more info on readfile [here](http... | What's the best way to supply download of a digital product in PHP? | [
"",
"php",
"download",
""
] |
Ok I'm at my work this friday setting up a table that will have data in it that will come from a separate file called values.php. When I write it like this, the divs turn up blank. I think I have the "include" written wrong, does an absolute path not work?
```
<?php include('http://www.nextadvisor.com/credit_report_se... | The type of include you are trying to do is blocked by default, not to say that it is dangerous. You are trying to include a remote file.
If your script is in the same machine as the "values.php" you should use an absolute path similar to "/var/www/nextadvisor.com/credit\_report\_services/values.php" or a relative pat... | Since you're using a URL, PHP will send a request to the server for the file, and the server will parse it just as it would if a browser requested it. What you probably want to do is use a path relative to the script for your include. If the file you want to include is in the same folder, just use
`include('values.ph... | Absolute paths for PHP include | [
"",
"php",
"include",
""
] |
It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value?
To read:
```
public static String GetSettings(SettingsType type, SectionType section)
{
XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH));
XmlDocument docume... | You don't need an "update" method - setting the InnerText property updates it. However, it only applies the update in memory. You *do* need to rewrite the whole file though - you can't just update a small part of it (at least, not without a *lot* of work and no out-of-the-box support). | `XmlDocument.Load` has an overload that will take the filename directly so there is no need for the reader.
Similarly when you are done `XmlDocument.Save` will take a filename to which it will save the document. | How to Update a XML Node? | [
"",
"c#",
"asp.net",
"xml",
""
] |
I need to use a query which will pull data from a field when it is less then 4 words, is this possible and if so could you give some pointers? I suppose if not possible it could cycle through the results until it found one which was 3 words and then end the while statement when it has found one. | ```
SELECT column FROM table where LENGTH(column) - LENGTH(REPLACE(column, ' ', ''))+1 < 4
```
[Credits and full explanation](http://www.mwasif.com/2008/12/count-number-of-words-in-a-mysql-column/)
Here [Regexp Solution](http://www.experts-exchange.com/Database/MySQL/Q_22682620.html).
```
select * from TABLE where c... | Calling functions in a select on a per-record basis is almost always a bad idea in terms of performance - disk space is usually much 'cheaper' than CPU capacity (I enclose that in quotes since I'm not talking about dollar costs).
Most databases tend to be "more read than write" as my DBA mentor once told me; the ideal... | PHP MySql Where Field = <4 Words | [
"",
"php",
"mysql",
""
] |
> **Possible Duplicate:**
> [Could you explain STA and MTA?](https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta)
> All ThreadPool threads are in the
> multithreaded apartment.
--As per the MSDN
What does that mean? I am really concerned with what the difference between the multi vs single thr... | STA (single-threaded apartment) and MTA (multi-threaded apartment) are to do with [COM](http://msdn.microsoft.com/en-us/library/ms690156(VS.85).aspx). COM components can be designed to be accessed by a single thread, in which case it they are hosted in an [STA](http://msdn.microsoft.com/en-us/library/ms680112.aspx), or... | In actuality, STAs and MTAs have an impact on .NET code. See Chris Brumme's blog entry for way more detail then you probably need:
<https://devblogs.microsoft.com/cbrumme/apartments-and-pumping-in-the-clr/>
It's really important to understand how STAs pump messages in .NET. It does have consequences. | Single-Threaded Apartments vs Multi-Threaded Apartments | [
"",
"c#",
".net",
"multithreading",
"apartments",
""
] |
I currently have the query running on Postgres:
```
SELECT * FROM addenda.users WHERE users.username LIKE '%\_'
```
But rather then returning just entries ending in an underscore, I get all results back, regardless of whether it contains an underscore or not.
Running the query below returns a username which is just ... | Is your backslash not getting through to PostgreSQL? If you're passing the string through another layer that treats the backslash as an escape character (e.g. a Java String), then that layer may be removing the backslash, and you might need to escape your backslash for that layer.
Do you have any more single character... | `"_"` is the single-character wildcard in most SQL variants. You HAVE to escape it if you want to match an actual `"_"` character. | Why does my query with LIKE '%\_' return all rows and not just those ending in an underscore? | [
"",
"sql",
"postgresql",
""
] |
**bpp** = bits per pixel, so 32bpp means 8/8/8/8 for R/G/B/A.
Like .NET has an enum for these "System.Drawing.Imaging.PixelFormat".
Now once I have a **Bitmap** or **Image** object with my graphics, **how would I save it** to a file / what format would I use?
What image file format (JPEG/GIF/PNG) supports low bit-de... | Try this:
```
ImageCodecInfo pngCodec = ImageCodecInfo.GetImageEncoders().Where(codec => codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault();
if (pngCodec != null)
{
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
myImage.... | I don't think the other's answering tested their code as GDI+ PNG does not support the Encoder.BitDepth EncoderParameter. In fact, the only Codec which does is TIFF.
You need to change your image's PixelFormat before saving in order to have any effect out the output. This won't always produce the PixelFormat you expec... | Generate image file with low bit depths? | [
"",
"c#",
"vb.net",
"bitmap",
"imaging",
""
] |
Is there a way to convert variable names to strings in javascript? To be more specific:
```
var a = 1, b = 2, c = 'hello';
var array = [a, b, c];
```
Now at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it t... | Use a Javascript object literal:
```
var obj = {
a: 1,
b: 2,
c: 'hello'
};
```
You can then traverse it like this:
```
for (var key in obj){
console.log(key, obj[key]);
}
```
And access properties on the object like this:
```
console.log(obj.a, obj.c);
``` | What you could do is something like:
```
var hash = {};
hash.a = 1;
hash.b = 2;
hash.c = 'hello';
for(key in hash) {
// key would be 'a' and hash[key] would be 1, and so on.
}
``` | How to make a variable addressable by name as string in JavaScript? | [
"",
"javascript",
""
] |
This question is inspired by Jon Skeet's answer:
[Is there a c# equivalent to c++'s access-modifier regions](https://stackoverflow.com/questions/431091/is-there-a-c-equivalent-to-cs-access-modifier-regions#431105)
He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that th... | Here is a classic example from the C# language spec (Section 10.5.5)
```
class Test
{
static int a = b + 1;
static int b = a + 1;
static void Main() {
Console.WriteLine("a = {0}, b = {1}", a, b);
}
}
```
This is a completely valid program and as written (a = 1, b =2). However if you swap the o... | Yeah, it does matter when interfacing with unmanaged code. | Does the order of fields in C# matter? | [
"",
"c#",
"field",
"specifications",
""
] |
I recently [read this thread on MSDN](http://social.msdn.microsoft.com/Forums/en-US/clr/thread/b18b0a27-e2fd-445a-bcb3-22a315cd6f0d/). So I was thinking of using a lambda expression as a way of calling EndInvoke just as a way to make sure everything is nice and tidy.
Which would be more correct?
Example 1:
```
Actio... | Your 2nd example is slightly more efficient because the "method" delegate instance doesn't have to be captured in the closure. I doubt you'd ever notice. | I don't know if this was possible way back in Jan '09, but certainly now you can just write this:
```
method.BeginInvoke(5, method.EndInvoke, null);
``` | The proper way to end a BeginInvoke? | [
"",
"c#",
"lambda",
""
] |
I am writing a web application using PHP. I want to use the MVC pattern for this, and decided to go with [CodeIgniter](http://codeigniter.com/). My application will have some pages which will require authentication, and some pages won't. I want to design this in a very generic way, so that there should be no code dupli... | Write a custom library that you can autoload in your code igniter app on every page view. It should have functions that:
* Authenticate the user ie. check if a user is logged in or not
* Log you in ie. set a session variable or something
* Log you out
Then in your controller classes you can do a call to the authentic... | "Ion Auth" is lean, well-programmed, somewhat widely used and is actively maintained.
<http://github.com/benedmunds/CodeIgniter-Ion-Auth> | User authentication with CodeIgniter | [
"",
"php",
"codeigniter",
"authentication",
""
] |
I need a library that allows me to do email operations(e.g Sent/Receive mail) in Gmail using Java. | Have you seen [g4j - GMail API for Java](http://g4j.sourceforge.net/)?
> GMailer API for Java (g4j) is set of
> API that allows Java programmer to
> communicate to GMail. With G4J
> programmers can made Java based
> application that based on huge storage
> of GMail. | You can use the Javamail for that. The thing to remember is that GMail uses SMTPS not SMTP.
```
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SimpleSSLMail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT... | Access gmail from Java | [
"",
"java",
"gmail",
""
] |
I am not that familiar with Javascript, and am looking for the function that returns the UNICODE value of a character, and given the UNICODE value, returns the string equivalent. I'm sure there is something simple, but I don't see it.
Example:
* ASC("A") = 65
* CHR(65) = "A"
* ASC("ਔ") = 2580
* CHR(2580) = "ਔ" | Have a look at:
```
String.fromCharCode(64)
```
and
```
String.prototype.charCodeAt(0)
```
The first must be called on the String **class** (literally `String.fromCharCode...`) and will return "@" (for 64). The second should be run on a String **instance** or **primitive** (e.g., `"@@@".charCodeAt...`) and returns ... | Because [JavaScript uses UCS-2 internally](http://mathiasbynens.be/notes/javascript-encoding), `String.fromCharCode(codePoint)` won’t work for supplementary Unicode characters. If `codePoint` is `119558` (`0x1D306`, for the `''` character), for example.
If you want to create a string based on a non-BMP Unicode code po... | What is an easy way to call Asc() and Chr() in JavaScript for Unicode values? | [
"",
"javascript",
"unicode",
""
] |
i have a module (a single .py file, actually), with a class called HashedDir.
when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.
Eg:
```
h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] #... | There are two kinds of variables in a class:
* class variables, defined at the class level, and common to all instances
* instance variables, defined within a class method (usually `__init__`) and qualified by the instance (usually `self.`).
Example
```
class SomeClass( object ):
classVariable = 0
def __init... | Is it fileList you're talking about? You have it as a class variable, to make it an instance variable you need to do:
```
self.fileList = {'files': [], 'dirs': []}
```
in you \_\_ init \_\_ function. | How come my class is behaving like a static class? | [
"",
"python",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.