Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've been told wsgi is the way to go and not mod\_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc? | Apache+mod\_wsgi is a common choice.
Here's a simple example vhost, setup up to map any requests for /wsgi/something to the application (which can then look at PATH\_INFO to choose an action, or however you are doing your dispatching). The root URL '/' is also routed to the WSGI application.
```
LoadModule wsgi_module /usr/local/lib/mod_wsgi.so
...
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /www/example/htdocs
WSGIScriptAliasMatch ^/$ /www/example/application.py
WSGIScriptAlias /wsgi /www/example/application.py
</VirtualHost>
```
You can use the WSGIProcessGroup directive to separate handlers for different vhosts if you like. If you need vhosts' scripts to be run under different users you'll need to use WSGIDaemonProcess instead of the embedded Python interpreter.
application.py would, when run, leave your WSGI callable in the global ‘application’ variable. You can also add a run-as-main footer for compatibility with old-school CGI:
```
#!/usr/bin/env python
from mymodule import MyApplication
application= MyApplication()
if __name__=='main':
import wsgiref.handlers
wsgiref.handlers.CGIHandler().run(application)
``` | I'd recommend Nginx for the web server. Fast and easy to set up.
You'd probably want to have one unix user per vhost - so every home directory holds its own application, python environment and server configuration. This allows you to restart a particular app safely, simply by killing worker processes that your vhost owns.
Just a tip, hope it helps. | How would you set up a python web server with multiple vhosts? | [
"",
"python",
"webserver",
"environment",
"wsgi",
""
] |
I have this piece of code I'm trying to get to display but no matter how I do it I just don't get any response or error whatsoever.
```
<?php
$day = array("Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo");
//$month[]= array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
function today(){
$d = date("N");
switch ($d){
case 1:
echo $day[1];
break;
case 2:
echo $day[2];
break;
case 3:
echo $day[3];
break;
case 4:
echo $day[4];
break;
case 5:
echo $day[5];
break;
case 6:
echo $day[6];
break;
case 7:
echo $day[7];
break;
}
}
today();
?>
```
Can anyone see any obvious mistake I might be making and haven't noticed? | To avoid using global variables (which is [often-times a bad idea](http://en.wikipedia.org/wiki/Global_variable)). You can just pass the variable in to the function.
Thus change the function declaration to
```
function today($day)
```
and the last function call to
```
today($day);
```
Note that the two $day's are not the same.
The `function today($day)` is simply saying that every $day variable within this function will contain the value that is passed in as this argument. It is **not** the array you declared. Therefore you can change this to whatever valid php variable name you want, along with all of the $days within the function scope and the result will remain the same.
The `today($day)` is saying pass in the `Array` $day that you declared before into the function `today`. | You need to add
```
global $day;
```
At the top of your function.
Check out the PHP manual on [`variable scoping`](https://www.php.net/global) for more. In addition to that, as [The.Anti.9 mentioned](https://stackoverflow.com/questions/523113/php-no-response-issue/523118#523118), you could just do:
```
$days = array("Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo");
function today() {
global $days;
echo $days[date("N")-1];
}
today();
``` | PHP No response Issue | [
"",
"php",
"no-response",
""
] |
The closest I've seen in the PHP docs, is to fread() a given length, but that doesnt specify which line to start from. Any other suggestions? | You not going to be able to read starting from line X because lines can be of arbitrary length. So you will have to read from the start counting the number of lines read to get to line X. For example:
```
<?php
$f = fopen('sample.txt', 'r');
$lineNo = 0;
$startLine = 3;
$endLine = 6;
while ($line = fgets($f)) {
$lineNo++;
if ($lineNo >= $startLine) {
echo $line;
}
if ($lineNo == $endLine) {
break;
}
}
fclose($f);
``` | Yes, you can do that easily with [`SplFileObject::seek`](http://de.php.net/manual/en/splfileobject.seek.php)
```
$file = new SplFileObject('filename.txt');
$file->seek(1000);
for($i = 0; !$file->eof() && $i < 1000; $i++) {
echo $file->current();
$file->next();
}
```
This is a method from the [SeekableIterator](http://de.php.net/manual/en/class.seekableiterator.php) interface and not to be confused with `fseek`.
And because SplFileObject is iterable you can do it even easier with a [`LimitIterator`](http://de.php.net/manual/en/class.limititerator.php):
```
$file = new SplFileObject('longFile.txt');
$fileIterator = new LimitIterator($file, 1000, 2000);
foreach($fileIterator as $line) {
echo $line, PHP_EOL;
}
```
Again, this is zero-based, so it's line 1001 to 2001. | How do I open a file from line X to line Y in PHP? | [
"",
"php",
"fopen",
""
] |
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read. Here is an example:
```
var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
.OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
a => a);
```
Some question this naming, and would prefer to see long typed out names, like this:
```
var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
.OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
theInfoId2 => theInfoId2);
```
Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.
**Without getting caught up in the silly naming examples I used above**, what is the general consensus on Lambda variable names? To short name, or not to short name? | The way I usualy do it depends on the collection you're enumerating over. If the name of the collection implies what type the lambda parameter will be, then I just go with the single letter, however if the collection isn't as descriptive, then I'll use a word.
IE:
```
myCollection.Where(person =>....); //non descriptive collection name
myPeopleCollection.Where(p=>...); // descriptive collection name
``` | I try to use single-word but meaningful names. So I would *tend* to use "person" rather than "p" but wouldn't go for "newlyAddedPerson".
This goes for query expressions as well - I may well violate this in quick throwaway examples, but I don't generally like:
```
from p in source
where p.Age > 10
select p.Name;
```
I'd far rather see
```
from person in source
where person.Age > 10
select person.Name;
``` | Lambda variable names - to short name, or not to short name? | [
"",
"c#",
".net",
"naming-conventions",
"lambda",
""
] |
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:
```
select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
```
There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.
You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ? | Dave Marke is right, but more generaly...
conditional join is answer to your question, try find some resources on web for example
<http://weblogs.sqlteam.com/jeffs/archive/2007/04/03/Conditional-Joins.aspx>
<http://bytes.com/groups/ms-sql/641690-difference-condition-join-where>
it is very powerful technique to make joins depending on data in tables | ```
select *
from T1
join T2
on T1.value = T2.value
and T1.booleancolumn = 1
where T2.value2 = 'variable2'
and T2.value3 = 'variable3';
``` | Join to a table only when column value is true | [
"",
"sql",
"sql-server",
""
] |
When declaring a template, I am used to having this kind of code:
```
template <class T>
```
But [in this question](https://stackoverflow.com/questions/498757/factory-method-returning-an-concrete-instantiation-of-a-c-template-class), they used:
```
template <unsigned int N>
```
I checked that it compiles. But what does it mean? Is it a non-type parameter? And if so, how can we have a template without any type parameter? | It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
```
unsigned int x = N;
```
In fact, we can create algorithms which evaluate at compile time (from [Wikipedia](http://en.wikipedia.org/wiki/Template_metaprogramming)):
```
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
``` | Yes, it is a non-type parameter. You can have several kinds of template parameters
* Type Parameters.
+ Types
+ Templates (only classes and alias templates, no functions or variable templates)
* Non-type Parameters
+ Pointers
+ References
+ Integral constant expressions
What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:
Template type parameter:
```
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
```
Template integer parameter:
```
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
```
Template pointer parameter (passing a pointer to a function)
```
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
```
Template reference parameter (passing an integer)
```
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
```
Template template parameter.
```
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
```
A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:
```
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
```
Syntactically, `template<>` is reserved to mark an explicit template specialization, instead of a template without parameters:
```
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};
``` | What does template <unsigned int N> mean? | [
"",
"c++",
"templates",
"non-type-template-parameter",
""
] |
I have a list of about a hundreds unique strings in C++, I need to check if a value exists in this list, but preferrably lightning fast.
I am currenly using a hash\_set with std::strings (since I could not get it to work with const char\*) like so:
```
stdext::hash_set<const std::string> _items;
_items.insert("LONG_NAME_A_WITH_SOMETHING");
_items.insert("LONG_NAME_A_WITH_SOMETHING_ELSE");
_items.insert("SHORTER_NAME");
_items.insert("SHORTER_NAME_SPECIAL");
stdext::hash_set<const std::string>::const_iterator it = _items.find( "SHORTER_NAME" ) );
if( it != _items.end() ) {
std::cout << "item exists" << std::endl;
}
```
Does anybody else have a good idea for a faster search method without building a complete hashtable myself?
---
The list is a fixed list of strings which will not change. It contains a list of names of elements which are affected by a certain bug and should be repaired on-the-fly when opened with a newer version.
I've built hashtables before using Aho-Corasick but I'm not really willing to add too much complexity.
---
I was amazed by the number of answers. I ended up testing a few methods for their performance and ended up using a combination of kirkus and Rob K.'s answers. I had tried a binary search before but I guess I had a small bug implementing it (how hard can it be...).
The results where shocking... I thought I had a fast implementation using a hash\_set... well, ends out I did not. Here's some statistics (and the eventual code):
> **Random lookup of 5 existing keys and 1 non-existant key, 50.000 times**
>
> My original algorithm took on average **18,62** seconds
> A lineair search took on average **2,49** seconds
> A binary search took on average **0,92** seconds.
> A search using a perfect hashtable generated by gperf took on average **0,51** seconds.
Here's the code I use now:
```
bool searchWithBinaryLookup(const std::string& strKey) {
static const char arrItems[][NUM_ITEMS] = { /* list of items */ };
/* Binary lookup */
int low, mid, high;
low = 0;
high = NUM_ITEMS;
while( low < high ) {
mid = (low + high) / 2;
if(arrAffectedSymbols[mid] > strKey) {
high = mid;
}
else if(arrAffectedSymbols[mid] < strKey) {
low = mid + 1;
}
else {
return true;
}
}
return false;
}
```
*NOTE: This is Microsoft VC++ so I'm not using the std::hash\_set from SGI.*
---
I did some tests this morning using gperf as [VardhanDotNet](https://stackoverflow.com/users/10958/vardhandotnet) suggested and this is quite a bit faster indeed. | If your list of strings are fixed at compile time, use gperf
<http://www.gnu.org/software/gperf/>
QUOTE:
gperf is a perfect hash function generator. For a given list of strings, it produces a hash function and hash table, in form of C or C++ code, for looking up a value depending on the input string. The hash function is perfect, which means that the hash table has no collisions, and the hash table lookup needs a single string comparison only.
The output of gperf is not governed by gpl or lgpl, afaik. | You could try a PATRICIA Trie if none of the standard containers meet your needs.
Worst-case lookup is bounded by the length of the string you're looking up. Also, strings share common prefixes so it is really easy on memory.So if you have lots of relatively short strings this could be beneficial.
[Check it out here.](http://en.wikipedia.org/wiki/Radix_tree)
Note: PATRICIA = Practical Algorithm to Retrieve Information Coded in Alphanumeric | Searching fast through a sorted list of strings in C++ | [
"",
"c++",
"visual-c++",
""
] |
Hey all. I have a server written in java using the ServerSocket and Socket classes.
I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.
What is the proper procedure to detect client disconnections, close the socket, and then accept new clients? | Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).
Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately. | The only safe way to detect the other end has gone is to send heartbeats periodically and have the other end to timeout based on a lack of a heartbeat. | How do you handle Socket Disconnecting in Java? | [
"",
"java",
"sockets",
""
] |
Is there a way to access the screen display's DPI settings in a Javascript function?
I am trying to position a HTML panel on the page and when the user's DPI is set to large (120), it throws the position off. I need to be able to know what the DPI is so I can adjust the position accordingly. | Firstly, to help with the possible (and very common) confusion with the term DPI (dots per inch):
DPI isn't exactly a part of "display settings". It's (mis)used in two different contexts:
1. The native pixels per inch of a display (or video). It determines how small the pixels are. You can have the same 1024x768 resolution on both a 14" laptop screen and a 17" LCD monitor. The former would roughly be 1280/14 = 91 DPI and the latter would roughly be 1280/17 = 75 DPI. The DPI of a screen is immutable; it can't be changed with display settings. [More...](http://en.wikipedia.org/wiki/Dots_per_inch#DPI_measurement_in_video_resolution)
2. The dots per inch painted on paper during printing. This is the number of side-by-side dots a printer/photocopier/fax machine can imprint within an inch of paper. Most printers can be set to print at a lower DPI, by just printing each dot as two, four, etc. dots. [More...](http://en.wikipedia.org/wiki/Dots_per_inch#DPI_measurement_in_printing)
When printing an image, there are many things that affect the final dimensions of the image on paper:
* The dimensions of the source image -- this is the amount of pixels or data there is.
* The DPI of the source image. This value determines how the dimensions should be interpreted when printing the image.
* If the source image doesn't have embedded DPI information (a JPEG can have one, a GIF never does), the program that's being used may have settings to specify a DPI. This could be an image viewer/editor or even a web browser.
* The zoom factor that's typically specified in a print dialog.
* The current DPI setting of the printer.
* The physical (max) DPI of the printer.
The bottom line is, the image that you're printing will effectively get resampled (reduced or enlarged) to match the final DPI that's used in the print process. Any of the parties involed may be causing this (the program, the print driver, the printer).
~~Now, coming back to your question. No, you can't determine the DPI of the screen, because it's not in software domain. It's a hardware domain term, describing how large a monitor a user could afford to buy.~~ **Update:** I initially wrote this answer back in 2009, with my understanding of the current technologies. As @thure pointed out, you can now (since 2012?) use the [window.matchMedia](https://developer.mozilla.org/en-US/docs/DOM/window.matchMedia) function to determine the DPI of the screen.
If you're trying to achieve precision in printing an HTML layout, as others have suggested, your CSS should use print dimensions like em, pt or pc instead of px. However, the final outcome might still depend on the browser using. If converting your HTML to PDF (or generating PDF from scratch) is an option for you, printing a PDF would give you the truest WYSIWYG both on screen and paper.
* [Misunderstandings about dpi](http://www.dpiphoto.eu/dpi.htm)
* [DPI, PPI, Pixels - Facts and Fallacies](http://www.unleash.com/knpepper/dpi/) | Looks like you can use the 'screen' DOM object in IE, its got properties for deviceXDPI, deviceYDPI, logicalXDPI, logicalYDPI.
<https://www.w3schools.com/jsref/obj_screen.asp>
Here's a solution from <http://www.webdeveloper.com/forum/showthread.php?t=175278>
(i havent tried it, seems like a total hack :)
Just create something 1 inch wide and measure it in pixels!
```
console.log(document.getElementById("dpi").offsetHeight);
```
```
#dpi {
height: 1in;
left: -100%;
position: absolute;
top: -100%;
width: 1in;
}
```
```
<div id="dpi"></div>
``` | How to access screen display’s DPI settings via javascript? | [
"",
"javascript",
"dpi",
"display-dpi",
""
] |
Is there anyway to have the var be of a nullable type?
This implicitly types i as an int, but what if I want a nullable int?
`var i = 0;`
Why not support this:
`var? i = 0;` | Why support it? If that's what you mean, you should say `var i = (int?)0;` instead.
(Well, you should probably just say `int? i = 0`, but for more complicated types, etc.) | `var` is typed implicitly by the expression or constant on the right hand side of the assignment. `var` in and of itself is not a type so `Nullable<var>` is not possible. | nullable var using implicit typing in c#? | [
"",
"c#",
".net-3.5",
"nullable",
"var",
""
] |
I'm looking to fill a text input with a time that the user can choose in 15 minute intervals. I know there are a few plugins out there. I was wondering if there was any “industry standard” plugin, or strong objective reasons to prefer a particular one in common scenarios. | I found [this plugin](http://labs.perifer.se/timedatepicker/) ([github repository](https://github.com/perifer/timePicker)) trumps the other one mentioned. It mimics Google Calendar's timepicker. | I tried a ton of timepicker and was not satisfied so I wrote [yet] another one. I think it works well. Also it is inspired from the datepicker so it looks like standard jQuery UI stuff.
The default minute increments is at 5 and can be set to 15 in the options.
<http://fgelinas.com/code/timepicker> | jQuery time picker | [
"",
"javascript",
"jquery",
"time",
""
] |
Hey! I am not trying to push my luck here but I have another c# question.
I have tried every possible event I found using google.
Here is the code:
```
private void Form1_OnClose()
{
MessageBox.Show("I was closed -2");
}
private void Form1_Exit(object sender, EventArgs evArgs)
{
MessageBox.Show("I was closed -1");
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBox.Show("I was closed 0");
}
private void Form1_Closed(object sender, EventArgs e)
{
MessageBox.Show("I was closed 1");
}
private void Form1_FormClosed(Object sender, FormClosedEventArgs e)
{
MessageBox.Show("I was closed 2");
}
```
Not one of these trigger anything when I either do Alt+f4 or click on the X button.
What am I doing wrong here? | You might be missing actual subscription code, which is something along these lines:
```
this.Closing += Form1_Closing;
```
Instead, try overriding *OnXXX* methods - this is the preferred way of doing things. | The error is likely that you aren't wiring the events at the right time. Check your program.cs file. It should look something like this:
```
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace Test
{
internal class Program
{
private static void Main(string[] args)
{
Form form = new Form2();
form.Closing += form_Closing;
Application.Run(form);
}
private static void form_Closing(object sender, CancelEventArgs e)
{
MessageBox.Show("Closing");
}
}
}
```
I just ran this and the event fired. | Catching the close event on a c# form | [
"",
"c#",
"forms",
""
] |
Is there a .NET library/tutorial available that will let me show me how to customize the Windows 7 Jump List for my application? | channel9.msdn.com did a series of discussions covering the new taskbar, including the jumplist.
[Jump Into Windows 7 Taskbar Jump Lists](http://channel9.msdn.com/posts/yochay/Jump-into-the-Windows-7-Taskbar-Jump-Lists/)
Additionally, The Windows 7 Blog started a series of posts that covering developing the task-bar, including how to work with jump-lists. You can view their initial post at <http://blogs.msdn.com/yochay/archive/2009/01/06/windows-7-taskbar-part-1-the-basics.aspx> | Windows 7 API Code Pack contains the official implementation for .NET, see <http://code.msdn.microsoft.com/WindowsAPICodePack> | .NET Jump List | [
"",
"c#",
".net",
"windows-7",
""
] |
How can I *iterate* over a string in Python (get each character from the string, one at a time, each time through a loop)? | As Johannes pointed out,
```
for c in "string":
#do something with c
```
You can iterate pretty much anything in python using the `for loop` construct,
for example, `open("file.txt")` returns a file object (and opens the file), iterating over it iterates over lines in that file
```
with open(filename) as f:
for line in f:
# do something with line
```
If that seems like magic, well it kinda is, but the idea behind it is really simple.
There's a simple iterator protocol that can be applied to any kind of object to make the `for` loop work on it.
Simply implement an iterator that defines a `next()` method, and implement an `__iter__` method on a class to make it iterable. (the `__iter__` of course, should return an iterator object, that is, an object that defines `next()`)
[See official documentation](http://docs.python.org/library/stdtypes.html#iterator-types) | If you need access to the index as you iterate through the string, use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate):
```
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
``` | Iterating each character in a string using Python | [
"",
"python",
"string",
"iteration",
""
] |
The typical way of selecting data is:
```
select * from my_table
```
But what if the table contains 10 million records and you only want records 300,010 to 300,020
Is there a way to create a SQL statement on Microsoft SQL that only gets 10 records at once?
E.g.
```
select * from my_table from records 300,010 to 300,020
```
This would be way more efficient than retrieving 10 million records across the network, storing them in the IIS server and then counting to the records you want. | Try looking at info about pagination. Here's a short summary of it for [SQL Server](http://www.singingeels.com/Articles/Pagination_In_SQL_Server_2005.aspx). | `SELECT * FROM my_table` is just the tip of the iceberg. Assuming you're talking a table with an identity field for the primary key, you can just say:
```
SELECT * FROM my_table WHERE ID >= 300010 AND ID <= 300020
```
You should also know that selecting \* is considered poor practice in many circles. They want you specify the exact column list. | Is there efficient SQL to query a portion of a large table | [
"",
"sql",
"performance",
""
] |
## Context
* PHP 5.3.x
## Overview
After doing a code-review with an associate who uses both php and ruby routinely, a fun challenge came up on string interpolation in php compared to ruby.
## Question
Assume color = "orange";
**Ruby:**
```
puts("My favorite color is #{color.downcase() + 'ish'} -- at least for now.");
```
**PHP:**
```
print("My favorite color is {strtolower( $color ) + 'ish'} -- at least for now.");
```
**Challenge:** can anyone specify a way to get the PHP version behave like Ruby?
## Caveat
This challenge is intended as a fun exercise with the constraint of using only straight PHP. This is not intended for serious PHP projects. For serious PHP projects, the developer will want to consider addon libraries, such as [TWIG](https://stackoverflow.com/questions/tagged/twig). | You can't call plain functions inside strings like that, but you can coax the parser into doing strange things:
```
<?php
print "{$a->b()}"; // Works
//Parse error: syntax error, unexpected '(' in Command line code on line 1
print "${time()}";
print "${$a=time()} $a"; // Also works: prints "1234380996"
?>
```
As long as it sees a valid variable at the start, it'll go ahead and interpolate an entire statement without complaining.
For those who were wondering, yes, this works too...
```
<?php
print "${$a or print shell_exec('ls')}";
?>
``` | You're close, you can embed variables in strings, but not function calls.
I use `printf()` (and `sprintf()`) for that, which is a thin wrapper around the C function of the same name:
```
printf('My favorite color is %sish -- at least for now.', strtolower( $color ));
```
See that `%s` in there? That's the placeholder for the string data type that you're passing in as the 2nd argument.
`sprintf()` works the same way, but it returns the formatted string instead of print'ing it.
The only other options are:
A. Performing the function calls first and assigning the end-result to the variable:
```
$color = strtolower( $color );
print("My favorite color is {$color}ish -- at least for now.");
```
B. Using concatenation, which is a little ugly IMO:
```
print('My favorite color is ' . strtolower( $color ) . 'ish -- at least for now.');
```
You may have noticed my use of single quotes (aka ticks), and double quotes.
In PHP, literals inside double quotes are parsed for variables, as you see in "A" above.
Literals inside single quotes are not parsed. Because of this, they're faster. You should, as a rule, only use double-quotes around literals when there's a variable to be parsed. | Ruby addict looking for PHP subexpressions in strings | [
"",
"php",
"ruby",
"comparison",
"string-interpolation",
""
] |
What are your thoughts about them?
Sometimes I have to write unmanaged code at work, but with large scale (games) projects, it just becomes way more time-consuming and complicated, which is solved by throwing more people at it.
Do you think managed code is viable for large scale applications? (applications like Photoshop, [3ds Max](http://www.softpedia.com/screenshots/3D-Studio-Max_8.png), [Maya](http://www.d-vw.com/dsculptor/with_other/maya_screen_shot.gif), [XSI](http://img259.imageshack.us/img259/4116/maxwellxsiur2.jpg), etc, which are computationally intensive but don't have the realtime requirements of games (to a degree). | I think using unmanaged code for performance reasons is one of the worst premature optimizations I´ve ever heard of. Before you choose some technology that is harder to work with just because it might faster you should be very sure that you need the speed.
Besides the CLR is so close to unmanged performance that 99 out of 100 cases shouldnt even have to think about it. And even if you fall into the camp that needs the performance you should write most of your code in the managed space and then switch to unmanged in the parts that your profiler tells you to.
About games in particular: there have been a few bigger titles writen in on mono now that ***gained*** performance, because they could write everything in manged code and didnt have to resort to scripting languages for the abstract parts like AI. | I think you can do large applications with .NET. There are many examples out there:
* Parts of VisualStudio are written in .NET (e.g. WinForms editor and WPF editor)
* Expression Blend is written in .NET and WPF
* Stackoverflow uses .NET and ASP.NET, as do many other sites.
* In VisualStudio 2010, the new editor (replacement for the current implementation) is written in .NET and WPF
One word about computationally intensive applications: Since the code is compiled to machine code by the interpreter, most calculations should be as fast as unmanaged code.
On the other hand you have a lot of advantages:
* (almost) no memory leaks (garbage collector)
* you get exceptions when something is wrong, no crash without information
* the code runs equally well on x32 and x64, without the need to change or recompile the application
* C# is easier to use than C++ (delegate, collections, LINQ etc)
* ... | Managed vs Unmanaged | [
"",
"c#",
".net",
"performance",
"unmanaged",
"managed",
""
] |
I make an AJAX request like so using JQuery:
```
$.ajax({
type: "GET",
url: "getvideo.php",
data: 'videoid=' + vid,
```
I use firebug to tell me what's going on and it tells me that a 500 internal server error has occurred? Here is part of the script concerned:
```
$videoid = $_GET['videoid'];
$get = new youtubeAPI();
$get->getVideoAPI($videoid);
class youtubeAPI extends Exception {
function getVideoAPI($videoid){
if (isset($videoid)) {
$clientLibraryPath = 'library';
$oldPath = set_include_path(
get_include_path() . PATH_SEPARATOR . $clientLibraryPath
);
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
```
I use the same AJAX call to other scripts and they are fine. I have used these scripts on another server and it was fine **except** on the other server the file is named "getvideo.php5" whereas here I named it "getvideo.php" since I have PHP 5.2.6 installed only.
Please help
## UPDATE
This is the error:
> [Wed Feb 11 20:48:17 2009] [error] [client xx.xx.xxx.xxx] PHP Fatal error: Class 'DOMDocument' not found in /var/www/html/library/Zend/Gdata/App.php on line 734, referer: <http://xx.xx.xx.xxx/>
I hid my IP. At that line:
```
public static function importString($string, $className='Zend_Gdata_App_Feed') {
// Load the feed as an XML DOMDocument object
@ini_set('track_errors', 1);
$doc = new DOMDocument(); // LINE 734
$success = @$doc->loadXML($string);
@ini_restore('track_errors');
```
But I shouldn't be playing around with that right? In any case, that class doesn't exist as a script and doesn't exist in that script as a class. I AM MAKING USE OF THIS SAME LIBRARY IN MY OTHER SERVER. It is also missing that too??? This is what I downloaded from the Youtube API zip folder.
## SOLVED
This was a brand new server and it had minimal PHP installed. I was missing PHP dom functions. A quick install fixed this problem. Thanks for reminding me to look at the logs. I should have tried that first.
```
yum install php-xml
yum install php-xmlrpc
``` | Try executing the call manually yourself in your browser (its the same thing) and see what gets returned. If nothing gets returned and you get a 500 internal server error, you need to then review your logs and see whats causing this error to happen.
Also make sure you are making the ajax call to the proper domain. If you try calling out of your domain the call will fail every time. | What? `.php5` ? I don't know your apache configuration (given you're even using it), but `.php` will work for all versions of PHP.
Anyway, try to directly access that URL and see what happens, this shouldn't have anything to do with Ajax. Also take a look at your web-server logs. | AJAX Call to PHP script gives me 500 Internal Server Error? | [
"",
"php",
"ajax",
"apache",
""
] |
I'm trying to understand what single and multiple dispatch are, exactly.
I just read this:
<http://en.wikipedia.org/wiki/Multiple_dispatch>
And from that definition is seems to me that C# and VB.Net are multiple-dispatch, even though the choice of which overload to call is made at compile-time.
Am I correct here, or am I missing something?
Thanks! | OK, I understood the subtle difference where function overloading is different from multiple-dispatch.
Basically, the difference is whether which method to call is chosen at run-time or compile-time. Now, I know everybody's said this, but without a clear example this sounds VERY obvious, given that C# is statically typed and multiple-dispatch languages (apparently to me, at least) seem to be dynamically typed. Up to now, with just that definition multiple-dispatch and function overloading sounded exactly the same to me.
The case where this makes a real difference is when you
* have two overloads of a method that differ on the type of a parameter (`CaptureSpaceShip(IRebelAllianceShip ship)` and `CaptureSpaceShip(Xwing ship)`
* the two types (`IRebelAllianceShip` and `CaptureSpaceShip`) are polymorphic, and
* you call the method with a reference declared as the higher type, which actually points to an object of the lower type
Full Example:
```
int CaptureSpaceShip(IRebelAllianceShip ship) {}
int CaptureSpaceShip(XWing ship) {}
void Main() {
IRebelAllianceShip theShip = new XWing();
CaptureSpaceShip(theShip);
}
```
XWing obviously implements IRebelAllianceShip.
In this case, the first method will be called, whereas if C# implemented multiple-dispatch, the second method would be called.
Sorry about the doc rehash... This seems to me the clearest way to explain this difference, rather than just reading the definitions for each dispatch method.
For a more formal explanation:
[http://en.wikipedia.org/wiki/Double\_dispatch#Double\_dispatch\_is\_more\_than\_function\_overloading](http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading "http://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading") | For those that find this article using a search engine, C# 4.0 introduces the [dynamic](http://msdn.microsoft.com/en-us/library/dd264736.aspx) keyword. The code would look like the following.
```
int CaptureSpaceShip(IRebelAllianceShip ship) {}
int CaptureSpaceShip(XWing ship) {}
void Main() {
IRebelAllianceShip theShip = new XWing();
CaptureSpaceShip((dynamic)theShip);
}
``` | Is C# a single dispatch or multiple dispatch language? | [
"",
"c#",
"programming-languages",
"multiple-dispatch",
"single-dispatch",
""
] |
How do you set the cursor position in a text field using jQuery? I've got a text field with content, and I want the users cursor to be positioned at a certain offset when they focus on the field. The code should look kind of like this:
```
$('#input').focus(function() {
$(this).setCursorPosition(4);
});
```
What would the implementation of that setCursorPosition function look like? If you had a text field with the content abcdefg, this call would result in the cursor being positioned as follows: abcd\*\*|\*\*efg.
Java has a similar function, setCaretPosition. Does a similar method exist for javascript?
**Update: I modified CMS's code to work with jQuery as follows:**
```
new function($) {
$.fn.setCursorPosition = function(pos) {
if (this.setSelectionRange) {
this.setSelectionRange(pos, pos);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
if(pos < 0) {
pos = $(this).val().length + pos;
}
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
``` | I have two functions:
```
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
```
Then you can use setCaretToPos like this:
```
setCaretToPos(document.getElementById("YOURINPUT"), 4);
```
Live example with both a `textarea` and an `input`, showing use from jQuery:
```
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
} else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos(input, pos) {
setSelectionRange(input, pos, pos);
}
$("#set-textarea").click(function() {
setCaretToPos($("#the-textarea")[0], 10)
});
$("#set-input").click(function() {
setCaretToPos($("#the-input")[0], 10);
});
```
```
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
<br><input type="button" id="set-textarea" value="Set in textarea">
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">
<br><input type="button" id="set-input" value="Set in input">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
```
As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last [here](http://jsbin.com/sujoxosepo); Stack Snippets don't support IE8). | Here's a jQuery solution:
```
$.fn.selectRange = function(start, end) {
if(end === undefined) {
end = start;
}
return this.each(function() {
if('selectionStart' in this) {
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange) {
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
```
With this, you can do
```
$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position
```
* [JsFiddle](http://jsfiddle.net/mnpenner/WpqsN/2291/)
* [JsBin](https://jsbin.com/vayoso/1/edit?html,js,output) | jQuery Set Cursor Position in Text Area | [
"",
"javascript",
"jquery",
"html",
"textfield",
""
] |
I am currently using JUnit 4.4 and Java 1.6.x. And after a recent code fix, we started getting this AssertionFailedError in my JUnit tests on the method:
*UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001 expected: "Mon Jan 15 09:26:07 PST 2001" but was: "Mon Jan 15 09:26:07 PST 2001"*
*junit.framework.AssertionFailedError: UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001 expected: but was:
at UtilityTest.testParseDate(Unknown Source)*
As you can see, the expected and actual appear identical, and after several code inspections, we can find no obvious error in the code. Test runs with actual data have also produced correct (expected) results.
Has anyone seen this behavior before in JUnit, and if so, did you find the cause and/or a fix?
I have seen the same thing in previous versions of Java and JUnit myself: always somewhat random when it occurs, and usually the only fix "that worked" was to retype the chunk of code in from scratch. Weird, yet that was tne only way to remove this error. I'm trying to find out something more "concrete" in the behavior this time.
Thanks,
-Richard | Can you post the code for UtilityTest.testParseDate()?
Are you using *assertEquals()* on the date values or are you comparing them in another fashion? If so, can you assert that the millisecond timestamps are equal instead of the dates themselves? | The test code is:
```
Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.set(2001, 0, 15, 9, 26, 07); // Jan 15 2001, 09:26:07
// format 4 = ddd mmm dd hh:mm:ss TTT yyyy (with gettime)
assertEquals("UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001", cal.getTime(), Utility.parseDate("Mon Jan 15 09:26:07 PST 2001", today, true));
```
Here's what parseDate looks like (just the method signature as the code was long):
```
public static Date parseDate(String date, Date today, boolean gettime) {
```
I think you may have it though - even though it does not DISPLAY the milliseconds, they would be different. | JUnit produces strange AssertionFailedError | [
"",
"java",
"testing",
"junit",
""
] |
I'm utilizing the Reporting Services web service to generate a report and allow the user to download it. This is occuring via PDF, Excel, XML, etc. and working just fine. I'm trying to create some seperation between my reporting class and the implementation, but am struggling with how I can can do this in a manor that is still testable.
Since my custom Reports Object/Class is calling the web service directly, should I seperate this out even further with the use of interfaces? Any reccomendations on this and how it would still be unit testable regardless of the byte source would be much appreciated. | Russell, I think your answer lies in learning about Dependency Injection/Inversion of Control. You might start here...
* <http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx>
* <http://misko.hevery.com/2009/01/14/when-to-use-dependency-injection/>
* <http://iridescence.no/post/Using-Unit-Tests-to-Uncover-Design-Flaws.aspx>
* <http://en.wikipedia.org/wiki/Dependency_injection>
* <http://martinfowler.com/articles/injection.html> | If you're new to Dependency Injection/Inversion of Control, this link is a great screencast by Carl Franklin and James Kovacs.
[DNR TV Show #126: James Kovacs' roll-your-own IoC container](http://www.dnrtv.com/default.aspx?showNum=126)
I'm a sucker for learning new things by hearing others explain it clearly and watching them code it. James explains the principles, the code that does it, and how you can further your study by using a framework. | Byte Stream Unit Test | [
"",
"c#",
"asp.net",
"unit-testing",
"reporting-services",
"interface",
""
] |
**Duplicate of** *[What's the BEST way to remove the time portion of a datetime value (SQL Server)?](https://stackoverflow.com/questions/2775)*
I have a column that tracks when things are created using a datetime, but I'd like to generate a report that groups them by day, so I need a way of nulling out the time component of a datetime column.
How do I do this? | One way is to change `getdate()` to your column name,
```
select dateadd(dd, datediff(dd, 0, getdate())+0, 0)
``` | Why not convert straight to date:
```
select convert(date, getdate())
```
This truncates days, not rounds. To round Days do this:
```
select convert(date, getdate() + 0.5)
``` | T-SQL to trim a datetime to the nearest date? | [
"",
"sql",
"t-sql",
"datetime",
"date-arithmetic",
""
] |
I'm just starting to use Django for a personal project.
What are the pros and cons of using the built-in Admin application versus integrating my administrative functions into the app itself (by checking request.user.is\_staff)?
This is a community wiki because it could be considered a poll. | It really depends on the project I guess. While you can do everything in the admin, when your app gets more complex using the admin gets more complex too. And if you want to make your app really easy to manage you want control over every little detail, which is not really possible with the admin app.
I guess you should see it like this:
Using django admin: save time writing it, lose time using it.
Rolling your own admin: lose time writing it, save time using it. | I would use Django's admin app, for a number of reasons. First, writing an administration app may be quite tricky and take some time if you want to do it right, and `django.contrib.admin` is for free and works out of the box. Second, it is really well designed and very nice to work with (even for non-technical users). Third, it covers a lot of the common cases and it doesn't seem wise to waste time on rewriting it until you are really sure you cannot do otherwise. Fourth, it isn't really so difficult to customize. For example, adding akismet mark-as-spam and mark-as-ham buttons was really a piece of cake. | Django Admin app or roll my own? | [
"",
"python",
"django",
"django-admin",
""
] |
When using a SortedDictionary in Linq and iterating over the KeyValuePair it provides, can I be assured that a complex linq query will execute it in ascending order? Here's a brief, although a bit confusing example:
```
Random r = new Random();
//build 100 dictionaries and put them into a sorted dictionary
//with "priority" as the key and it is a number 0-99.
SortedDictionary<int, Dictionary<int, double>> sortedDict =
new SortedDictionary<int, Dictionary<int, double>>();
for (int i = 0; i < 100; i++)
{
Dictionary<int, double> dict = new Dictionary<int, double>();
//create the dictionary and a random 10 k/v pairs
for (int j = 0; j < 10; j++)
{
dict[r.Next(0, 100)] = r.NextDouble() * i * 10;
}
sortedDict[i] = dict;
}
IEnumerable<int> keys = Enumerable.Range(0, 100);
//the goal is to find the FIRST existence of the "key" inside one
//of the inner dictionaries going through the SortedDictionary IN ORDER
//this appears to work:
var qry = from key in keys
from priority in sortedDict
where priority.Value.ContainsKey(key)
let value = priority.Value[key]
group value by key into keyGroup
let firstValue = keyGroup.First()
select new { Key = keyGroup.Key, Value = firstValue };
// the result is as expected, a list of the numbers at most 0-99 and their
// value found in the dictionary with the lowest "priority"
```
The question(s):
1. It appears to work, but can I rely on this behavior?
2. Is this efficient, or does the group by throw it off?
3. Does adding "sortedDict.Reverse()" work properly too? (it appears to)
4. How would PLinq handle this - and would it still be consistent?
If this isn't guaranteed, I know how I can pull the "priority" into the grouping and order by it after the fact. But I'd rather not... | 1. Yes, you can trust the order of SortedDictionary. It would be pointless otherwise :)
2. It would be slightly more efficient without the "let" clause. Just do:
```
var qry = from key in keys
from priority in sortedDict
where priority.Value.ContainsKey(key)
let value = priority.Value[key]
group value by key into keyGroup
select new { Key = keyGroup.Key, Value = keyGroup.First() };
```
However, you're still scanning through the dictionary quite a lot with this. Don't you basically want a reverse map from key to priorities containing that key? That could be constructed much more efficiently. As you say, the example is pretty confusing. If you could tell us what you're trying to achieve in your *real* code, we may be able to come up with something better. (If it's exactly this situation, I can certainly work on that - I'd rather not do so and then find out that reality is very different though!)
3. Calling Reverse() will indeed work - but it will buffer all the data. If you want it in reverse order, I suggest you give the SortedDictionary an appropriate IComparer to start with.
4. Parallel LINQ is "interesting" when it comes to order. It may be different right now, but I [had fun a while ago](http://msmvps.com/blogs/jon_skeet/archive/2007/12/04/a-cautionary-parallel-tale-ordering-isn-t-simple.aspx) when I was plotting the Mandelbrot set using it... | Here's an [answer](https://stackoverflow.com/questions/204505/preserving-order-with-linq/204777#204777) about which linq methods preserve order.
Eyeballing the query, it looks like you have:
```
keys.SelectMany(...)
.Where(...)
.GroupBy(...)
.Select(g => g.First())
.Select(...);
```
All of which will preserve ordering in some way. | Can I rely on the order of a SortedDictionary in Linq, and is it doing this efficiently? | [
"",
"c#",
".net",
"linq",
"linq-to-objects",
""
] |
## Example Problem:
### Entities:
* User contains name and a list of friends (User references)
* Blog Post contains title, content, date and Writer (User)
### Requirement:
I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through older entries.
## SQL Solution:
So in sql land it would be something like:
```
select * from blog_post where user_id in (select friend_id from user_friend where user_id = :userId) order by date
```
## GAE solutions i can think of are:
* Load user, loop through the list of friends and load their latest blog posts. Finally merge all the blog posts to find the latest 10 blog entries
* In a blog post have a list of all users that have the writer as a friend. This would mean a simple read but would result in quota overload when adding a friend who has lots of blog posts.
I don't believe either of these solutions will scale.
Im sure others have hit this problem but I've searched, watched google io videos, read other's code ... What am i missing? | This topic is covered in a Google io talk:
<http://code.google.com/events/io/sessions/BuildingScalableComplexApps.html>
Basically the Google team suggest using list properties and what they call relational index entities, an example application can be found here: <http://pubsub-test.appspot.com/> | If you look at how the SQL solution you provided will be executed, it will go basically like this:
1. Fetch a list of friends for the current user
2. For each user in the list, start an index scan over recent posts
3. Merge-join all the scans from step 2, stopping when you've retrieved enough entries
You can carry out exactly the same procedure yourself in App Engine, by using the Query instances as iterators and doing a merge join over them.
You're right that this will not scale well to large numbers of friends, but it suffers from exactly the same issues the SQL implementation has, it just doesn't disguise them as well: Fetching the latest 20 (for example) entries costs roughly O(n log n) work, where n is the number of friends. | GAE - How to live with no joins? | [
"",
"python",
"google-app-engine",
"join",
"google-cloud-datastore",
""
] |
I would like to create a spinning menu akin to the one done in flash [here.](http://accuval.net) Are there any relevant links you know about to help with this endeavor?
Thank you kindly. | You could use the <canvas> tag. | You can do it with a series of images and just swap them. Without getting into complexities of cross-browser canvas/svg that's probably the easiest way to do it. | Spinning javascript menu | [
"",
"javascript",
"flash",
"menu",
"navigation",
""
] |
I'm rendering some HTML in a QT QLabel. The HTML looks like this:
```
<pre>foo\tbar</pre>
```
(note that I've put "\t" where there is a tab chracter in the code).
This renders fine, but the tab character appears to be rendered as eight spaces, whereas I want it to be redered as 4. How can I change this **without having to change the source HTML**? | According to [W3](http://www.w3.org/TR/html4/struct/text.html#h-9.3.4) (HTML4):
> The horizontal tab character (decimal 9 in [ISO10646] and [ISO88591]) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. **We strongly discourage using horizontal tabs** in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.
It's implementation-defined, essencially. Most, if not all, browsers/renderers use eight spaces for tabs. This cannot be configured in Qt.
It is, however somewhat trivial to go through your HTML and replace tabs with however many spaces you wish. Write a simple parser for that. Pseudocode:
```
for each <pre> block {
for each line in block {
position_in_line = 0
for each character in line {
if character is a tab {
remove tab character
do {
add a space character
++position_in_line
} while position_in_line % 8 != 0
} else {
++position_in_line
}
}
}
}
```
In case you're curious, HTML3 specifies the use of [eight-character tabs](http://www.w3.org/MarkUp/html3/specialchars.html):
> Within <PRE>, the tab should be interpreted to shift the horizontal column position to the next position which is a multiple of 8 on the same line; that is, col := (col+8) mod 8. | While `QLabel` uses a `QTextDocument` internally when rendering rich text, it does not allow access to it in it's API. However, since `QTextDocument` is a `QObject`, you can try to use
```
QTextDocument * tl = label->findChild<QTextDocument>();
```
to get access to it (will work if the `QLabel` creates the `QTextDocument` as a (direct or indirect) child of itself).
Once you have a pointer to the text document, you can use the `QTextDocument` API, e.g. `QTextOption::setTabsStop()`, to change the tab stops.
The last step is to somehow make the `QLabel` repaint itself. Probably a call to `QWidget::update()` suffices, but caching (or worse, recreating the text document) might thward that. In this case, you can register an event listener on the label to adjust the text document just prior to a `paintEvent()`, but note that the `sizeHint()` might also change when the tab stops change, so it might be more complicated still.
That said, it's how I'd approach the problem. | Change tab stop size in rendered HTML using Qt's QLabel class | [
"",
"c++",
"html",
"qt",
"rendering",
""
] |
From what I have gathered, I want to force a class to use particular private fields (and methods) I need an abstract class because an interface only declares public/static/final fields and methods. Correct??
I just started my first big java project and want to make sure I'm not going to hurt myself later :) | It's fairly common to provide both, so that you end up with:
```
public interface Sendable {
public void sendMe();
}
```
and
```
public abstract class AbstractSender implements Sendable {
public abstract void send();
public void sendMe() {
send(this.toString());
}
}
```
That way, anyone who is happy with the default implementation in the abstract class can quickly subclass it without rewriting a lot of code, but anyone who needs to do something more complex (or who needs to inherit from a different base class) can still implement the interface and be plug-and-play. | You don’t want to force the use of certain private fields or methods. In general you don’t care about the implementation, you care about the interface. So define a couple of methods in a couple of interfaces (depending on how much you need) and define classes that implement them. This will probably hurt you the least in the future. | Java: Interface vs Abstract Class (regarding fields) | [
"",
"java",
"interface",
"accessibility",
"abstract-class",
"field",
""
] |
I have a stored procedure that gets all the non-system database names from a SQL Server:
```
select name from MySQLServer.master.sys.databases
where name not like ('master')
and name not like ('tempdb')
and name not like ('msdb')
and name not like ('model')
and name not like ('Admin')
```
What I would like to do is pass the server name as a parameter, so this sproc is more reusable:
```
@servername = 'some passed servername'
select name from @servername.master.sys.databases
where name not like ('master')
and name not like ('tempdb')
and name not like ('msdb')
and name not like ('model')
and name not like ('Admin')
```
Can this be done? How would I do this?
Could I create a variable like:
```
DECLARE @serverPointer nvarchar(MAX)
SET @serverPointer = @servername + '.master.sys.databases'
select name from @serverPointer
```
Any help would be appreciated. | This will work if you have linked servers to all of the SQL Servers you wish to query. As to the query to use, the system databases take up the first 4 database\_id values. So you can run the following to get the user databases:
```
SELECT '[' + name + ']'
FROM sys.databases
WHERE database_id > 4
```
Putting that together, you'd basically do the following for your proc:
```
CREATE PROC GetUserDBs
@Server sysname
AS
BEGIN
DECLARE @SQL nvarchar(2000);
SET @SQL = 'SELECT ''['' + name + '']'' FROM [' + @Server + '].master.sys.databases WHERE database_id > 4';
EXECUTE sp_executesql @SQL;
END
GO
``` | ```
declare @servername nvarchar(max)
DECLARE @serverPointer nvarchar(MAX)
declare @qry nvarchar(max)
@serverPointer = @servername + '.master.sys.databases'
set @qry = 'select name from '+@serverPointer
exec sp_executesql @qry
``` | SQL Stored-Proc using parameter for server name? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to write a thread-safe queue using pthreads in c++. My program works 93% of the time. The other 7% of the time it other spits out garbage, OR seems to fall asleep. I'm wondering if there is some flaw in my queue where a context-switch would break it?
```
// thread-safe queue
// inspired by http://msmvps.com/blogs/vandooren/archive/2007/01/05/creating-a-thread-safe-producer-consumer-queue-in-c-without-using-locks.aspx
// only works with one producer and one consumer
#include <pthread.h>
#include <exception>
template<class T>
class tsqueue
{
private:
volatile int m_ReadIndex, m_WriteIndex;
volatile T *m_Data;
volatile bool m_Done;
const int m_Size;
pthread_mutex_t m_ReadMutex, m_WriteMutex;
pthread_cond_t m_ReadCond, m_WriteCond;
public:
tsqueue(const int &size);
~tsqueue();
void push(const T &elem);
T pop();
void terminate();
bool isDone() const;
};
template <class T>
tsqueue<T>::tsqueue(const int &size) : m_ReadIndex(0), m_WriteIndex(0), m_Size(size), m_Done(false) {
m_Data = new T[size];
pthread_mutex_init(&m_ReadMutex, NULL);
pthread_mutex_init(&m_WriteMutex, NULL);
pthread_cond_init(&m_WriteCond, NULL);
pthread_cond_init(&m_WriteCond, NULL);
}
template <class T>
tsqueue<T>::~tsqueue() {
delete[] m_Data;
pthread_mutex_destroy(&m_ReadMutex);
pthread_mutex_destroy(&m_WriteMutex);
pthread_cond_destroy(&m_ReadCond);
pthread_cond_destroy(&m_WriteCond);
}
template <class T>
void tsqueue<T>::push(const T &elem) {
int next = (m_WriteIndex + 1) % m_Size;
if(next == m_ReadIndex) {
pthread_mutex_lock(&m_WriteMutex);
pthread_cond_wait(&m_WriteCond, &m_WriteMutex);
pthread_mutex_unlock(&m_WriteMutex);
}
m_Data[m_WriteIndex] = elem;
m_WriteIndex = next;
pthread_cond_signal(&m_ReadCond);
}
template <class T>
T tsqueue<T>::pop() {
if(m_ReadIndex == m_WriteIndex) {
pthread_mutex_lock(&m_ReadMutex);
pthread_cond_wait(&m_ReadCond, &m_ReadMutex);
pthread_mutex_unlock(&m_ReadMutex);
if(m_Done && m_ReadIndex == m_WriteIndex) throw "queue empty and terminated";
}
int next = (m_ReadIndex +1) % m_Size;
T elem = m_Data[m_ReadIndex];
m_ReadIndex = next;
pthread_cond_signal(&m_WriteCond);
return elem;
}
template <class T>
void tsqueue<T>::terminate() {
m_Done = true;
pthread_cond_signal(&m_ReadCond);
}
template <class T>
bool tsqueue<T>::isDone() const {
return (m_Done && m_ReadIndex == m_WriteIndex);
}
```
This could be used like this:
```
// thread 1
while(cin.get(c)) {
queue1.push(c);
}
queue1.terminate();
// thread 2
while(!queue1.isDone()) {
try{ c = queue1.pop(); }
catch(char const* str){break;}
cout.put(c);
}
```
If anyone sees a problem with this, please say so :) | If you want anything with decent performance I would strongly suggest dumping your R/W lock and just use a very simple spinlock. Or if you really think you can get the performance you want with R/W lock, i would roll your own based on [this](http://www.bluebytesoftware.com/blog/2009/01/30/ASinglewordReaderwriterSpinLock.aspx) design(single word R/W Spinlock) from Joe Duffy. | Yes, there are definitely problems here. All your accesses to queue member variables occur *outside* the mutexes. In fact, I'm not entirely sure what your mutexes are protecting, since they are just around a wait on a condition variable.
Also, it appears that your reader and writer will always operate in lock-step, never allowing the queue to grow beyond one element in size. | Problem with thread-safe queue? | [
"",
"c++",
"multithreading",
"concurrency",
"queue",
"pthreads",
""
] |
I'm developing a python framework that would have "addons" written as separate packages. I.e.:
```
import myframework
from myframework.addons import foo, bar
```
Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into `myframework.addons` namespace.
Currently my best solution to this is the following. An add-on would be deployed (most likely into `{python_version}/site-packages/` like so:
```
fooext/
fooext/__init__.py
fooext/myframework/
fooext/myframework/__init__.py
fooext/myframework/addons/
fooext/myframework/addons/__init__.py
fooext/myframework/addons/foo.py
```
The `fooext/myframework/addons/__init__.py` would have the pkgutil path extension code:
```
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
```
The problem is that for this to work, the PYTHONPATH needs to have `fooext/` in it, however the only thing it would have is the parent install directory (most likely, the above-mentioned `site-packages`).
The solution to this is to have extra code in `myframework/addons/__init__.py` which would tranverse `sys.path` and look for any modules with a myframework sub-package, in which case it adds it to `sys.path` and everything works.
Another idea I had is to write the addon files directly to `myframework/addons/` install location, but then it would make development and deployed namespace differ.
Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether? | > Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?
Possibly. Python's module/package setup is generally tricky to tamper with dynamically like this, but its object/class system is open and extensible in a well-defined way. When modules and packages don't quite have the features you need to encapsulate your project nicely you can use classes instead.
For example you could have the extension functionality in a completely different package, but allow it to inject classes into your basic framework through a specific interface. eg. myframework/\_\_init\_\_.py containing a basic application wrapper:
```
class MyFramework(object):
"""A bare MyFramework, I only hold a person's name
"""
_addons= {}
@staticmethod
def addAddon(name, addon):
MyFramework._addons[name]= addon
def __init__(self, person):
self.person= person
for name, addon in MyFramework._addons.items():
setattr(self, name, addon(self))
```
Then you could have extension functionality in a myexts/helloer.py, that keeps a reference to its 'owner' or 'outer' MyFramework class instance:
```
class Helloer(object):
def __init__(self, owner):
self.owner= owner
def hello(self):
print 'hello '+self.owner.person
import myframework
myframework.MyFramework.addAddon('helloer', Helloer)
```
So now if you just "import myframework", you only get the basic functionality. But if you also "import myexts.helloer" you also get the ability to call MyFramework.helloer.hello(). Naturally you can also define protocols for addons to interact with the basic framework behaviour, and each other. You can also do things like inner classes a subclass of the framework can override to customise without having to monkey-patch classes that might affect other applications, if you need that level of complexity.
Encapsulating behaviour like this can be useful, but it's typically annoying work to adapt module-level code you've already got to fit this model. | See namespace packages:
<http://www.python.org/dev/peps/pep-0382/>
or in setuptools:
<http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages> | Putting separate python packages into same namespace? | [
"",
"python",
"namespaces",
"distribution",
"extend",
""
] |
I'm not sure if there is a way to do this in Velocity or not:
I have a User POJO which a property named Status, which looks like an enum (but it is not, since I am stuck on Java 1.4), the definition looks something like this:
```
public class User {
// default status to User
private Status status = Status.USER;
public void setStatus(Status status) {
this.status = status;
}
public Status getStatus() {
return status;
}
```
And Status is a static inner class:
```
public static final class Status {
private String statusString;
private Status(String statusString) {
this.statusString = statusString;
}
public final static Status USER = new Status("user");
public final static Status ADMIN = new Status("admin");
public final static Status STATUS_X = new Status("blah");
//.equals() and .hashCode() implemented as well
}
```
With this pattern, a user status can easily be tested in a conditional such as
```
if(User.Status.ADMIN.equals(user.getStatus())) ...
```
... without having to reference any constants for the status ID, any magic numbers, etc.
However, I can't figure out how to test these conditionals in my Velocity template with VTL. I'd like to just print a simple string based upon the user's status, such as:
```
Welcome <b>${user.name}</b>!
<br/>
<br/>
#if($user.status == com.company.blah.User.Status.USER)
You are a regular user
#elseif($user.status == com.company.blah.User.Status.ADMIN)
You are an administrator
#etc...
#end
```
But this throws an Exception that looks like `org.apache.velocity.exception.ParseErrorException: Encountered "User" at webpages/include/dashboard.inc[line 10, column 21] Was expecting one of: "[" ...`
From [the VTL User Guide](http://velocity.apache.org/engine/releases/velocity-1.6.1/user-guide.html), there is no mention of accessing a Java class/static member directly in VTL, it appears that the right hand side (RHS) of a conditional can only be a number literal, string literal, property reference, or method reference.
So is there any way that I can access static Java properties/references in a Velocity template? I'm aware that as a workaround, I could embed the status ID or some other identifier as a reference in my controller (this is a web MVC application using Velocity as the View technology), but I strongly do not want to embed any magic numbers or constants in the view layer. | I figured out a workaround that allows me to add each `User.Status` object to the Velocity context, which avoids any sort of references to constants or magic numbers in the template.
On the controller/Java side:
```
// put the statuses directly into the model
Map statusMap = new HashMap();
statusMap.put("user", User.Status.USER);
statusMap.put("groupOperator", User.Status.ADMIN);
...
modelAndView.addObject("statusmap", statusMap);
```
And then in the template these values can be referenced like so:
```
#if($user.status == $statusmap.user)
You are a regular user
#elseif($user.status == $statusmap.admin)
You are an administrator
##etc...
#end
``` | Yeah, Velocity doesn't natively grok classes and packages. You could do what you did, or use the FieldMethodizer class to automate that. Another option would be the FieldTool in VelocityTools 2.0. | How to access static members in a Velocity template? | [
"",
"java",
"model-view-controller",
"velocity",
""
] |
```
public interface IBar {}
public interface IFoo : IBar {}
typeof(IFoo).BaseType == null
```
How can I get IBar? | ```
Type[] types = typeof(IFoo).GetInterfaces();
```
Edit: If you specifically want IBar, you can do:
```
Type type = typeof(IFoo).GetInterface("IBar");
``` | An interface is not a base type. Interfaces are not part of the inheritance tree.
To get access to interfaces list you can use:
```
typeof(IFoo).GetInterfaces()
```
or if you know the interface name:
```
typeof(IFoo).GetInterface("IBar")
```
If you are only interested in knowing if a type is implicitly compatible with another type (which I suspect is what you are looking for), use type.IsAssignableFrom(fromType). This is equivalent of 'is' keyword but with runtime types.
Example:
```
if(foo is IBar) {
// ...
}
```
Is equivalent to:
```
if(typeof(IBar).IsAssignableFrom(foo.GetType())) {
// ...
}
```
But in your case, you are probably more interested in:
```
if(typeof(IBar).IsAssignableFrom(typeof(IFoo))) {
// ...
}
``` | How to get interface basetype via reflection? | [
"",
"c#",
"reflection",
"interface",
""
] |
I'm trying to write some documentation for a webservice that has been provided by one of our vendors for an application we're integrating. A bunch of the interface is custom objects defined in the web service itself. The vendor has put up significant resistance to providing any documentation for this application and so I've taken it upon myself to do their job for them [against my better judgement].
The documentation they *have* provided frankly is embarassing and I'm trying to make as short work of this as I possibly can to put some good quality docs together. I know that as I don't have access to their source, I can't just run it through nDoc/Sandcastle to spit out an API doc, but I was wondering if (as a half way house) there was an easy way to export the intellisense to a text file without me having to write a utility to specificially iterate through each of the object types defined and reflect the members out to text?
If I could do this, it would at least make sure that I have a good quality document structure where I can just fill in the blanks. Having to skip back and forth to Visual Studio to check the intellisense for every class member is a very laborious way of doing this.
Does anyone have any ideas? | If it is a web service that you are trying to document, couldnt you then parse out the WSDL? | If you are accessing a remote Web Service, then I think you have access to the corresponding WSDL: what about parsing it and look for just the information you need?
Or using a tool to do this (I Googled for "wsdl documentation generator")?
Or even using WSDL.exe to generate some dummy code from the WSDL and then document it, perhaps helped by GhostDoc?
HTH | Can intellisense be exported or extracted from Visual Studio to a text file? | [
"",
"c#",
"vb.net",
"visual-studio",
"documentation",
"intellisense",
""
] |
I'm currently working on a web app that makes heavy use of JSF and IceFaces. We've had some discussions of moving to another presentation layer, and I thought I'd take the discussion out into SO and see what the experts think.
I'm curious if anyone could weigh in on the pros and cons of the various Java presentation layer technologies. If you've only worked with one, say why you love it or hate it. If you've worked with several, give your impressions of how they stack up against each other.
Our technologies under consideration are:
* IceFaces
* JSF (without IceFaces)
* GWT (Google Web Toolkit)
* Wicket
* Tapestry
And if I'm missing anything from my list, let me know.
Thanks! | My opinions are quite heavily biased towards Wicket because I've been using it for a while after tripping over JSP mines far too many times.
**Wicket PROs:**
* True separation of layout and code.
* Component based which means high reusability of site elements; For example you can create prettified form with automatic labeling and CSS styles and everything and just by changing it's DAO object in the component's constructor it's completely reusable in another project.
* Excellent support for things like Ajax, Portlets and various frameworks in general directly out-of-the-box AND more importantly it doesn't rely on anything else than slf4j/log4j to work, everything's optional!
**Wicket CONs:**
* Development has some confusion about things in general and Wicket generics are a bit of a mess right now although they've been cleaned a lot in 1.4
* Some components (like `Form.onSubmit()`) require extensive subclassing or anonymous method overriding for injecting behaviour easily. This is partly due to Wicket's powerful event-based design but unfortunately it also means it's easy to make a code mess with Wicket.
**Random CONs:** (that is, I haven't used but these are my opionions and/or things I've heard)
* GWT is JavaScript based which sounds stupid to me. Main issue is that it reminds me too much of JSP:s and its autogenerated classes which are horrible.
* Tapestry doesn't separate markup and code properly in a manner which could be easily validated between the two which will cause problems in the future. | I've used GWT for a couple small projects. Here are some things I like about it:
1. It's ajax by default, so I didn't have to *make* it do ajax, it just came along with using GWT.
2. It's got good separation of client versus server-side code.
3. I can unit-test my client code using junit
4. It lets you built crisp, snappy apps, largely because it's ajax.
Things I don't like:
1. Some things don't work as expected. For example, I've seen cases where click events didn't fire as expected, so I had to do a workaround.
2. Auto-deploy to tomcat running in eclipse sometimes just stops working, and I could never figure out why. | Pros and Cons of Various Java Web Presentation Layer Technologies | [
"",
"java",
"jakarta-ee",
"presentation-layer",
""
] |
I've been considering fast poker hand evaluation in Python. It occurred to me that one way to speed the process up would be to represent all the card faces and suits as prime numbers and multiply them together to represent the hands. To whit:
```
class PokerCard:
faces = '23456789TJQKA'
suits = 'cdhs'
facePrimes = [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 53, 59, 61]
suitPrimes = [2, 3, 5, 7]
```
AND
```
def HashVal(self):
return PokerCard.facePrimes[self.cardFace] * PokerCard.suitPrimes[self.cardSuit]
```
This would give each hand a numeric value that, through modulo could tell me how many kings are in the hand or how many hearts. For example, any hand with five or more clubs in it would divide evenly by 2^5; any hand with four kings would divide evenly by 59^4, etc.
The problem is that a seven-card hand like AcAdAhAsKdKhKs has a hash value of approximately 62.7 quadrillion, which would take considerably more than 32 bits to represent internally. Is there a way to store such large numbers in Python that will allow me to perform arithmetic operations on it? | Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called `long` and is separate from the `int` type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the `int` type has been dropped completely.
That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
You can find all the gory details in [PEP 0237](http://www.python.org/dev/peps/pep-0237). | Python supports ***arbitrarily*** large ***integers*** naturally:
Example:
```
>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```
You could even get, for example, a huge integer value, fib(4000000).
But still it does **not** (for now) supports an arbitrarily large **float**!!
If you need one big, large, float then check up on the decimal Module. There are examples of use on this site: *[OverflowError: (34, 'Result too large')](https://stackoverflow.com/questions/20201706/overflowerror-34-result-too-large)*
Another reference: *[9.4. decimal — Decimal fixed point and floating point arithmetic](http://docs.python.org/2/library/decimal.html)*
You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): *[Handling big numbers in code](https://stackoverflow.com/questions/1386604/handling-big-numbers-in-code)*
Another reference: *[gmpy](https://code.google.com/p/gmpy/)* ([Google Code](https://en.wikipedia.org/wiki/Google_Developers#Google_Code). Read-only) | Handling very large numbers in Python | [
"",
"python",
"optimization",
"largenumber",
""
] |
Is there a character in JavaScript to break up a line of code so that it is read as continuous despite being on a new line?
Something like....
```
1. alert ( "Please Select file
2. \ to delete" );
``` | In your example, you can break the string into two pieces:
```
alert ( "Please Select file"
+ " to delete");
```
Or, when it's a string, as in your case, you can use a [backslash](http://www.nczonline.net/blog/2006/12/26/interesting-javascript-string-capability/) as @Gumbo suggested:
```
alert ( "Please Select file\
to delete");
```
Note that this backslash approach is [not necessarily preferred](http://davidwalsh.name/multiline-javascript-strings#comments), and possibly not universally supported (I had trouble finding hard data on this). It is *not* in the [ECMA 5.1 spec](http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4).
When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:
```
if(SuperLongConditionWhyIsThisSoLong
&& SuperLongConditionOnAnotherLine
&& SuperLongConditionOnThirdLineSheesh)
{
// launch_missiles();
}
``` | Put the backslash at the end of the line:
```
alert("Please Select file\
to delete");
```
---
**Edit** I have to note that this is *not* part of [ECMAScript strings](http://bclary.com/2004/11/07/#a-7.8.4) as [line terminating characters](http://bclary.com/2004/11/07/#a-7.3) are not allowed at all:
> A '*LineTerminator*' character cannot appear in a string literal, even if preceded by a backslash `\`. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as `\n` or `\u000A`.
So using string concatenation is the better choice.
---
**Update 2015-01-05** [String literals in ECMAScript5](http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4) allow the mentioned syntax:
> A line terminator character cannot appear in a string literal, except as part of a *LineContinuation* to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as `\n` or `\u000A`. | How do I break a string across more than one line of code in JavaScript? | [
"",
"javascript",
"line-breaks",
""
] |
I've got a bug from one of our customers and believe that the problem lies with **MSVCR80.DLL v8.0.50727.3053** - a version which I cannot find for download anywhere, however a [google search](http://google.com/search?q=MSVCR80.DLL+8.0.50727.3053) turns up plenty of other crash reports.
Latest version on my system (and others here) is 8.0.50727.1433 and the [Microsoft Visual C++ 2005 SP1 Redistributable Package (x86)](http://www.microsoft.com/downloads/details.aspx?familyid=200b2fd9-ae1a-4a14-984d-389c36f85647&displaylang=en) is only version 8.0.5027.762 (currently same as the merge module we use)
Is there an "official" link to get this update? Is it bundled with any other Microsoft products?
**EDIT:** please don't email it to me, I'm looking for the SxS install.
**EDIT2:** damn, that wasn't the problem after all :( | A thread on the MSDN forums [pointed out the answer](http://social.msdn.microsoft.com/Forums/en-US/windowsworkflowfoundation/thread/5d57e3b1-80c0-43c2-8eab-0b7c4fe168e2/): msvcr80.dll version 8.0.50727.3053 is included in [.NET Framework 3.5 SP1](http://www.microsoft.com/downloads/details.aspx?familyid=ab99342f-5d1a-413d-8319-81da479ab0d7&displaylang=en) | You ought to be able to answer this question using Microsoft's DLL Help Database <http://support.microsoft.com/dllhelp/>
Unfortunately, when I try it, I only get two answers for msvcr80.dll whereas there ought to be dozens of different versions: and I don't know why. | Where can I find MSCVR80.DLL v8.0.50727.3053? | [
"",
"c++",
"visual-studio-2005",
"dll",
""
] |
Is there a way to make the following return true?
```
string title = "ASTRINGTOTEST";
title.Contains("string");
```
There doesn't seem to be an overload that allows me to set the case sensitivity. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the [i18n](http://en.wikipedia.org/wiki/Internationalization_and_localization) issues that come with up- and down casing).
**UPDATE**
This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.
For most cases, in mono-lingual, English code bases [this](https://stackoverflow.com/a/444818/11333) answer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.
[This](https://stackoverflow.com/a/15464440/11333) answer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such. | To test if the string `paragraph` contains the string `word` (thanks @QuarterMeister)
```
culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0
```
Where `culture` is the instance of [`CultureInfo`](http://msdn.microsoft.com/en-gb/library/system.globalization.cultureinfo(v=vs.110).aspx) describing the language that the text is written in.
This solution is transparent about **the definition of case-insensitivity, which is language dependent**. For example, the English language uses the characters `I` and `i` for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the [eleventh and twelfth letters](http://en.wikipedia.org/wiki/Dotted_and_dotless_I) of its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character 'İ'.
Thus the strings `tin` and `TIN` are the same word *in English*, but different words *in Turkish*. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)
To summarise, you can only answer the question 'are these two strings the same but in different cases' *if you know what language the text is in*. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to [`CultureInfo.InvariantCulture`](https://stackoverflow.com/questions/9760237/what-does-cultureinfo-invariantculture-mean), because it will be wrong in familiar ways. | You could use the [`String.IndexOf` Method](https://msdn.microsoft.com/en-us/library/ms224425(v=vs.110).aspx) and pass [`StringComparison.OrdinalIgnoreCase`](https://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase(v=vs.110).aspx) as the type of search to use:
```
string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;
```
Even better is defining a new extension method for string:
```
public static class StringExtensions
{
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source?.IndexOf(toCheck, comp) >= 0;
}
}
```
Note, that [null propagation](https://stackoverflow.com/questions/25666993/c-sharp-null-propagating-operator-conditional-access-expression-if-blocks) `?.` is available since C# 6.0 (VS 2015), for older versions use
```
if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;
```
USAGE:
```
string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);
``` | Case insensitive 'Contains(string)' | [
"",
"c#",
"string",
"contains",
"case-insensitive",
""
] |
Source:
```
<TD>
<A HREF="/home"><IMG SRC="/images/home.gif"></A>
<IMG SRC="/images/spacer.gif">
<A HREF="/search"><IMG SRC="/images/search.gif"></A>
<IMG SRC="/images/spacer.gif">
<A HREF="/help"><IMG SRC="/images/help.gif"></A>
</TD>
```
Regex:
```
(<[Aa]\s+[^>]+>\s*)?<[Ii][Mm][Gg]\s+[^>]+>(?(1)\s*</[Aa]>)
```
Result:
```
<A HREF="/home"><IMG SRC="/images/home.gif"></A>
<IMG SRC="/images/spacer.gif">
<A HREF="/search"><IMG SRC="/images/search.gif"></A>
<IMG SRC="/images/spacer.gif">
<A HREF="/help"><IMG SRC="/images/help.gif"></A>
```
what's the "?(1)" mean?
When I run it in Java ,it cause a exception: java.util.regex.PatternSyntaxException,the
"?(1)" can't be recognized.
The explanation in the book is :
`This pattern requires explanation. (<[Aa]\s+[^>]+>\s*)? matches an opening <A> or <a> tag (with any attributes that may be present), if present (the closing ? makes the expression optional). <[Ii][Mm][Gg]\s+[^>]+> then matches the <IMG> tag (regardless of case) with any of its attributes. (?(1)\s*</[Aa]>) starts off with a condition: ?(1) means execute only what comes next if backreference 1 (the opening <A> tag) exists (or in other words, execute only what comes next if the first <A> match was successful). If (1) exists, then \s*</[Aa]> matches any trailing whitespace followed by the closing </A> tag.` | The syntax is correct. The strange looking (?....) sets up a conditional. This is the regular expression syntax for an if...then statement. The (1) is a back-reference to the capture group at the beginning of the regex, which matches an html <a> tag, if there is one since that capture group is optional. Since the back-reference to the captured tag follows the "if" part of the regex, what it is doing is making sure that there was an opening <a> tag captured before trying to match the closing one. A pretty clever way of making both tags optional, but forcing both when the first one exists. That's how it's able to match all the lines in the sample text even though some of them just have <img> tags.
As to why it throws an exception in your case, most likely the flavor of regex you're using doesn't support conditionals. Not all do.
EDIT: Here's a good reference on conditionals in regular expressions: <http://www.regular-expressions.info/conditional.html> | What you're looking at is a conditional construct, as Bryan said, and Java doesn't support them. The parenthesized expression immediately after the question mark can actually be any zero-width assertion, like a lookahead or lookbehind, and not just a reference to a capture group. (I prefer to call those *back-assertions*, to avoid confusion. A *back-reference* matches the same thing the capture group did, but a back-assertion just asserts that the capture group matched *something*.)
I learned about conditionals when I was working in Perl years ago, but I've never missed them in Java. In this case, for example, a simple alternation will do the trick:
```
(?i)<a\s+[^>]+>\s*<img\s+[^>]+>\s*</a]>|<img\s+[^>]+>
```
One advantage of the conditional version is that you can capture the IMG tag with a single capture group:
```
(?i)(<a\s+[^>]+>\s*)?(<img\s+[^>]+>)(?(1)\s*</a>)
```
In the alternation version you have to have a capturing group for each alternative, but that's not as important in Java as it is in Perl, with all its built-in regex magic. Here's how I would pluck the IMG tags in Java:
```
Pattern p = Pattern.compile(
"<a\\s+[^>]+>\\s*(<img\\s+[^>]+>)\\s*</a>|(<img\\s+[^>]+>)"
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
while (m.find())
{
System.out.println(m.start(1) != -1 ? m.group(1) : m.group(2));
}
``` | Using Condition in Regular Expressions | [
"",
"java",
"regex",
"exception",
""
] |
I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.
I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.
Which is the best way to do this:
1. VBA macro from inside Word to create CSV and then upload to the DB?
2. VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)
3. Python script via win32com then upload to DB?
The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.
**EDIT:** I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:
```
sFile = "D:\temp\output.txt"
fnum = FreeFile
Open sFile For Output As #fnum
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text
Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text
If Target = "" Then
ExportText = ""
Else
ExportText = Descr & Chr(44) & Assign & Chr(44) & _
Target & Chr(13) & Chr(10)
Print #fnum, ExportText
End If
Next n
Close #fnum
```
What's up with the little control character box? Is some kind of character code coming across from Word? | Word has a little marker thingy that it puts at the end of every cell of text in a table.
It is used just like an end-of-paragraph marker in paragraphs: to store the formatting for the entire paragraph.
Just use the Left() function to strip it out, i.e.
```
Left(Target, Len(Target)-1))
```
By the way, instead of
```
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
```
Try this:
```
For Each row in Application.ActiveDocument.Tables(2).Rows
Descr = row.Cells(2).Range.Text
``` | Well, I've never scripted Word, but it's pretty easy to do simple stuff with win32com. Something like:
```
from win32com.client import Dispatch
word = Dispatch('Word.Application')
doc = word.Open('d:\\stuff\\myfile.doc')
doc.SaveAs(FileName='d:\\stuff\\text\\myfile.txt', FileFormat=?) # not sure what to use for ?
```
This is untested, but I think something like that will just open the file and save it as plain text (provided you can find the right fileformat) – you could then read the text into python and manipulate it from there. There is probably a way to grab the contents of the file directly, too, but I don't know it off hand; documentation can be hard to find, but if you've got VBA docs or experience, you should be able to carry them across.
Have a look at this post from a while ago: <http://mail.python.org/pipermail/python-list/2002-October/168785.html> Scroll down to COMTools.py; there's some good examples there.
You can also run makepy.py (part of the pythonwin distribution) to generate python "signatures" for the COM functions available, and then look through it as a kind of documentation. | Extracting data from MS Word | [
"",
"python",
"vba",
"ms-word",
"pywin32",
""
] |
I have a char\* buffer and I am interested in looking at the first byte in the char\* buffer, what is the most optimal way to go about this.
EDIT: Based on the negative votes I might want to explain why this question, I am aware of methods but in the code base that I have been looking for getting first byte people do all kinds of crazy things like do a copy of the buffer , copy it to a stream and then do a get. | Just use
```
char firstByte = buffer[0];
``` | Or this:
```
char firstByte = *buffer;
```
For clarification, there's no difference between `*buffer` and `buffer[0]`, since the latter is really just shorthand for `*(buffer + 0*sizeof(char))`, and any compiler is going to be smart enough to replace that with `*(buffer+0)` and then `*buffer`. So the choice is really whichever is clearest in the context you are using it, not how efficient each one is. | Getting first byte in a char* buffer | [
"",
"c++",
"c",
""
] |
Given a list of objects, I am needing to transform it into a dataset where each item in the list is represented by a row and each property is a column in the row. This DataSet will then be passed to an [Aspose.Cells](http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx) function in order to create an Excel document as a report.
Say I have the following:
```
public class Record
{
public int ID { get; set; }
public bool Status { get; set; }
public string Message { get; set; }
}
```
Given a List records, how do I transform it into a DataSet as follows:
```
ID Status Message
1 true "message"
2 false "message2"
3 true "message3"
...
```
At the moment the only thing I can think of is as follows:
```
DataSet ds = new DataSet
ds.Tables.Add();
ds.Tables[0].Add("ID", typeof(int));
ds.Tables[0].Add("Status", typeof(bool));
ds.Tables[0].Add("Message", typeof(string));
foreach(Record record in records)
{
ds.Tables[0].Rows.Add(record.ID, record.Status, record.Message);
}
```
But this way leaves me thinking there must be a better way since at the very least if new properties are added to Record then they won't show up in the DataSet...but at the same time it allows me to control the order each property is added to the row.
Does anyone know of a better way to do this? | You can do it through reflection and generics, inspecting the properties of the underlying type.
Consider this extension method that I use:
```
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
DataTable dt = new DataTable("DataTable");
Type t = typeof(T);
PropertyInfo[] pia = t.GetProperties();
//Inspect the properties and create the columns in the DataTable
foreach (PropertyInfo pi in pia)
{
Type ColumnType = pi.PropertyType;
if ((ColumnType.IsGenericType))
{
ColumnType = ColumnType.GetGenericArguments()[0];
}
dt.Columns.Add(pi.Name, ColumnType);
}
//Populate the data table
foreach (T item in collection)
{
DataRow dr = dt.NewRow();
dr.BeginEdit();
foreach (PropertyInfo pi in pia)
{
if (pi.GetValue(item, null) != null)
{
dr[pi.Name] = pi.GetValue(item, null);
}
}
dr.EndEdit();
dt.Rows.Add(dr);
}
return dt;
}
``` | I found this code on Microsoft forum. This is so far one of easiest way, easy to understand and use. This has saved me hours. I have customized this as extension method without any change to actual implementaion. Below is the code. it doesn't require much explanation.
You can use two function signature with same implementation
1) public static DataSet ToDataSetFromObject(this **object** dsCollection)
2) public static DataSet ToDataSetFromArrayOfObject( this **object[]** arrCollection). I'll be using this one in below example.
```
// <summary>
// Serialize Object to XML and then read it into a DataSet:
// </summary>
// <param name="arrCollection">Array of object</param>
// <returns>dataset</returns>
public static DataSet ToDataSetFromArrayOfObject( this object[] arrCollection)
{
DataSet ds = new DataSet();
try {
XmlSerializer serializer = new XmlSerializer(arrCollection.GetType);
System.IO.StringWriter sw = new System.IO.StringWriter();
serializer.Serialize(sw, dsCollection);
System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
ds.ReadXml(reader);
} catch (Exception ex) {
throw (new Exception("Error While Converting Array of Object to Dataset."));
}
return ds;
}
```
To use this extension in code
```
Country[] objArrayCountry = null;
objArrayCountry = ....;// populate your array
if ((objArrayCountry != null)) {
dataset = objArrayCountry.ToDataSetFromArrayOfObject();
}
``` | How do I transform a List<T> into a DataSet? | [
"",
"c#",
"list",
"dataset",
"transformation",
""
] |
What is the best way to convert a JSON code as this:
```
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
```
in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).
Any ideas? Should I use Json-lib for that? Or better if I write my own parser? | I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from <http://json.org> (section java) would work.
For one of them (Jackson <https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator>), you'd do:
```
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
```
(where JSON\_SOURCE is a File, input stream, reader, or json content String) | Using the GSON library:
```
import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;
```
Use the following code:
```
Type mapType = new TypeToken<Map<String, Map>>(){}.getType();
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
``` | Convert JSON to Map | [
"",
"java",
"json",
"parsing",
"collections",
""
] |
Is there an easy way to get the type of line ending that the current operating system uses? | If you are operating on a file that you opened in text mode, then you are correct that line breaks all show up as '`\n`'. Otherwise, you are looking for [`os.linesep`](http://docs.python.org/library/os.html) .
From <http://docs.python.org/library/os.html>:
> os.**linesep**
>
> The string used to separate (or, rather, terminate) lines on the
> current platform. This may be a single
> character, such as '\n' for POSIX, or
> multiple characters, for example,
> '\r\n' for Windows. Do not use
> os.linesep as a line terminator when
> writing files opened in text mode (the
> default); use a single '\n' instead,
> on all platforms. | Oh, I figured it out. Apparently, [PEP-278](http://www.python.org/dev/peps/pep-0278/) states the following:
> Any line ending in the input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines. | Python get proper line ending | [
"",
"python",
"line-endings",
""
] |
I have a class of type `ISimpleCache<IBrokeredDataObject>` that I want to add as a type alias (then a type) in the App.Config file
the line
```
<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache<IBrokeredDataObject>, MyApplication" />
```
is obviously wrong due to the <>, however I'm not convinced escaping them;
```
<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache<IBrokeredDataObject>, MyApplication" />
```
is correct either.
I am currently ripping my code apart to use Unity, so am too far from a compilable code base to test this quickly, and was hoping to get some confirmation here. | Check out [this](http://blogs.microsoft.co.il/blogs/gilf/archive/2008/07/25/working-with-generic-types-in-unity-configuration-section.aspx) blog post:
> In order to write a generic type, use the `` ` `` sign followed by the number of generic types that the interface/class receives.
And a comment in the same page said:
> In order to use a constant type in the generic you need to use brackets (`[[ ]]`).
So I guess your configuration file should contain something like this:
```
<typeAlias alias="ISimpleCacheOfIBrokeredDataObject"
type="MyApplication.ISimpleCache`1[[MyApplication.IBrokeredDataObject, MyApplication]], MyApplication" />
```
Note the use of the "grave accent" or "backquote" character (`` ` ``), not the normal single quote (`'`). | I would have rather commented on the answer above, but my score isn't high enough.
The syntax is documented for the Type.GetType Method (string) here: <http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx>
There are a bunch of examples, a few of which I pasted below.
**A generic type with one type argument**
```
Type.GetType("MyGenericType`1[MyType]")
```
**A generic type with two type arguments**
```
Type.GetType("MyGenericType`2[MyType,AnotherType]")
```
**A generic type with two assembly-qualified type arguments**
```
Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
```
**An assembly-qualified generic type with an assembly-qualified type argument**
```
Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
```
**A generic type whose type argument is a generic type with two type arguments**
```
Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")
``` | Including a generic class in Unity App.Config file | [
"",
"c#",
"generics",
"app-config",
"unity-container",
""
] |
I would like to know how Can I paas Page as Ref Parameter to a function
This is what I want to do
```
public partial class HomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!SetupUserPermission.isSessionExpired())
{
string UserId = Session["UserId"].ToString();
SetupUserPermission.SetupUserRights(ref this.Page, Convert.ToInt32(UserId));
}
}
}
``` | You can't pass a property by reference in C#. Why do you want to pass Page by reference in this case?
In VB you *can* pass a property by reference, and the equivalent in this case would be:
```
Page tmp = Page;
SetupUserPermission.SetupUserRights(ref tmp, Convert.ToInt32(UserId));
Page = tmp;
```
Are you really sure you want to do that?
I suspect you don't really want to pass it by reference, and you're just slightly confused about parameter passing. See [my article on the topic](http://pobox.com/~skeet/csharp/parameters.html) for more information. | Why do you want to pass it `ref`? It seems to me that a regular pass should do; this passes the **reference** by value - which is what you want (unless you are creating a new page...).
Also, isn't "`this`" the `Page`? Can't you just:
```
SetupUserPermission.SetupUserRights(this, ...);
```
where `SetupUserRights` takes a `Page`?
See also: Jon Skeet's page on [parameter passing in C#](http://www.yoda.arachsys.com/csharp/parameters.html); that might fix a few misconceptions (hint: `Page` is a *reference-type* (a class)). | How to pass Page as ref parameter to a function | [
"",
"c#",
"asp.net",
""
] |
How is it that Java's `BigDecimal` can be this painful?
```
Double d = 13.3D;
BigDecimal bd1 = new BigDecimal(d);
BigDecimal bd2 = new BigDecimal(String.valueOf(d));
System.out.println("RESULT 1: "+bd1.toString());
System.out.println("RESULT 2: "+bd2.toString());
RESULT 1: 13.300000000000000710542735760100185871124267578125
RESULT 2: 13.3
```
Is there any situation where Result 1 would be desired? I know that Java 1.5 changed the `toString()` method but was this the intended consequence?
Also I realise that `BigDecimal` has `doubleValue()` etc, but the library that I am working with helpfully uses a `toString()` and I can't change that :-(
Cheers. | Well, the [API](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)) does address this apparent inconsistency in the constructor `BigDecimal(double val)`:
> 1. The results of this constructor can be somewhat unpredictable. One might
> assume that writing new
> BigDecimal(0.1) in Java creates a
> BigDecimal which is exactly equal to
> 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal
> to
> 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 **cannot be
> represented exactly as a double** (or,
> for that matter, as a binary fraction
> of any finite length). Thus, the value
> that is being passed in to the
> constructor is not exactly equal to
> 0.1, appearances notwithstanding.
> 2. The String constructor, on the other hand, is perfectly predictable:
> writing new BigDecimal("0.1") creates
> a BigDecimal which is exactly equal to
> 0.1, as one would expect. Therefore, **it is generally recommended that the
> String constructor be used in
> preference to this one.**
> 3. **When a double must be used as a source for a BigDecimal**, note that
> this constructor provides an exact
> conversion; it does not give the same
> result as converting the double to a
> String using the
> Double.toString(double) method and
> then using the BigDecimal(String)
> constructor. To get that result, **use
> the static valueOf(double) method**.
Moral of the story: The pain seems self-inflicted, just use [**`new BigDecimal(String val)`**](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)) or [**`BigDecimal.valueOf(double val)`**](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#valueOf(double)) instead =) | Your problem has nothing to do with `BigDecimal`, and everything with `Double`, which cannot represent 13.3 accurately, since it uses binary fractions internally.
So your error is introduced in the very first line. The first `BigDecimal` simply preserves it, while `String.valueOf()` does some fishy rounding that causes the second one to have the desired content, pretty much through luck. | "new BigDecimal(13.3D)" results in imprecise "13.3000000000000007105.."? | [
"",
"java",
"precision",
"bigdecimal",
""
] |
This question is *NOT* about race-conditions, atomicity, or why you should use locks in your code. I already know about those.
UPDATE: My question isn't "does weirdness with volatile memory exist" (i know it does), my question is "doesn't the .NET runtime abstract that away so you'll never see it".
See <http://www.yoda.arachsys.com/csharp/threads/volatility.shtml>
and the first answer on [Is a string property itself threadsafe?](https://stackoverflow.com/questions/434890/is-a-string-property-itself-threadsafe)
(They're really the same article since one references the other.) One thread sets a bool and the other thread loops forever reading that bool -- those articles claim the reading thread might cache the old value and never read the new value, so therefore you need a lock (or use the volatile keyword). They claim the following code will potentially loop forever.
Now I agree it's good practice to lock your variables, but I can't believe the .NET runtime would really ignore a memory value changing as the article claims. I understand their talk about volatile memory vs non-volatile memory, and I agree they have a valid point in *non-managed* code, but I can't believe the .NET runtime won't correctly abstract that away so that the following code does what you expect.
The article even admits the code will "almost certainly" work (though not guaranteed), so I'm calling BS on the claim. Can anyone verify that it's true the following code won't always work? Is anyone able to get even one case (maybe you can't always reproduce it) where this fails?
```
class BackgroundTaskDemo
{
private bool stopping = false;
static void Main()
{
BackgroundTaskDemo demo = new BackgroundTaskDemo();
new Thread(demo.DoWork).Start();
Thread.Sleep(5000);
demo.stopping = true;
}
static void DoWork()
{
while (!stopping)
{
// Do something here
}
}
}
``` | The point is: it might work, but it isn't **guaranteed** to work by the spec. What people are usually after is code that works for the right reasons, rather than working by a fluke combination of the compiler, the runtime and the JIT, which *might* change between framework versions, the physical CPU, the platform, and things like x86 vs x64.
Understanding the memory model is a very very complex area, and I don't claim to be an expert; but people who **are** real experts in this area assure me that the behaviour you are seeing is not guaranteed.
You can post as many working examples as you like, but unfortunately that doesn't prove much other than "it usually works". It certainly doesn't prove that it is **guaranteed** to work. It would only take a single counter-example to disprove, but finding it is the problem...
~~No, I don't have one to hand.~~
---
Update with repeatable counter-example:
```
using System.Threading;
using System;
static class BackgroundTaskDemo
{
// make this volatile to fix it
private static bool stopping = false;
static void Main()
{
new Thread(DoWork).Start();
Thread.Sleep(5000);
stopping = true;
Console.WriteLine("Main exit");
Console.ReadLine();
}
static void DoWork()
{
int i = 0;
while (!stopping)
{
i++;
}
Console.WriteLine("DoWork exit " + i);
}
}
```
Output:
```
Main exit
```
but still running, at full CPU; note that `stopping` has been set to `true` by this point. The `ReadLine` is so that the process doesn't terminate. The optimization seems to be dependent on the size of the code inside the loop (hence `i++`). It only works in "release" mode obviously. Add `volatile` and it all works fine. | This example includes the native x86 code as comments to demonstrate that the controlling variable ('stopLooping') is cached.
Change 'stopLooping' to volatile to "fix" it.
This was built with Visual Studio 2008 as a Release build and run without debugging.
```
using System;
using System.Threading;
/* A simple console application which demonstrates the need for
the volatile keyword and shows the native x86 (JITed) code.*/
static class LoopForeverIfWeLoopOnce
{
private static bool stopLooping = false;
static void Main()
{
new Thread(Loop).Start();
Thread.Sleep(1000);
stopLooping = true;
Console.Write("Main() is waiting for Enter to be pressed...");
Console.ReadLine();
Console.WriteLine("Main() is returning.");
}
static void Loop()
{
/*
* Stack frame setup (Native x86 code):
* 00000000 push ebp
* 00000001 mov ebp,esp
* 00000003 push edi
* 00000004 push esi
*/
int i = 0;
/*
* Initialize 'i' to zero ('i' is in register edi)
* 00000005 xor edi,edi
*/
while (!stopLooping)
/*
* Load 'stopLooping' into eax, test and skip loop if != 0
* 00000007 movzx eax,byte ptr ds:[001E2FE0h]
* 0000000e test eax,eax
* 00000010 jne 00000017
*/
{
i++;
/*
* Increment 'i'
* 00000012 inc edi
*/
/*
* Test the cached value of 'stopped' still in
* register eax and do it again if it's still
* zero (false), which it is if we get here:
* 00000013 test eax,eax
* 00000015 je 00000012
*/
}
Console.WriteLine("i={0}", i);
}
}
``` | Can a C# thread really cache a value and ignore changes to that value on other threads? | [
"",
"c#",
"multithreading",
""
] |
I've just noticed that `tidy_repair_string()` is removing my non-breaking spaces from empty elements causing my table to collapse. Basically I've put in:
> `<td> </td>`
and HTML Tidy is stripping them out to:
```
<td> </td>
```
which may or may not be some Unicode break but either way it's collapsing. The only ` ` related option I've seen is 'quote-nbsp' but that doesn't seem to be it. I think it defaults to on anyway.
How do I keep my non-breaking spaces? | Apply this style, then you do not need to put content in the "empty" cells:
td { [empty-cells](http://www.w3schools.com/Css/pr_tab_empty-cells.asp): show; } | use the "bare" config option.
more information and an explanation available here: <http://osdir.com/ml/web.html-tidy.user/2004-07/msg00005.html> | How to keep my non-breaking spaces with HTML Tidy (PHP)? | [
"",
"php",
"html",
"htmltidy",
""
] |
I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...
I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).
Can anyone shed some light on how to enable this mode in the interpreter? | Ctrl-Alt-J switches from Emacs mode to Vi mode in [readline programs](http://tiswww.case.edu/php/chet/readline/rluserman.html#SEC22).
Alternatively add "set editing-mode vi" to your ~/.inputrc | This kind of all depends on a few things.
First of all, the python shell uses readline, and as such, your `~/.inputrc` is important here. That's the same with psql the PostgreSQL command-line interpreter and mysql the MySQL shell. All of those can be configured to use vi-style command bindings, with history etc.
`<ESC>` will put you into vi mode at the python shell once you've got your editing mode set to vi
You may need the following definition in your `~/.inputrc`
```
set editing-mode vi
```
**OSX info**
OSX uses libedit which uses ~/.editrc. You can *man editrc* for more information.
For example, to mimick a popular key combination which searches in your history, you can add the following to your .editrc
```
bind "^R" em-inc-search-prev
``` | Standard python interpreter has a vi command mode? | [
"",
"python",
"vi",
""
] |
**Note**
I'm running windows, the path just looks like it's linus because I typed it manually and thats how I think of paths.
I'm trying to run a java class That I have built to diagnose my connection to a databse, it references the oracle jdbc adaptor.
When I just run it without a class path:
```
%> java DBDiagnostics <connectionString>
```
I get an exception when it reaches the following line of code:
```
Class.forName("oracle.jdbc.pool.OracleDataSource").newInstance();
```
with the following exception:
```
java.lang.ClassNotFoundException: oracle.jdbc.pool.OracleDataSource
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at DBDiagnostics.GetConnection(DBDiagnostics.java:43)
at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)
at DBDiagnostics.main(DBDiagnostics.java:18)
Creating connection.
java.sql.SQLException: No suitable driver found for lskd
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at DBDiagnostics.GetConnection(DBDiagnostics.java:55)
at DBDiagnostics.runDiagnostic(DBDiagnostics.java:29)
at DBDiagnostics.main(DBDiagnostics.java:18)
Veryfying connectivity to Database
Exception in thread "main" java.lang.NullPointerException
at DBDiagnostics.verifyTable(DBDiagnostics.java:86)
at DBDiagnostics.verifyTable(DBDiagnostics.java:76)
at DBDiagnostics.verifyDatabseConnectivity(DBDiagnostics.java:68)
at DBDiagnostics.runDiagnostic(DBDiagnostics.java:36)
at DBDiagnostics.main(DBDiagnostics.java:18)
```
I assume that this is because I need to include it in the classpath.
So, I tried adding it to the classpath like this:
```
%> java -classpath .:ojdbc6.jar DBDiagnostics <connectionString>
```
The VM just says it cant find the class:
```
Exception in thread "main" java.lang.NoClassDefFoundError: DBDiagnostics
Caused by: java.lang.ClassNotFoundException: DBDiagnostics
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: DBDiagnostics. Program will exit.
```
I know this is a question I should just know the answer to, but what am I doing wrong? | Replace the colon with a semicolon:
```
java -classpath .;ojdbc6.jar DBDiagnostics <connectionString>
``` | is there a typo:
```
%> java -classpath .:ojdbc6.jar DBDiagnostics <connectionString>
```
maybe it would work if you type this:
```
%> java -classpath ./ojdbc6.jar DBDiagnostics <connectionString>
``` | Running a java program at the command line, what am I doing wrong? | [
"",
"java",
"classpath",
""
] |
I want to submit a with using jquery as below;
```
$("#formid").submit();
```
Its working perfect in all browsers except IE6.
How to make it work in IE6 ?? | You probably have an `<input name="submit" />` somewhere in your form, which overwrites the function "submit" of the form in IE.
**Edit:**
I have tested in some other browsers. The latest versions of all major browsers seem to be affected by this issue.
* IE - all versions
* Firefox 4+
* Chrome at least since version 12
* Opera at least since version 11
Bottom line: Never name your inputs "submit", or any other default property or method of the form element (e.g. "action" or "reset") . See [MDC](https://developer.mozilla.org/en/DOM/HTMLFormElement) for a complete overview. | I had a similar problem when I was about to submit the form via an A-element. I had set the href attribute to "javascript:;" to let the main jQuery script handle the actual submit but it just wouldn't work in IE6.
jQuery main script:
```
$(".submitLink").click(function(){
$(this).parent()[0].submit();
$(this).addClass("loading");
});
```
My solution was to change the href attribute from "javascript:;" to "#". | jQuery form submit() is not working in IE6? | [
"",
"javascript",
"jquery",
"html",
"internet-explorer-6",
""
] |
Which is the preferred/recommended way of handling events in .NET:
```
this.Load += new EventHandler(Form1_Load);
private void Form1_Load(object sender, EventArgs e)
{ }
```
**or**
```
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
```
What would the pros/cons of each method be? I've used both methods over the years, and have usually leaned more towards the first method simply because that is what Visual Studio creates automatically for handling events. Are there any benefits to the second method that I am missing though? | The first way is what Microsoft suggests. The pattern is:
1. some code wants to raise an event, calls OnXxx
2. OnXxx makes a call to the delegate
3. Wired event handlers are called
If you perform the second model, you risk forgetting the base.OnXxx call and breaking everything. Nice part of option 2 is that you get to decide if you are called before or after all of the other event handlers. If you put your code before the base.OnXxx, you get executed before the event does. Of course the first model can be used always, the second only if you are subclassing the class raising the event. | It depends entirely on where you want to catch the event and why.
The first method (wire-up) is for when you want *some other class* to handle the event. And you may need to do that for a number of reasons; the other class may have access to services that perform some complex logic or whatever. The point is that you use the first method when you want a separate observer to respond to the event.
The second method (overriding) is for when you want the form to respond because it can; because it's responsibility is local. | What is the preferred method for event handling in C#? | [
"",
"c#",
"winforms",
"event-handling",
""
] |
I have been using the mysql api in PHP, and am now converting to mysqli for the increased security. The example syntax I have seen uses printf, and I would like to know if this is necessary. At the moment I use echo, like so:
```
echo "<h1>".$row['ARTICLE_NAME']."</h1>
<div id='leftlayer' class='leftlayer'>
<p><strong>Username: </strong>".$row['USERNAME']."
<p><strong>Article Number: </strong>".$row['ARTICLE_NO']."
<p><strong>Subtitle: </strong>".$row['SUBTITLE']."
<p><strong>Auction Start: </strong>".$row['ACCESSSTARTS']."
</div>";
```
Since with mysqli you must bind variables to the result, I have done this like so:
```
$getRecords->bind_result($ARTICLE_NO, $ARTICLE_NAME, $SUBTITLE$, $CURRENT_BID, $START_PRICE, $BID_COUNT, $QUANT_TOTAL, $QUANT_SOLD, $ACCESSSTARTS, $ACCESSENDS, $ACCESSORIGIN_END, $USERNAME, $BEST_BIDDER_ID, $FINISHED$, $WATCH$$, $BUYITNOW_PRICE, $PIC_URL, $PRIVATE_AUCTION, $AUCTION_TYPE, $ACCESSINSERT_DATE, $ACCESSUPDATE_DATE, $CAT_DESC$, $CAT_PATH, $ARTICLE_DESC, $COUNTRYCODE, $LOCATION$, $CONDITIONS, $REVISED$, $PAYPAL_ACCEPT, $PRE_TERMINATED, $SHIPPING_TO, $FEE_INSERTION, $FEE_FINAL$, $FEE_LISTING, $PIC_XXL$, $PIC_DIASHOW, $PIC_COUNT, $ITEM_SITE_ID);
```
and would like to know if I could simply replace my reference to $row with the bound variable, for example:
```
<p><strong>Username: </strong>".$USERNAME."
```
Are there any security problems with this approach, or is it fine | I'm not sure that binding makes your application more secure when you are getting data out of the database, however it will help when you are writing into the DB as you will have no risk of SQL injection.
Whatever approach you take to reading from the DB, you still need to escape the output using `htmlspecialchars()` if you are not entirely certain that the data is completely clean. The bound statement will not handle this as you suggest in your comment to Ionut - you have to escape the data in a way that is applicable to where you are outputting it. PHP/MySQL doesn't know whether you are printing into an HTML document/shell command/json/etc. There isn't an magic escape method that makes any data safe for any output medium. | I agree that mysqli is--at least in principle--better than the mysql package because you can bind parameters, which is both more secure and better for query execution. That being said, I've discovered at least two serious issues with mysqli:
* [Bug 46808](http://bugs.php.net/bug.php?id=46808) is a serious problem that has been reported in different ways for **at least three years** and still hasn't been fixed yet. If you want to use LONGTEXT columns you may have a problem; and
* Sometimes I just get weird bugs where mysqli fails (with meaningless messages about errors in "canary form" or somesuch). It's at this point (combined with (1)) that I just had to give up on mysqli.
PDO is probably a better choice. Me? I just went back to mysql. It's hard to argue with the simplicity as long as you're careful with escaping strings and so on. | converting from mysql to mysqli - outputting variables | [
"",
"php",
"mysql",
"mysqli",
""
] |
I've got a custom object (example only code for ease of understanding) ...
```
public class MyClass
{
private string name;
private int increment;
private Guid id;
public string Name
{
get { return name; }
set { name = value; }
}
public int Increment
{
get { return increment; }
set { increment = value; }
}
public Guid Id
{
get { return id; }
set { id = value; }
}
}
```
... and a custom collection of this class ...
```
public class MyClassCollection : Collection<MyClass>
{
}
```
I was looking to write a Sort routine for the collection which will have the following public method ...
```
public void Sort(params string[] sortProperties)
{
if (sortProperties == null)
{
throw new ArgumentNullException("sortProperties", "Parameter must not be null");
}
if ((sortProperties.Length > 0) && (Items.Count > 1))
{
foreach (string s in sortProperties)
{
// call private sort method
Sort(s);
}
}
}
```
... and the private Sort method would take a parameter of the property name ...
```
private void Sort(string propertyName)
{
}
```
What I want to do is be able to pass in a set of property names into the method ...
```
MyClassCollection current = new MyClassCollection();
// setup a objects in the collection
current = GetCollectionData();
// sort by Name, then by Increment
current.Sort("Name", "Increment");
```
Using the property names passed into the method I want to be able to check to see if it has a property of that name, if so work out what type it is and then run through a sort of it.
The interim workaround which I have currently got is ...
```
private void Sort(string propertyName)
{
// convert to List
List<MyClass> myCurrentClass = Items as List<MyClass>;
// sort
if (myCurrentClass != null)
{
switch (propertyName)
{
case "Name":
myCurrentClass.Sort(delegate(MyClass myClassOne, MyClass myClassTwo)
{
return
Comparer<string>.Default.Compare(myClassOne.Name,
myClassTwo.Name);
}
);
break;
case "Increment":
myCurrentClass.Sort(delegate(MyClass myClassOne, MyClass myClassTwo)
{
return
Comparer<int>.Default.Compare(myClassOne.Increment,
myClassTwo.Increment);
});
break;
}
}
}
```
... but ideally I would like to switch on the underlying type of the Property (string, int etc.) and using a distinct number of delegate calls for the types for sorting. I've looked around but I've not found anything which points me in the right direction. I've had a look at reflection but I couldn't see anything which would be able to help me.
Is this even possible? and if so, how?!
Cheers! | After hitting my head against the problem for a while and hoping on a train home last night I decided that I would try and bash out an answer. Using a combination of Jon's pointers and Frederik's use of the PropertyInfo class and keeping the original idea of switching on the underlying object type, this is what I came up with ...
```
private void Sort_version2(string propertyName)
{
// convert to list
List<MyClass> myCurrentClass = Items as List<MyClass>;
string typeOfProperty;
PropertyInfo pi;
// sort
if ((myCurrentClass != null) && (MyClass.HasDetailAndExtract(propertyName, out typeOfProperty, out pi)))
{
switch(typeOfProperty)
{
case "System.String":
myCurrentClass.Sort(delegate(MyClass one, MyClass two)
{
return
Comparer<string>.Default.Compare(pi.GetValue(one, null).ToString(),
pi.GetValue(two, null).ToString());
});
break;
case "System.Int32":
myCurrentClass.Sort(delegate (MyClass one, MyClass two)
{
return
Comparer<int>.Default.Compare(
Convert.ToInt32(pi.GetValue(one, null)),
Convert.ToInt32(pi.GetValue(two, null)));
});
break;
default:
throw new NotImplementedException("Type of property not implemented yet");
}
}
}
```
I've documented the thought process and more details on [my blog](http://westdiscgolf.blogspot.com/2009/01/accessing-object-properties-from-string.html) let me know what you think!
Thanks to Jon and Frederik for the help :-) | Reflection would be the way to go - look at `Type.GetProperty(string name)`. Creating the right comparer might be tricky after that - you might want to write a generic method, and then invoke that with reflection based on the property type. It all gets pretty icky, I'm afraid - but it's definitely feasible. | Accessing object properties from string representations | [
"",
"c#",
"generics",
"reflection",
"sorting",
""
] |
Is there a way to do `foreach` style iteration over lined up enumerables in C#? For subscriptable lists, I know one could use a regular `for` loop iterating an int over the index range, but I really prefer `foreach` to `for` for a number of reasons.
Bonus points if it works in C# 2.0.
**Clarification:** I am talking about multiple lined up enumerables. Like arrays of pencils and papers. I want each pencil to write on the corresponding paper.
**Note:** Originally this question used the term *parallel* instead of *lined up*. | Short answer, no. `foreach` works on only one enumerable at a time.
However, if you combine your parallel enumerables into a single one, you can `foreach` over the combined. I am not aware of any easy, built in method of doing this, but the following should work (though I have not tested it):
```
public IEnumerable<TSource[]> Combine<TSource>(params object[] sources)
{
foreach(var o in sources)
{
// Choose your own exception
if(!(o is IEnumerable<TSource>)) throw new Exception();
}
var enums =
sources.Select(s => ((IEnumerable<TSource>)s).GetEnumerator())
.ToArray();
while(enums.All(e => e.MoveNext()))
{
yield return enums.Select(e => e.Current).ToArray();
}
}
```
Then you can `foreach` over the returned enumerable:
```
foreach(var v in Combine(en1, en2, en3))
{
// Remembering that v is an array of the type contained in en1,
// en2 and en3.
}
``` | .NET 4's BlockingCollection makes this pretty easy. Create a BlockingCollection, return its .GetConsumingEnumerable() in the enumerable method. Then the foreach simply adds to the blocking collection.
E.g.
```
private BlockingCollection<T> m_data = new BlockingCollection<T>();
public IEnumerable<T> GetData( IEnumerable<IEnumerable<T>> sources )
{
Task.Factory.StartNew( () => ParallelGetData( sources ) );
return m_data.GetConsumingEnumerable();
}
private void ParallelGetData( IEnumerable<IEnumerable<T>> sources )
{
foreach( var source in sources )
{
foreach( var item in source )
{
m_data.Add( item );
};
}
//Adding complete, the enumeration can stop now
m_data.CompleteAdding();
}
```
Hope this helps.
BTW I [posted a blog about this](http://andrevdm.blogspot.com/2009/11/blockingcollection-parallel-yields.html) last night
Andre | Combined iteration over lined up enumerables in C#? | [
"",
"c#",
"loops",
"foreach",
"iteration",
"enumerable",
""
] |
How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times. | Here's a modified [`@ʞɔıu`'s answer](https://stackoverflow.com/questions/537542/how-can-i-create-multiple-hashes-of-a-file-using-only-one-pass/537585#537585) using [`@Jason S`' suggestion](https://stackoverflow.com/questions/537542/how-can-i-create-multiple-hashes-of-a-file-using-only-one-pass/537597#537597).
```
from __future__ import with_statement
from hashlib import md5, sha1
filename = 'hash_one-pass.py'
hashes = md5(), sha1()
chunksize = max(4096, max(h.block_size for h in hashes))
with open(filename, 'rb') as f:
while True:
chunk = f.read(chunksize)
if not chunk:
break
for h in hashes:
h.update(chunk)
for h in hashes:
print h.name, h.hexdigest()
``` | Something like this perhaps?
```
>>> import hashlib
>>> hashes = (hashlib.md5(), hashlib.sha1())
>>> f = open('some_file', 'r')
>>> for line in f:
... for hash in hashes:
... hash.update(line)
...
>>> for hash in hashes:
... print hash.name, hash.hexdigest()
```
or loop over f.read(1024) or something like that to get fixed-length blocks | How can I create multiple hashes of a file using only one pass? | [
"",
"python",
"hash",
""
] |
What does Assembly.GetExportedTypes() do? How is it different from Assembly.GetTypes()
Can you explain with example? | GetExportedTypes() does not include protected/private/internal types. As per the question linked in Alexander's question below, internal types are not included even if would be visible to an assembly via InternalsVisibleToAttribute.
GetTypes() includes all types. | `GetExportedTypes()` returns only types which are visible outside the assembly in question. "Visible" means public types and public types nested within other public types. | Assembly.GetExportedTypes vs GetTypes | [
"",
"c#",
".net",
""
] |
I want to pass a `byte[]` to a method takes a `IntPtr` Parameter in C#, is that possible and how? | Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:
```
IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);
```
Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.
**Edit:** Also, as Tyalis pointed out, you can also use *fixed* if unsafe code is an option for you | Another way,
```
GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// Do your stuff...
pinnedArray.Free();
``` | How to get IntPtr from byte[] in C# | [
"",
"c#",
".net",
""
] |
Consider the following table:
```
create table temp
(
name int,
a int,
b int
)
insert into temp (name, a, b)
values (1, 2, 3)
insert into temp (name, a, b)
values (1, 4, 5)
insert into temp (name, a, b)
values (2, 6, 7)
```
I want to select \*(all fields) with distinct [name]. In the case of two or more rows having the same [name], to choose whether to display the first (1, 2, 3) or the second row(1, 4, 5) the rule can be to choose the one with greater [b].
Can you point how must I write this stored procedure? | Here is one way to do this
sql 2000 and up version
```
select t1.* from(
select name,max(B) as MaxB
from temp
group by name) t2
join temp t1 on t1.a = t2.MaxB
and t1.name = t2.name
```
SQL 2005 and up version
```
select name, a, b
from (
select m.*,
row_number() over (
partition by name
order by B desc) as rn
from temp m
) m2
where m2.rn = 1;
``` | ```
SELECT t.*
FROM temp t
INNER JOIN (
SELECT name, max(b) as b
FROM temp
GROUP BY name
) m
ON t.name = m.name
AND t.b = m.b
```
Not exactly fast on big tables, unless you have an index on name, b. | How to select distinct elements when they appear repeated in a table? (T-SQL) | [
"",
"sql",
"t-sql",
"stored-procedures",
""
] |
I want to get the distinct values in a list, but not by the standard equality comparison.
What I want to do is something like this:
```
return myList.Distinct( (x, y) => x.Url == y.Url );
```
I can't, there's no extension method in Linq that will do this - just one that takes an `IEqualityComparer`.
I can hack around it with this:
```
return myList.GroupBy( x => x.Url ).Select( g => g.First() );
```
But that seems messy. It also doesn't quite do the same thing - I can only use it here because I have a single key.
I could also add my own:
```
public static IEnumerable<T> Distinct<T>(
this IEnumerable<T> input, Func<T,T,bool> compare )
{
//write my own here
}
```
But that does seem rather like writing something that should be there in the first place.
Anyone know why this method isn't there?
Am I missing something? | It's annoying, certainly. It's also part of my "MoreLINQ" project which I must pay some attention to at some point :) There are plenty of other operations which make sense when acting on a projection, but returning the original - MaxBy and MinBy spring to mind.
As you say, it's easy to write - although I prefer the name "DistinctBy" to match OrderBy etc. Here's my implementation if you're interested:
```
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector,
EqualityComparer<TKey>.Default);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (keySelector == null)
{
throw new ArgumentNullException("keySelector");
}
if (comparer == null)
{
throw new ArgumentNullException("comparer");
}
return DistinctByImpl(source, keySelector, comparer);
}
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>
(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
``` | > But that seems messy.
It's not messy, it's correct.
* If you want `Distinct` Programmers by FirstName and there are four Amy's, which one do you want?
* If you `Group` programmers By FirstName and take the `First` one, then it is clear what you want to do in the case of four Amy's.
> I can only use it here because I have a single key.
You can do a multiple key "distinct" with the same pattern:
```
return myList
.GroupBy( x => new { x.Url, x.Age } )
.Select( g => g.First() );
``` | Why is there no Linq method to return distinct values by a predicate? | [
"",
"c#",
"linq",
"distinct",
""
] |
It would be very useful to be able to overload the . operator in C++ and return a reference to an object.
You can overload `operator->` and `operator*` but not `operator.`
Is there a technical reason for this? | See [this quote from Bjarne Stroustrup](http://www.stroustrup.com/bs_faq2.html#overload-dot):
> Operator . (dot) could in principle be overloaded using the same
> technique as used for ->. However, doing so can lead to questions
> about whether an operation is meant for the object overloading . or an
> object referred to by . For example:
>
> ```
> class Y {
> public:
> void f();
> // ...
> };
>
> class X { // assume that you can overload .
> Y* p;
> Y& operator.() { return *p; }
> void f();
> // ...
> };
>
> void g(X& x)
> {
> x.f(); // X::f or Y::f or error?
> }
> ```
>
> This problem can be solved in several ways. At the time of
> standardization, it was not obvious which way would be best. For more
> details, see [The Design and Evolution of C++](http://www.stroustrup.com/dne.html). | Stroustrup said C++ should be an extensible, but not mutable language.
The dot (attribute access) operator was seen as too close to the core of the language to allow overloading.
See [The Design and Evolution of C++](http://www.google.com/search?q=The+Design+and+Evolution+of+C%2B%2B), page 242, section *11.5.2 Smart References*.
> When I decided to allow overloading of operator `->`, I naturally considered whether operator `.` could be similarly overloaded.
>
> At the time, I considered the following arguments conclusive: If `obj` is a class object then `obj.m` has a meaning for every member `m` of that object's class. We try not to make the language mutable by redefining built-in operations (though that rule is violated for `=` out of dire need, and for unary `&`).
>
> If we allowed overloading of `.` for a class `X`, we would be unable to access members of `X` by normal means; we would have to use a pointer and `->`, but `->` and `&` might also have been re-defined. I wanted an extensible language, not a mutable one.
>
> These arguments are weighty, but not conclusive. In particular, in 1990 Jim Adcock proposed to allow overloading of operator `.` *exactly* the way operator `->` is.
The "I" in this quote is Bjarne Stroustrup. You cannot be more authoritative than that.
If you want to really understand C++ (as in "why is it this way"), you should absolutely read this book. | Why can't you overload the '.' operator in C++? | [
"",
"c++",
"operator-overloading",
""
] |
Which query would run faster?
```
SELECT * FROM topic_info
LEFT JOIN topic_data ON topic_info.id = topic_data.id
WHERE id = ?
```
or
```
SELECT * FROM topic_info
LEFT JOIN topic_data ON topic_data.id = topic_info.id
WHERE id = ?
```
The difference is the order of expressions on the "ON" clause: the first query is checking topic\_info.id against topic\_data.id, the second topic\_data.id against topic\_info. Which query would generally run faster?
(I know either query won't parse because of the ambiguous "id" column, but let's ignore that) | I don't think it should make a difference. Pick a convention and stick with it. | It **probably** doesn't matter, but do test it out.
If you use MySQL, try 'explain select ...' -- it'll tell you what you need to know. | SQL "ON" Clause Optimization | [
"",
"sql",
"mysql",
"optimization",
"join",
""
] |
I have a query where i want to get a distinct description by the latest date entered and the descriptions ID. I can get the disctinct part but i run into trouble with trying to get the ID since im using MAX on the date. Here is the query:
```
SELECT DISTINCT Resource.Description, MAX(arq.DateReferred) AS DateReferred, arq.AssessmentResourceID
FROM AssessmentXResource AS arq
INNER JOIN Resource ON arq.ResourceID = Resource.ResourceID
INNER JOIN Assessment AS aq
INNER JOIN [Case] AS cq ON aq.CaseID = cq.CaseID
INNER JOIN [Plan] AS pq ON cq.CaseID = pq.CaseID ON arq.AssessmentID = aq.AssessmentID
WHERE (pq.PlanID = 22)
GROUP BY Resource.Description, arq.AssessmentResourceID
ORDER BY Resource.Description
```
Im sure its simple but im not seeing it. | ```
SELECT
Resource.Description,
arq.DateReferred AS DateReferred,
arq.AssessmentResourceID
FROM
Resource
INNER JOIN
AssessmentXResource AS arq
ON arq.ResourceID = Resource.ResourceID
AND arq.DateReferred = (
SELECT
MAX(DateReferred)
FROM
AssessmentXResource
WHERE
ResourceID = Resource.ResourceID
)
INNER JOIN
Assessment AS aq
ON arq.AssessmentID = aq.AssessmentID
INNER JOIN
[Case] AS cq
ON aq.CaseID = cq.CaseID
INNER JOIN
[Plan] AS pq
ON cq.CaseID = pq.CaseID
WHERE
(pq.PlanID = 22)
ORDER BY
Resource.Description
``` | I doni't see a reason for the join to the [Case] table, so I've left that out. You can add it back if you need it for some reason.
```
SELECT
RES.Description,
ARQ.DateReferred,
ARQ.AssessmentResourceID
FROM
AssessmentXResource ARQ
INNER JOIN Resource ON
ARQ.ResourceID = RES.ResourceID
INNER JOIN Assessment AQ ON
AQ.AssessmentID = ARQ.AssessmentID
INNER JOIN [Plan] PQ ON
PQ.CaseID = AQ.CaseID
LEFT OUTER JOIN AssessmentXResource ARQ2 ON
ARQ2.ResourceID = ARQ.ResourceID AND
ARQ2.DateReferred > ARQ.DateReferred
WHERE
PQ.PlanID = 22 AND
ARQ2.ResourceID IS NULL
```
This may not act as hoped if there are identical DateReferred values for the same ResourceID in your data. You should come up with a business rule for that situation and change the query appropriately for it. Also, this will act slightly different from your query if it's not guaranteed that you have matching rows in the Assessment, Plan, and Case tables for your AssessmentXResource rows. You can make it work by adding in joins to ARQ2 for those, but that will affect performance and is also a little more complex. If you need that then post a comment and I can alter the query to handle it or maybe you can figure it out on your own. | Getting Distinct records with date field? | [
"",
"sql",
"distinct",
"max",
""
] |
Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.
What is the best dependency analysis tool for Python code? | I recommend using [snakefood](http://furius.ca/snakefood/) for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation.
Of course, you can omit the graph-creation step and receive a dependency dictionary in a file instead. | I don't know what is the *best* dependency analysis tool. You could look into `modulefinder` – it's a module in the standard library that determines the set of modules imported by a script.
Of course, with python you have problems of conditional imports, and even potentially scripts calling `__import__` directly, so it may not find everything. This is why tools like py2exe need special help to cope with packages like PIL. | Is there a good dependency analysis tool for Python? | [
"",
"python",
"dependencies",
""
] |
I've only written a small amount of JavaScript that runs embedded in a Java application, but it was tested using [QUnit](http://docs.jquery.com/QUnit), has been mixed, and I've not noticed any problems yet.
Is there some conventional wisdom whether to use semicolons or not in JavaScript? | **Use them. Use them constantly.**
It's far too easy to have something break later on because you neglected a semi-colon and it lost the whitespace which saved it before in a compression/generation/eval parse. | I'd say use them all the time; most code you'll encounter uses them, and consistency is your friend. | Should I use semicolons in JavaScript? | [
"",
"javascript",
""
] |
I'm attempting to create my first "real" C# application - a small pet project to help schedule peer reviews at work.
Due to the insane amount of process/bureaucracy involved in implementing anything new - as well as the fact that I'm doing this away from managements eyes, on my own time, for the time being - I'm going to be writing this with an ~~MS Access~~ MS Jet Engine backend (i.e. an access mdb file) due to restrictions on how I can deploy this application to my co-workers.
My question is: how do I poll the database intermittently to grab updates (new requested reviews, messages from other developers requesting info, etc.) from the database?
Should I just drop a Timer on each form that needs the info and refresh everything when an update has occurred?
**Edit:**
I'm looking for advice specifically on how to implement the timer. I can't install things on workstations, I don't have access to servers (outside of storage space), and I can't host this myself due to the company's security requirements since our client has ridiculous DoD restrictions.
I guess I've figured this out anyway, since the "timer on form" solution works just fine (I don't know what I was thinking when I said I wanted a secondary solution for a CLI version as it clearly isn't needed.. it's very late).
Thanks! | You could start a background worker thread to do the refreshes in an infinite loop, and sleep at the end (or beginning) of each loop iteration. | orrite.. i'll crumble.
my best suggestion to poll the access data store would be to use a System.IO.FileSystemWatcher to monitor the folder where the mdb file lives. this way you can craft your code to poll at an interval but only when the Changed event fires. this should chew less cpu and disk access.
hope this helps. :D | Polling database for updates from C# application | [
"",
"c#",
"jet",
"polling",
""
] |
I read this without finding the solution: <http://docs.python.org/install/index.html> | I think the current right way to do this is by `pip` like Pramod comments
```
pip install beautifulsoup4
```
because of last changes in Python, see discussion [here](https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install).
This was not so in the past. | The "normal" way is to:
* Go to the Beautiful Soup web site, <http://www.crummy.com/software/BeautifulSoup/>
* Download the package
* Unpack it
* In a Terminal window, `cd` to the resulting directory
* Type `python setup.py install`
Another solution is to use `easy_install`. Go to <http://peak.telecommunity.com/DevCenter/EasyInstall>), install the package using the instructions on that page, and then type, in a Terminal window:
```
easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup
```
`easy_install` will take care of downloading, unpacking, building, and installing the package. The advantage to using `easy_install` is that it knows how to search for many different Python packages, because it queries the [PyPI](http://pypi.python.org/) registry. Thus, once you have `easy_install` on your machine, you install many, many different third-party packages simply by one command at a shell. | How can I install the Beautiful Soup module on the Mac? | [
"",
"python",
"macos",
"module",
"installation",
""
] |
I need to create an administrative site for managing my web site's db. I don't want to build this myself, I simply want the framework in place so that I can add customization myself after it is in place.
Django has a great auto-generated admin. What's an equivalent auto-generated admin site built under asp.net? | <http://www.asp.net/dynamicdata/>
Scaffolding (CRUD) for all tables, or optionally only the ones you choose. | You could use [ASP.NET Dynamic Data](http://www.asp.net/dynamicdata/) to do something similar. | ASP.Net auto-generated Admin tool | [
"",
"c#",
"asp.net",
""
] |
There is a question regarding usage of functional programming techiques in C# code. Example
Let we have interface
```
interface IGraph { /*contains vertices and edges*/}
```
Suppose we need to layout graph's vertices (assign Point to each vertex).
```
interface ILayoutInfo {
Point GetVertexPoint(vertex);
}
```
Simple layout route can have such signature:
```
ILayoutInfo SimpleLayout(IGraph graph);
```
Which can be used in such way
```
void Demo() {
IGraph graph = CreateGraphInAnyWay();
ILayoutInfo layout = SimpleLayout(graph);
PrintCoordinates(graph,layout);
}
```
In design below PrintCoordinates need both references to graph and layout.
Consider functional style design where layouting routing augments graph information
with information about graph vertices coordenates.
```
ILayoutedGraph SimpleLayoutNew(IGraph graph);
```
Where ILayoutedGraph implements BOTH IGraph and ILayoutInfo
```
void DemoNew() {
IGraph graph = CreateGraphInAnyWay();
ILayoutedGraph layoutedGraph = SimpleLayoutNew(graph);
PrintCoordinatesNew(layoutedGraph);
}
```
1)In this design PrintCoordinatesNew gets only ONE parameter.
2)Weird interface ILayoutedGraph was born which doesn't contain any methods and just
wraps other interfaces. If some library has other types like INetwork, ITree we end up
creating wrap interfaces ILayoutedNetwork, ILayoutedTree (which is bad).
So such techique is used only in functinal languages just because they can't work in other way (there are no state so function must combine input with calculated info to be used by outer routines) or it is viable in imperative world too?
Thanks a lot,
PS: a more verbose pretty printed example can be found here
<http://tivadj.blogspot.com/2009/02/designing-c-api-in-functional-style.html> | If seems that what disturbs you when passing two arguments is that your layout (ILayoutInfo) is linked to the graph used to generate it. I would be meaningless to pass a layout with a graph that was not used to generate it.
In this case, you can keep a reference to the graph in the layout info, and provide an accessor on the ILayoutInfo interface.
This way, you can only pass the ILayoutInfo instance, and you PrintCoordinates function can still acces the graph that was used to generate the ILayoutInfo.
If you have other kind of object that can generate layout infos, use a common interface for them, or make the ILayoutInfo generic. | There is no problem with your original API of
```
void Demo() {
IGraph graph = CreateGraphInAnyWay();
ILayoutInfo layout = SimpleLayout(graph);
PrintCoordinates(graph,layout);
}
```
It is perfectly functional. An imperative API would involve a change to `graph` once it is created. Eg
```
void Demo() {
IGraph graph = CreateGraphInAnyWay();
graph.Layout(new SimpleLayout()); // changes the state of graph
PrintCoordinates(graph);
}
```
As for the problem of ILayoutedGraph, ILayoutedTree, ILayoutedQueue, etc, I think you would get around this by generic classes in a functional languages and multiple inheritance in the OO languages where this is allowed.
Personally, I would recommend generics: `ILayout<a>` where `a` is something with edges that needs to be laid out. | Functional style C# API design (returning function parameter augmented with calculation result) | [
"",
"c#",
"functional-programming",
"method-chaining",
""
] |
I am creating a php/mysql application for a university project and I am looking for any possible solution to allow users to buy from my site . | [PayPal](https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/home_US) has a number of solutions for you, including services for Payflow Pro. | Are you planning on writing the shopping cart as well?
We have been evaluating the Magento E-Commerce Platform, our initial tests show that it is pretty robust. It supports a bunch of payment gateway options.
Check it out... <http://www.magentocommerce.com/> | Php payment solutions? | [
"",
"php",
"paypal",
""
] |
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.
What format would be the best for these config files?
Here is my quantification of best:
1. Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.
2. Remains easily read by humans even when there are a large amount of entries
3. Is a widely used standard, no custom formats
4. Succinctness is appreciated
I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there. | How about an INI file format? It's a de facto configuration file standard, and PHP has a built-in parser for that format:
[parse\_ini\_file](http://us.php.net/parse_ini_file) | YAML is a good option:
<http://www.yaml.org/>
It's very simple and powerful, too
Ruby projects use it a lot for configuration. | What's Is the Best File Format for Configuration Files | [
"",
"php",
"configuration",
"file-format",
""
] |
I get a DataTable from a DataSet and then bind that DataTable to a DataGridView. Once the user edits the information on the DataGridView how do I take those changes and put them back into a DataTable that was used that I can then put back into my DataSet?
I want to make a Save Button on my DataGrid that when pressed actually saves the changes.
I don't if I can get anymore specific than that, because it is a fairly simple question.
Thanks in advance!
Let me know if you need me to elaborate more. | If you are using data-binding to a `DataGridView`, then you are *already* updating the `DataTable` / `DataSet`. If you mean changes down to the database, then that is where adapters come into play.
Here's an example:
```
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
DataSet set = new DataSet();
DataTable table = set.Tables.Add("MyTable");
table.Columns.Add("Foo", typeof(int));
table.Columns.Add("Bar", typeof(string));
Button btn;
using (Form form = new Form
{
Text = "DataGridView binding sample",
Controls =
{
new DataGridView {
Dock = DockStyle.Fill,
DataMember = "MyTable",
DataSource = set
},
(btn = new Button {
Dock = DockStyle.Bottom,
Text = "Total"
})
}
})
{
btn.Click += delegate
{
form.Text = table.AsEnumerable().Sum(
row => row.Field<int>("Foo")).ToString();
};
Application.Run(form);
}
}
}
``` | as mentioned DataAdapters are one of the easy ways.
See:
<http://www.codeproject.com/KB/database/relationaladonet.aspx>
for a pretty simple example that I think covers what youu need. | C# Issue: How do I save changes made in a DataGridView back to the DataTable used? | [
"",
"c#",
"datagrid",
"binding",
"datatable",
"dataset",
""
] |
I have written what I thought to be a pretty solid Linq statement but this is getting 2 to 5 second wait times on execution. Does anybody have thoughts about how to speed this up?
```
t.states = (from s in tmdb.tmZipCodes
where zips.Contains(s.ZipCode) && s.tmLicensing.Required.Equals(true)
group s by new Licensing {
stateCode = s.tmLicensing.StateCode,
stateName = s.tmLicensing.StateName,
FIPSCode = s.tmLicensing.FIPSCode,
required = (bool)s.tmLicensing.Required,
requirements = s.tmLicensing.Requirements,
canWorkWhen = s.tmLicensing.CanWorkWhen,
appProccesingTime = (int) s.tmLicensing.AppProcessingTime
}
into state
select state.Key).ToList();
```
I've changed it to a two stage query which runs almost instantaneously by doing a distinct query to make my grouping work, but it seems to me that it is a little counter intuitive to have that run so much faster than a single query. | Im not sure why it's taking so long, but it might help to have a look at [LINQPad](http://www.linqpad.net/), it will show you the actual query being generated and help optimize.
also, it might not be the actual query that's taking a long time, it might be the query generation. I've found that the longest part is when the linq is being converted to the sql statement.
you could possibly use a compiled query to speed up the sql generation process. a little information can be found on [3devs](http://www.3devs.com/?p=3). I'm not trying to promote my blog entry but i think it fits. | You don't seem to be using the group, just selecting the key at the end. So, does this do the same thing that you want?
```
t.states = (from s in tmdb.tmZipCodes
where zips.Contains(s.ZipCode) && s.tmLicensing.Required.Equals(true)
select new Licensing {
stateCode = s.tmLicensing.StateCode,
stateName = s.tmLicensing.StateName,
FIPSCode = s.tmLicensing.FIPSCode,
required = (bool)s.tmLicensing.Required,
requirements = s.tmLicensing.Requirements,
canWorkWhen = s.tmLicensing.CanWorkWhen,
appProccesingTime = (int) s.tmLicensing.AppProcessingTime
}).Distinct().ToList();
```
Also bear in mind that LINQ does not execute a query until it has to. So if you build your query in two statements, it will not execute that query against the data context (in this case SQL Server) until the call to ToList. When the query does run it will merge the multiple querys into one query and execute that. | Exceptionally slow database response time on Linq query | [
"",
"c#",
"sql-server",
"linq",
""
] |
The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?
Also, there are Write*datatype*() counterparts. | I think [struct.unpack\_from](http://docs.python.org/library/struct.html#struct.unpack_from) is what you're looking for. | Python's way is using struct.unpack to read binary data.
I'm very used to the BinaryReader and BinaryWriter in C#, so I made this:
```
from struct import *
class BinaryStream:
def __init__(self, base_stream):
self.base_stream = base_stream
def readByte(self):
return self.base_stream.read(1)
def readBytes(self, length):
return self.base_stream.read(length)
def readChar(self):
return self.unpack('b')
def readUChar(self):
return self.unpack('B')
def readBool(self):
return self.unpack('?')
def readInt16(self):
return self.unpack('h', 2)
def readUInt16(self):
return self.unpack('H', 2)
def readInt32(self):
return self.unpack('i', 4)
def readUInt32(self):
return self.unpack('I', 4)
def readInt64(self):
return self.unpack('q', 8)
def readUInt64(self):
return self.unpack('Q', 8)
def readFloat(self):
return self.unpack('f', 4)
def readDouble(self):
return self.unpack('d', 8)
def readString(self):
length = self.readUInt16()
return self.unpack(str(length) + 's', length)
def writeBytes(self, value):
self.base_stream.write(value)
def writeChar(self, value):
self.pack('c', value)
def writeUChar(self, value):
self.pack('C', value)
def writeBool(self, value):
self.pack('?', value)
def writeInt16(self, value):
self.pack('h', value)
def writeUInt16(self, value):
self.pack('H', value)
def writeInt32(self, value):
self.pack('i', value)
def writeUInt32(self, value):
self.pack('I', value)
def writeInt64(self, value):
self.pack('q', value)
def writeUInt64(self, value):
self.pack('Q', value)
def writeFloat(self, value):
self.pack('f', value)
def writeDouble(self, value):
self.pack('d', value)
def writeString(self, value):
length = len(value)
self.writeUInt16(length)
self.pack(str(length) + 's', value)
def pack(self, fmt, data):
return self.writeBytes(pack(fmt, data))
def unpack(self, fmt, length = 1):
return unpack(fmt, self.readBytes(length))[0]
```
Once you have a stream, you put it in the BinaryStream constructor and you got a BinaryStream :)
Example:
```
from binary import BinaryStream
f = open("Users", "rb")
stream = BinaryStream(f)
users_count = stream.readUInt64()
for i in range(users_count):
username = stream.readString()
password = stream.readString()
``` | ReadInt(), ReadByte(), ReadString(), etc. in Python? | [
"",
"python",
""
] |
I was looking at the builtin object methods in the [Python documentation](http://docs.python.org/reference/datamodel.html#objects-values-and-types), and I was interested in the documentation for `object.__repr__(self)`. Here's what it says:
> Called by the repr() built-in function
> and by string conversions (reverse
> quotes) to compute the “official”
> string representation of an object. If
> at all possible, this should look like
> a valid Python expression that could
> be used to recreate an object with the
> same value (given an appropriate
> environment). If this is not possible,
> a string of the form <...some useful
> description...> should be returned.
> The return value must be a string
> object. If a class defines **repr**()
> but not **str**(), then **repr**() is
> also used when an “informal” string
> representation of instances of that
> class is required.
>
> This is typically used for debugging,
> so it is important that the
> representation is information-rich and
> unambiguous
The most interesting part to me, was...
> If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value
... but I'm not sure exactly what this means. It says it should *look* like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?
In general I'm a bit confused as to exactly what I should be putting here. | ```
>>> from datetime import date
>>>
>>> repr(date.today()) # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_) # _ is the output of the last command
datetime.date(2009, 1, 16)
```
The output is a string that can be parsed by the python interpreter and results in an equal object.
If that's not possible, it should return a string in the form of `<...some useful description...>`. | It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a `Fraction` class that contains two integers, a numerator and denominator, your `__repr__()` method would look like this:
```
# in the definition of Fraction class
def __repr__(self):
return "Fraction(%d, %d)" % (self.numerator, self.denominator)
```
Assuming that the constructor takes those two values. | Python object.__repr__(self) should be an expression? | [
"",
"python",
""
] |
in a VS 2008 solution I just inherited there is a normal class library project that actually should be a web application project (because it is a web service indeed). What is the best way to convert it? | I also found out that this can be done manually by adding:
```
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
```
to the project file (\*.proj) just under `<ProjectGuid>...</ProjectGuid>` | Create a new Web Service (or Web Application) project and add the class library files to it. | Change project to Web Application in Visual Studio 2008 | [
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have a large result set assembled in a parent/child relationship. I need to walk the tree and display the results to the user.
I've done this before using recursion, but because my result set may be large, I want to avoid the possibility of receiving a StackOverflowException.
I found the following [example](http://msdn.microsoft.com/en-us/library/bb513869.aspx) on MSDN which uses a Stack. The problem I'm having is because a stack is last-in first-out, my data doesn't appear properly. I'd like it to look like the following:
```
LeveL 1
Level 1.1
Level 1.1.1
Level 1.1.2
Level 1.2
Level 1.2.1
Level 1.2.2
```
But it looks like:
```
LeveL 1
Level 1.2
Level 1.2.2
Level 1.2.1
Level 1.1
Level 1.1.2
Level 1.1.1
```
Any ideas?
Here is an example of my code. Assuming the `DataTable dt` has the following columns: ID, ParentID, and Text
```
private struct Item
{
public string Text;
public int ID;
public int ParentID;
}
private void BuildView()
{
Stack<Item> itemTree = new Stack<Item>(40);
//Get All Parent Nodes
DataView dv = new DataView(dt);
dv.RowFilter = "ParentID = 0";
//Add the parent nodes to the stack
foreach (DataRowView drv in dv)
{
Item item = new Item();
item.Text = drv["Text"].ToString();
item.ID = drv["ID"].ToString();
item.ParentID = drv["ParentID"].ToString();
itemTree.Push(item);
}
//Go through the stack one node at a time
while (itemTree.Count > 0)
{
Item currentItem = itemTree.Pop();
Debug.WriteLine(currentItem.Text);
//Get children of current node
dv.RowFilter = String.Format("ParentID = {0}", currentItem.ID);
if (dv.Count > 0)
{
//Add child nodes to the stack
foreach (DataRowView drvChild in dv)
{
Item item = new Item();
item.Text = drvChild["Text"].ToString();
item.ID = drvChild["ID"].ToString();
item.ParentID = drvChild["ParentID"].ToString();
itemTree.Push(item);
}
}
}
}
``` | Push your items onto the stack in the reverse order, i.e. 2 before 1.
Example:
```
// suppose I want to push children[] onto the stack
for (int i = children.Length - 1; i >= 0; i--)
{
stack.Push(children[i]);
}
```
To do this in your code, try the following `for-each` statement:
```
foreach (DataRowView drvChild in dv.Reverse())
``` | In the current algorithm you are going for the right child first.
Make it left child first. Thats all.
For example, in your code there may be something like:
```
node = node.rightChild()
```
Change it to
```
node = node.leftChild()
```
This is the general solution for this kind of issues.
Since the MSDN implementation does not expose this kind of code, I cannot comment on that. | C# Large Tree Iteration | [
"",
"c#",
"algorithm",
"recursion",
"iteration",
"tree-traversal",
""
] |
I'm using a SQL query that is similar to the following form:
```
SELECT col1, col2
FROM table1
LEFT OUTER JOIN table2
ON table1.person_uid = table2.person_uid
AND table1.period = table2.period
```
And it's either way too slow or something's deadlocking because it takes at least 4 minutes to return. If I were to change it to this:
```
SELECT col1, col2
FROM table1
LEFT OUTER JOIN table2
ON table1.person_uid = table2.person_uid
WHERE table1.period = table2.period
```
then it works fine (albeit not returning the right number of columns). Is there any way to speed this up?
**UPDATE**: It does the same thing if I switch the last two lines of the latter query:
```
SELECT col1, col2
FROM table1
LEFT OUTER JOIN table2
ON table1.period = table2.period
WHERE table1.person_uid = table2.person_uid
```
**UPDATE 2:** These are actually views that I'm joining. Unfortunately, they're on a database I don't have control over, so I can't (easily) make any changes to the indexing. I am inclined to agree that this is an indexing issue though. I'll wait a little while before accepting an answer in case there's some magical way to tune this query that I don't know about. Otherwise, I'll accept one of the current answers and try to figure out another way to do what I want to do. Thanks for everybody's help so far. | Bear in mind that statements 2 and 3 are different to the first one.
How? Well, you're doing a left outer join and your WHERE clause isn't taking that into account (like the ON clause does). At a minimum, try:
```
SELECT col1, col2
FROM table1, table2
WHERE table1.person_uid = table2.person_uid (+)
AND table1.period = table2.period (+)
```
and see if you get the same performance issue.
What indexes do you have on these tables? Is this relationship defined by a foreign key constraint?
What you probably need is a composite index on both person\_uid and period (on both tables). | I think you need to understand why the last two are not the same query as the first one. If you do a left join and then add a where clause referncing a field in the table on the right side of the join (the one which may not always have a record to match the first table), then you have effectively changed the join to an inner join. There is one exception to this and that is if you reference something like
```
SELECT col1, col2
FROM table1
LEFT OUTER JOIN table2
ON table1.person_uid = table2.person_uid
WHERE table2.person_uid is null
```
In this case you asking for the record which don't have a record in the second table. But other than this special case, you are changing the left join to an inner join if you refence a field in table2 in the where clause.
If your query is not fast enough, I would look at your indexing. | Left outer join on two columns performance issue | [
"",
"sql",
"oracle",
"join",
"oracle10g",
"left-join",
""
] |
Under Windows there are some handy functions like `QueryPerformanceCounter` from `mmsystem.h` to create a high resolution timer.
Is there something similar for Linux? | It's been [asked before here](https://stackoverflow.com/questions/464618/whats-the-equivalent-of-windows-queryperformancecounter-on-osx) -- but basically, there is a boost ptime function you can use, or a POSIX clock\_gettime() function which can serve basically the same purpose. | For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html).
```
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
```
See: [This answer](https://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds/275231#275231) for more information | High resolution timer with C++ and Linux? | [
"",
"c++",
"linux",
"timer",
""
] |
Is there a way to allocate an uninitialized block of memory, such as an array that contains whatever garbage happened to be left behind, in Java? I want to do so to benchmark how fast Java's memory allocator/garbage collector can allocate/free blocks of memory. | No. You can't separate allocation from initialization, at least not for arrays.
What, exactly, are you trying to benchmark?
The reason that I ask is that there are a lot of variables within a running JVM that will affect any object allocation timing, ranging from the size of the object (which determines where it's allocated), to what else is happening in the JVM at the same time (once you start allocating objects, they'll get shuffled between the various generations), to whether or not Hotspot decides that your code isn't doing anything and can be replaced by a no-op.
Incidentally, there are a similar but non-overlapping set of variables that get in the way of benchmarking malloc() ... | Maybe java.nio.ByteBuffer is what you are looking for. Your reasons are a bit vague though :-) | Java: Allocate uninitialized block of memory? | [
"",
"java",
"memory-management",
""
] |
Is it possible to decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it? | Sure, check [formatters](http://docs.python.org/library/logging.html#formatter-objects) in logging docs. Specifically the lineno and pathname variables.
> **%(pathname)s** Full pathname of the source file where the logging call was issued(if available).
>
> **%(filename)s** Filename portion of pathname.
>
> **%(module)s** Module (name portion of filename).
>
> **%(funcName)s** Name of function containing the logging call.
>
> **%(lineno)d** Source line number where the logging call was issued (if available).
Looks something like this:
```
formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')
``` | On top of [Seb's very useful answer](https://stackoverflow.com/a/533077/6862601), here is a handy code snippet that demonstrates the logger usage with a reasonable format:
```
#!/usr/bin/env python
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
```
Generates this output:
```
2017-06-06:17:07:02,158 DEBUG [log.py:11] This is a debug log
2017-06-06:17:07:02,158 INFO [log.py:12] This is an info log
2017-06-06:17:07:02,158 CRITICAL [log.py:13] This is critical
2017-06-06:17:07:02,158 ERROR [log.py:14] An error occurred
``` | How to log source file name and line number in Python | [
"",
"python",
"logging",
"python-logging",
""
] |
Recently I have discovered that my release executable (made with msvc++ express 2008) becomes very large. As I examine the executable with a hex viewer I saw that only the first 300k bytes contains useful data the remaining bytes are only zeros - 6 megs of zero bytes.
The debug built exe has 1MB size, but the release is 6.5MB.
Why does MSVC++ express do that useless thing? How can I fix it? | Did you define large arrays at file-scope in your program? That might be one reason. You can use the dumpbin program to see how much space each section in the exe file takes, that should give you a clue to the "why". | Perhaps you are statically linking your .exe in release, but dynamically linking in debug? Check this is the dialog Project Properties.
Another possibility is that in release mode a lot of functions are inlined or you are using a lots of templates.
You can tell the compiler to optimize for size in the dialog Project Properties. | Visual C++ express 2008: Why does it places megs of null bytes at the end of the release executable? | [
"",
"c++",
"visual-c++",
"size",
"release-mode",
""
] |
I have this application I'm developing in JSP and I wish to export some data from the database in XLS (MS Excel format).
Is it possible under tomcat to just write a file as if it was a normal Java application, and then generate a link to this file? Or do I need to use a specific API for it?
Will I have permission problems when doing this? | While you can use a full fledged library like [JExcelAPI](http://jexcelapi.sourceforge.net/), Excel will also read CSV and plain HTML tables provided you set the response MIME Type to something like "application/vnd.ms-excel".
Depending on how complex the spreadsheet needs to be, CSV or HTML can do the job for you without a 3rd party library. | Don't use plain HTML tables with an `application/vnd.ms-excel` content type. You're then basically fooling Excel with a wrong content type which would cause failure and/or warnings in the latest Excel versions. It will also messup the original HTML source when you edit and save it in Excel. Just don't do that.
CSV in turn is a standard format which enjoys default support from Excel without any problems and is in fact easy and memory-efficient to generate. Although there are libraries out, you can in fact also easily write one in less than 20 lines (funny for ones who can't resist). You just have to adhere the [RFC 4180](http://www.rfc-editor.org/rfc/rfc4180.txt) spec which basically contains only 3 rules:
1. Fields are separated by a comma.
2. If a comma occurs within a field, then the field has to be surrounded by double quotes.
3. If a double quote occurs within a field, then the field has to be surrounded by double quotes and the double quote within the field has to be escaped by another double quote.
Here's a kickoff example:
```
public static <T> void writeCsv (List<List<T>> csv, char separator, OutputStream output) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
for (List<T> row : csv) {
for (Iterator<T> iter = row.iterator(); iter.hasNext();) {
String field = String.valueOf(iter.next()).replace("\"", "\"\"");
if (field.indexOf(separator) > -1 || field.indexOf('"') > -1) {
field = '"' + field + '"';
}
writer.append(field);
if (iter.hasNext()) {
writer.append(separator);
}
}
writer.newLine();
}
writer.flush();
}
```
Here's an example how you could use it:
```
public static void main(String[] args) throws IOException {
List<List<String>> csv = new ArrayList<List<String>>();
csv.add(Arrays.asList("field1", "field2", "field3"));
csv.add(Arrays.asList("field1,", "field2", "fie\"ld3"));
csv.add(Arrays.asList("\"field1\"", ",field2,", ",\",\",\""));
writeCsv(csv, ',', System.out);
}
```
And inside a Servlet (yes, Servlet, don't use JSP for this!) you can basically do:
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
List<List<Object>> csv = someDAO().findCsvContentFor(filename);
response.setHeader("content-type", "text/csv");
response.setHeader("content-disposition", "attachment;filename=\"" + filename + "\"");
writeCsv(csv, ';', response.getOutputStream());
}
```
Map this servlet on something like `/csv/*` and invoke it as something like `http://example.com/context/csv/filename.csv`. That's all.
Note that I added the possiblity to specify the separator character separately, because it may depend on the locale used whether Excel would accept a comma `,` or semicolon `;` as CSV field separator. Note that I also added the filename to the URL pathinfo, because a certain webbrowser developed by a team in Redmond otherwise wouldn't save the download with the proper filename. | JSP generating Excel spreadsheet (XLS) to download | [
"",
"java",
"excel",
"jsp",
"tomcat",
"export",
""
] |
This is what I have right now:
```
$("#number").val(parseFloat($("#number").val()).toFixed(2));
```
It looks messy to me. I don't think I'm chaining the functions correctly. Do I have to call it for each textbox, or can I create a separate function? | If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
```
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
``` | Maybe something like this, where you could select more than one element if you'd like?
```
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
``` | In jQuery, what's the best way of formatting a number to 2 decimal places? | [
"",
"javascript",
"jquery",
"rounding",
"decimal-point",
"number-formatting",
""
] |
My language is PHP, but the algorithm should be fairly universal.
I have an associative array of (let's say) ratings and number of times that rating has been given.
```
$ratings = array(
1 => 1,
2 => 3,
3 => 6,
4 => 3,
5 => 3
);
```
This is the equivalent of: `[1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5]`, but given the numbers I'm working with, it would be quite inefficient to convert from the first form to the second.
What would be the algorithm to calculate the mean of the above numbers? | Try this:
```
$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
$total += $number * $frequency;
$count += $frequency;
}
return $total / $count;
``` | Wouldn't this work?
```
$total = 0;
$sum = 0;
foreach ($ratings as $k => $v) {
$total += $k * $v;
$sum += $v;
}
echo $total / $sum;
```
EDIT: Well, I look silly, since someone beat me to it. Oh well. | How to calculate a weighted mean? | [
"",
"php",
"algorithm",
"statistics",
""
] |
I'm translating some Delphi code into c# code when I ran into this. I don't have an environment setup for Delphi so I can't test it myself.
Delphi:
```
RandSeed := var1;
Result := Random($FF);
```
c#:
```
Random RandSeed = new Random(var1);
Result = RandSeed.Next(255);
```
Would these put the same value in Result? If not, any ideas on a way to do so? | The Delphi PRNG is a deterministic [linear congruential generator](http://en.wikipedia.org/wiki/Linear_congruential_generator) with 134775813 as **`a`** and 1 as **`c`**, and returning the high 32 bits for range-limited numbers. Here's an implementation in C# that returns the same values as Delphi:
```
using System;
class DelphiRandom
{
int _seed;
public DelphiRandom(int seed)
{
_seed = seed;
}
int GetNext() // note: returns negative numbers too
{
_seed = _seed * 0x08088405 + 1;
return _seed;
}
public int Next(int maxValue)
{
ulong result = (ulong) (uint) GetNext() * (ulong) (uint) maxValue;
return (int) (result >> 32);
}
}
class App
{
static void Main()
{
DelphiRandom r = new DelphiRandom(42);
for (int i = 0; i < 10; ++i)
Console.WriteLine(r.Next(100));
}
}
``` | Certainly not, because they use different RNGs. You could perhaps use a RNG from the Windows API, create your own RNG or use some RNG library to achieve this.
Another way to make sure your RNG creates the same numbers for a given seed would be to write a DLL and use it for both Delphi and C#.
By the way, if you want to code a RNG yourself, [Wikipedia](http://en.wikipedia.org/wiki/List_of_random_number_generators) is a good starting point to get the names of some usual generators. After you're done, you should run it through some [statistical test](http://en.wikipedia.org/wiki/Diehard_tests) to make sure it's "random" enough for you. | Is the Random Generator from Delphi the same calculation as C# if fed the same seed? | [
"",
"c#",
"delphi",
"random",
""
] |
When I saw [this article](http://www.guilabs.net/#Screenshots) about using a python-like sintax (indentation based, without curly braces, syntax) for C#, I begun to wonder: can I have an IDE that parses and compiles it? | What about [Iron Python](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython)? It's python for dotnet.
You can also check out [Delphi Prism](http://www.codegear.com/products/delphi/prism) (runs as a plugin for Visual Studio) if you don't like braces. It can do everything that C# does, plus a few extra things. | > : can I have an IDE that parses and compiles it?
First off, a bit of pedantry. An **IDE** neither parses nor compiles.
I would either suggest to use Iron Python or Delphi Prism (as Wouter suggested faster) or what about this:
You use Notepad++ as an IDE and write a small tool that automatically adds the brackets based on the intention before the code is compiled. I think that this can be done within one code "search and replace traversal":
For example:
```
if true
for each a in b
foo();
foo();
```
The code simply scans each line and adds an opening bracket if: The code in the currentline is further intended than the code in the previous line:
```
if true
{for each a in b
{foo();
foo();
```
And adds a closing bracket wherever the code of the next line is less intended than in the current line. - Store the indentation depth (I would recommend a stackbased system)!
```
if true
{for each a in b
{foo();}
}
foo();
```
And so on... The problems with Namespaces and "Using" can also be solved that way. | Is there any IDE or Visual Studio/Mono/SharpDevelop plugin for braceless C#? | [
"",
"c#",
"visual-studio",
"ide",
"indentation",
"curly-braces",
""
] |
i have a large list of static data from a server that i load on startup. I load this into a hashtable of foo objects. the user has a dropdown where they can choose one of these object. by default there are 50,000 objects which take up a lot of memory. i am trying to reduce memory
after monitoring usage, it turns out that most people only use about 1,000 of them. i want to have it so the gui only loads up those 1000 and if they need to select one that is outside that 1000 then they can go back to the server or to disk.
what would be the best way of doing this . . | I'm assuming you're filtering this list elsewhere...otherwise that's quite a list. The easiest way to hit your new, leaner static cache before hitting the DB will be to pass all requests through a single method:
```
public yourClass GetDesiredObject(string lkupValue)
{
if (yourCachedHashtable.ContainsKey(lkupValue))
{
return yourCachedHashtable[lkupValue]
}
else
{
//Hit the db to retrieve the object values.
yourClass obj = yourDatabaseCode.GetNewObject(lkupValue);
//Add to the cache if desired.
yourCachedHashtable.Add(lkupValue, obj);
return obj;
}
}
``` | The problem with loading a 1000 first is
1. Who would scroll a 1000?
2. The going back to the disk will cause the dropdown to reset and they'll have to scroll again.
Solution
1. Why not implement a auto search dropdown, and try caching app block, it works great for me with extensive amounts of data.
2. Look at devexpress dropdown edit, you'll need to purchase their controls though. | Caching strategy | [
"",
"c#",
"winforms",
"memory",
""
] |
What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web? | [Django](http://www.djangoproject.com/) is, IMHO, one of the major benefits of using Python. Model your domain, code your classes, and voila, your ORM is done, and you can focus on the UI. Add in the ease of templating with the built-in templating language (or one of many others you can use as well), and it becomes *very* easy to whip up effective web applications in no time. Throw in the built-in admin interface, and it's a no-brainer. | Certainly one successful use of Python on the web is [Google App Engine](http://code.google.com/appengine/). Site authors write code in (a slightly restricted subset of) Python, which is then executed by the App Engine servers in a distributed and scalable manner. | What are the benefits of using Python for web programming? | [
"",
"python",
"programming-languages",
""
] |
### Background
* I have an application with a *Poof-Crash*[*1*]. I'm fairly certain it is due to a blown stack.
* The application is Multi-Threaded.
* I am compiling with "`Enable C++ Exceptions: Yes With SEH Exceptions (/EHa)`".
* I have written an SE Translator function and called `_set_se_translator()` with it.
* I have written functions for and setup `set_terminate()` and `set_unexpected()`.
* To get the Stack Overflow, I must run in release mode, under heavy load, for several days. Running under a debugger is not an option as the application can't perform fast enough to achieve the runtime necessary to see the issue.
* I can simulate the issue by adding infinite recursion on execution of one of the functions, and thus test the catching of the `EXCEPTION_STACK_OVERFLOW` exception.
* I have WinDBG setup as the crash dump program, and get good information for all other crash issues but **not this one**. The crash dump will only contain one thread, which is 'Sleep()'ing. All other threads have exited.
### The Question
None of the things I've tried has resulted in picking up the `EXCEPTION_STACK_OVERFLOW` exception.
Does anyone know how to guarantee getting a a chance at this exception during runtime in release mode?
### Definitions
1. *Poof-Crash*: The application crashes by going "poof" and disappearing without a trace.
*(Considering the name of this site, I'm kind of surprised this question isn't on here already!)*
### Notes
1. An answer was posted briefly about adjusting the stack size to potentially force the issue sooner and allow catching it with a debugger. That is a clever thought, but unfortunately, I don't believe it would help. The issue is likely caused by a corner case leading to infinite recursion. Shortening the stack would not expose the issue any sooner and would likely cause an unrelated crash in validly deep code. Nice idea though, and thanks for posting it, even if you did remove it. | Everything prior to windows xp would not (or would be harder) generally be able to trap stack overflows. With the advent of xp, you can set [vectored exception handler](http://msdn.microsoft.com/en-us/library/ms679274(VS.85).aspx) that gets a chance at stack overflow prior to any stack-based (structured exception) handlers (this is being the very reason - structured exception handlers are stack-based).
But there's really not much you can do even if you're able to trap such an exception.
In [his blog](http://blogs.msdn.com/cbrumme/), cbrumme (sorry, do not have his/her real name) discusses a stack page neighboring the guard page (the one, that generates the stack overflow) that can potentially be used for backout. If you can squeeze your backout code to use just one stack page - you can free as much as your logic allows. Otherwise, the application is pretty much dead upon encountering stack overflow. The only other reasonable thing to do, having trapped it, is to write a dump file for later debugging.
Hope, it helps. | I'm not convinced that you're on the right track in diagnosing this as a stack overflow.
But in any case, the fact that you're getting a *poof!*, plus what you're seeing in WinDbg
> The crash dump will only contain one thread, which is 'Sleep()'ing. All other threads have exited.
suggests to me that somebody has called the C RTL exit() function, or possibly called the Windows API TerminateProcess() directly. That could have something to do with your interrupt handlers or not. Maybe something in the exception handling logic has a re-entrance check and arbitrarily decides to exit() if it's reentered.
My suggestion is to patch your executables to put maybe an INT 3 debug at the entry point to exit (), if it's statically linked, or if it's dynamically linked, patch up the import and also patch up any imports of kernel32::TerminateProcess to throw a DebugBreak() instead.
Of course, exit() and/or TerminateProcess() may be called on a normal shutdown, too, so you'll have to filter out the false alarms, but if you can get the call stack for the case where it's just about to go proof, you should have what you need.
EDIT ADD: Just simply writing your own version of exit() and linking it in instead of the CRTL version might do the trick. | How can I guarantee catching a EXCEPTION_STACK_OVERFLOW structured exception in C++ under Visual Studio 2005? | [
"",
"c++",
"debugging",
"exception",
"stack-overflow",
"structured-exception",
""
] |
I've got quite a bit of PHP code laying around and am wondering at what point should I start upgrading the scripts to support IPV6.
I know IPV6 has been on the 'list of things to do' for a long, long time but really have never seen a clear transition path on when I need to start supporting it. | IPv6 has widespread adoption in some countries (e.g. Japan, China, Korea) and some large organisations (an IPv6 workshop I did 6 years ago suggested IPv6 support was required for all networking gear sold to the US govt for example).
I think the short answer to your question is... "When a significant proportion of your target audience uses IPv6".
For a public internet site, the answer to that is likely "probably never". IPv6 was meant to solve the "we're running out of IPv4 addresses" problem. Since instead of IPv6, most organisations have gone down the [network address translation](http://en.wikipedia.org/wiki/Network_address_translation) route, greatly extending the life of the IPv4 address space. | I think the short answer to your question is... "***Before*** a significant proportion of your target audience uses IPv6".
If you're developing a commercial app, "Before your competition supports IPv6". | At what point should I support IPV6 in my php scripts? | [
"",
"php",
"upgrade",
"ipv6",
"transition",
""
] |
It is possible to add and remove elements from an enum in Java at runtime?
For example, could I read in the labels and constructor arguments of an enum from a file?
---
@saua, it's just a question of whether it can be done out of interest really. I was hoping there'd be some neat way of altering the running bytecode, maybe using [BCEL](http://bcel.sourceforge.net/) or something. I've also followed up with [this question](https://stackoverflow.com/questions/481068/when-to-use-enum-or-collection-in-java) because I realised I wasn't totally sure when an enum should be used.
I'm pretty convinced that the right answer would be to use a collection that ensured uniqueness instead of an enum if I want to be able to alter the contents safely at runtime. | No, enums are supposed to be a complete static enumeration.
At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.
In some cases you might want a set of standard values but allow extension. The usual way to do this is have an `interface` for the interface and an `enum` that implements that `interface` for the standard values. Of course, you lose the ability to `switch` when you only have a reference to the `interface`. | Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see [here](http://snipplr.com/view/1655/typesafe-enum-pattern/) for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the `enum` keyword as a shorthand. See the source for [Enum<T>](http://www.docjar.com/html/api/java/lang/Enum.java.html) to learn more.
So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.
Also, do yourself a favor and override `equals`, `hashCode` and `toString`, and if possible create a `values` method
The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create `enum MathConstants` and then go ahead and use `MathConstants.PI` wherever you want... | Can I add and remove elements of enumeration at runtime in Java | [
"",
"java",
"enums",
""
] |
Why should I use `<?php` instead of `<?` in my php script? | The two main reasons to avoid the short opening tag are
1. Maximum portability - `<?php` will work on every PHP enabled server, but `<?` can be disabled
2. It's identical to the opening of the XML preamble - could cause parsing or execution headaches | There are two methods to start PHP
```
<?php
```
and
```
<?
```
PHP also includes
```
<?=
```
But that will print out the variable behind it, since its a shorthand for echo.
You should use < ?php since its compatible with all server types. You can move your code to a new hosting solution or setup a new server default and the shorthands could be disabled. | <?php instead of <? | [
"",
"php",
"syntax",
""
] |
I'm trying to encapsulate some functions from the C socket library into my own C++ class. I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature. For example, I'd like to write the function
```
ssize_t MyClass::write(const void *buf);
```
which makes a call to
```
ssize_t write(int fd, const void *buf, size_t count);
```
When I compile I get the following errors
```
error: no matching function for call to ‘MyClass::write(int&, const char*&, size_t)’
note: candidates are: ssize_t MyClass::write(const char*)
```
I have the correct `#include` statements to make the call to the C socket library, but my definition of a write function seems to be shadowing it. If I change the name of my class defined function to something else, everything seems to work fine.
I'm reasonably sure that changing my function name is going to be my final solution, but could someone tell me the name of the C++ naming rule that causes this behavior? I'd like to read up on it so I know what I'm doing in the future. | Have you tried calling the C function expliciting that it lives in the global namespace, like ::write? | [This page](http://msdn.microsoft.com/en-us/library/2902y0f8(VS.80).aspx) does a pretty good job of describing the name lookup rules in C++. Basically, once the compiler sees that `write()` is a class member function, it doesn't look for global functions of the same name. It then reports an error since the member function `write()` doesn't have the right number and types of arguments as what you gave it. The use of the unary scope resolution operator `::` forces the compiler to only search the global namespace for functions named `write()`, which then succeeds. | C++ class member function naming rules | [
"",
"c++",
"naming",
""
] |
Coming from a background in Django, I often use "template inheritance", where multiple templates inherit from a common base. Is there an easy way to do this in JSP? If not, is there an alternative to JSP that does this (besides Django on Jython that is :)
## base template
```
<html>
<body>
{% block content %}
{% endblock %}
</body>
<html>
```
## basic content
```
{% extends "base template" %}
{% block content %}
<h1>{{ content.title }} <-- Fills in a variable</h1>
{{ content.body }} <-- Fills in another variable
{% endblock %}
```
Will render as follows (assuming that conten.title is "Insert Title Here", and content.body is "Insert Body Here")
```
<html>
<body>
<h1>Insert title Here <-- Fills in a variable</h1>
Insert Body Here <-- Fills in another variable
</body>
<html>
``` | You'll probably want to look into [Tiles](http://tiles.apache.org/index.html).
EDIT: On a related note to tiles, you might want to look into [Struts](http://struts.apache.org/). It's not what you're looking for (that's tiles), but it is useful for someone coming from Django. | You can do similar things using JSP tag files. Create your own `page.tag` that contains the page structure. Then use a `<jsp:body/>` tag to insert the contents. | JSP template inheritance | [
"",
"java",
"django",
"jsp",
"templates",
""
] |
I have a dictionary that I am using to define the ratings of copper cable. I want to use these values to calculate how many cables it will take to meet a certain connections rating. The size of the connection, the cable type, and system type are selected by two ComboBoxs named cb\_amperage, cb\_cable\_size and, cb\_system\_type. The answer found once the equation runs is to be displayed in a text box named tb6\_cable\_qty. I welcome any and all comments and suggestions. Thank you in advance for the assistance.
The math is easy:
```
decimal x, y, z;
x = decimal.Parse(cb_amperage.);
y = decimal.Parse();//<---- this value must come from the dictionary below
a = decimal.Parse();//<---- this value must also come from a dictionary below
z = (x / y) * a
tb6_cable_qty.Text = Math.Round(z,2).ToString();
void Cb_amperageSelectedIndexChanged(object sender, EventArgs e)
{
if (!String.!IsNullOrEmpty(cb_amperage) & !String.IsNullOrEmpty(cb_cable_size))
//not sure if the above is right but I think it coveys the idea
{
//function based on the values in the dictionary below
}
//Cable Dictionary 1 used for cable quantity calculation
Dictionary<string, int> cable_dictionary_1 = new Dictionary<string, int>();
cable_dictionary_1.Add ("#1", 130);
cable_dictionary_1.Add ("1/0", 150);
cable_dictionary_1.Add ("2/0", 175);
cable_dictionary_1.Add ("3/0", 200);
cable_dictionary_1.Add ("4/0", 230);
cable_dictionary_1.Add ("250", 255);
cable_dictionary_1.Add ("300", 285);
cable_dictionary_1.Add ("400", 355);
cable_dictionary_1.Add ("500", 380);
cable_dictionary_1.Add ("600", 720);
cable_dictionary_1.Add ("750", 475);
//System Type Dictionary used for cable quantity calculation
Dictionary<string, int> system_type_dictionary = new Dictionary<string, int>();
system_type_dictionary.Add ("3P 3W", 3);
system_type_dictionary.Add ("3P 4W", 4);
```
EDIT 1:
mmr; please take a look at the code below. I have a feeling I missed something that I would know if I was a little more expierenced. The following is my implementation of the first part of the solution you suggested. I get an error. I think it is because these two items, the string and the dictionary dont know they are supposed to be linked. Here is the error; \*Invalid token ',' in class, struct, or interface member declaration (CS1519). See what you can see. Thanks again.
```
//The following strings are used in the cable quantity calculation
private const string cblsize1 = "#1";
private const string cblsize2 = "1/0";
private const string cblsize3 = "2/0";
private const string cblsize4 = "3/0";
//Cable Dictionary 1 used for cable quantity calculation
Dictionary<string, int> cable_dictionary_1 = new Dictionary<string, int>();
cable_dictionary.Add(cblsize1, 130);//#1 Cable
cable_dictionary.Add(cblsize2, 150);//1/0 Cable
cable_dictionary.Add(cblsize3, 175);//2/0 Cable
cable_dictionary.Add(cblsize4, 200);//3/0 Cable
``` | Solved!!!!
Below is the code. Thanks to Rudedog2 of the MSDN C# Forum!
```
partial class MainForm
{
double x, y, z;
List<string> cable_size1;
List<string> system_type_list;
List<string> amperage;
Dictionary<string, double> cable_dictionary_1;
Dictionary<string, double> system_type;
Dictionary<string, double> amperage_dictionary;
private void MainFormLoad(object sender, EventArgs e)
{
//Each of the following lists populate the ComboBoxes
//to be selected on the main form.
amperage = new List<string>();
cable_size1 = new List<string>();
system_type_list = new List<string>();
cable_dictionary_1 = new Dictionary<string, double>();
system_type = new Dictionary<string, double>();
amperage_dictionary = new Dictionary<string, double>();
//
InitializeCurrentLoadCB();
InitializeCableSizeCB();
InitializeSystemTypeCB();
//---------------Dictionaries---------------------------------------------------------
InitializeSystemTypeLookup();
InitializeCableLookup();
InitializeAmperageLookup();
}
private void InitializeCurrentLoadCB()
{
//Amperage List, No Exclusions-----------------------------------------------------------
amperage = new List<string>();
amperage.Add("Please Select Amperage");
amperage.Add("400");
amperage.Add("800");
amperage.Add("1000");
amperage.Add("1200");
amperage.Add("1600");
amperage.Add("2000");
amperage.Add("2500");
amperage.Add("3000");
amperage.Add("3200");
amperage.Add("4000");
amperage.Add("5000");
amperage.Add("6000");
cb_test_1.DataSource = amperage;
cb_test_1.SelectedIndex = 0;
cb_test_1.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void InitializeCableSizeCB()
{
//Cable List, No Exclusions --------------------------------------------------------------
cable_size1 = new List<string>();
cable_size1.Add("Please Select Cable Size");
cable_size1.Add ("#1");
cable_size1.Add ("1/0");
cable_size1.Add ("2/0");
cable_size1.Add ("3/0");
cable_size1.Add ("4/0");
cable_size1.Add ("250");
cable_size1.Add ("300");
cable_size1.Add ("400");
cable_size1.Add ("500");
cable_size1.Add ("600");
cable_size1.Add ("700");
cable_size1.Add ("750");
cb_test_2.DataSource = cable_size1;
cb_test_2.SelectedIndex = 0;
cb_test_2.DropDownStyle = ComboBoxStyle.DropDownList;
//Initial DataBind for cable size ComboBox
}
private void InitializeSystemTypeCB()
{
//System Type List
system_type_list = new List<string>();
system_type_list.Add("Select System Type");
system_type_list.Add("3 Phase 3 Wire");
system_type_list.Add("3 Phase 4 Wire");
cb_test_3.DataSource = system_type_list;
cb_test_3.SelectedIndex = 0;
cb_test_3.DropDownStyle = ComboBoxStyle.DropDownList;
//Initial DataBind for cb_system type ComboBox
}
private void Button1Click(object sender, System.EventArgs e)
{
if (!String.IsNullOrEmpty(cb_test_1.Text) &&
(!String.IsNullOrEmpty(cb_test_2.Text) &&
(!String.IsNullOrEmpty(cb_test_3.Text))))
{
double a;
if (cb_test_1.SelectedIndex != 0)
{
x = amperage_dictionary[amperage[cb_test_1.SelectedIndex]];
}
if (cb_test_2.SelectedIndex != 0)
{
y = cable_dictionary_1[cable_size1[cb_test_2.SelectedIndex]];
}
if (cb_test_3.SelectedIndex != 0)
{
z = system_type[system_type_list[cb_test_3.SelectedIndex]];
}
a = ((x / y)*z);
this.tb_1.Text = Math.Round(a,2).ToString();
}
}
private void InitializeSystemTypeLookup()
{
//System Type Dictionary
this.system_type = new Dictionary<string, double>();
this.system_type.Add(this.system_type_list[0], 0);
this.system_type.Add(this.system_type_list[1], 3);
this.system_type.Add(this.system_type_list[2], 4);
}
private void InitializeCableLookup()
{
//Cable Dictionary 1 used for cable quantity calculation
this.cable_dictionary_1 = new Dictionary<string, double>();
this.cable_dictionary_1.Add (this.cable_size1[0], 0);
this.cable_dictionary_1.Add (this.cable_size1[1], 130);
this.cable_dictionary_1.Add (this.cable_size1[2], 150);
this.cable_dictionary_1.Add (this.cable_size1[3], 175);
this.cable_dictionary_1.Add (this.cable_size1[4], 200);
this.cable_dictionary_1.Add (this.cable_size1[5], 230);
this.cable_dictionary_1.Add (this.cable_size1[6], 255);
this.cable_dictionary_1.Add (this.cable_size1[7], 285);
this.cable_dictionary_1.Add (this.cable_size1[8], 355);
this.cable_dictionary_1.Add (this.cable_size1[9], 380);
this.cable_dictionary_1.Add (this.cable_size1[10], 720);
this.cable_dictionary_1.Add (this.cable_size1[11], 475);
}
private void InitializeAmperageLookup()
{
//Amperage Dictionary
this.amperage_dictionary = new Dictionary<string, double>();
this.amperage_dictionary.Add(this.amperage[0], 0);
this.amperage_dictionary.Add(this.amperage[1], 400);
this.amperage_dictionary.Add(this.amperage[2], 800);
this.amperage_dictionary.Add(this.amperage[3], 1000);
this.amperage_dictionary.Add(this.amperage[4], 1200);
this.amperage_dictionary.Add(this.amperage[5], 1600);
this.amperage_dictionary.Add(this.amperage[6], 2000);
this.amperage_dictionary.Add(this.amperage[7], 2500);
this.amperage_dictionary.Add(this.amperage[8], 3000);
this.amperage_dictionary.Add(this.amperage[9], 3200);
this.amperage_dictionary.Add(this.amperage[10], 4000);
this.amperage_dictionary.Add(this.amperage[11], 5000);
this.amperage_dictionary.Add(this.amperage[12], 6000);
}
}
``` | I'm not sure what your question is? It sounds like you got it all covered. | C# Dictionary Application: Applying Values through the selection of keys | [
"",
"c#",
"dictionary",
"combobox",
""
] |
I have been learning C++ with some books from school that are from the 80's and I'm not really sure if they are strings in C++ or just really long arrays of type char. Can anyone help? | There is a [string](http://en.cppreference.com/w/cpp/string/basic_string) class in C++. | Check out the standard library.
In the STL, you can find the std::string class, as well as a bunch of other useful classes.
The basic documentation can be found here:
<http://www.sgi.com/tech/stl/>
The string documentation can be found here:
<http://www.sgi.com/tech/stl/basic_string.html>
The beauty of these stl strings is that they delete themselves; so once you declare them, you can just let them go, and they will handle their own memory. That's true of other stl classes as well (Of course, if you declare a vector of pointers, the vector will get deleted, but the memory the pointers point to has to be handled as well; it's not a total panacea, but it works nicely if you keep that limitation in mind).
Finally, I've found that this book is a really good way to learn how to think in STL:
[Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) | There are Strings in C++? | [
"",
"c++",
"string",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.