Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :).
JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.
Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.
Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have `"onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'"` in the `<tr>` tags, and tables start off with "class='closed'".
Single clicks collapse and expand tables in FF & Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!
Here's the JS code:
```
bURL_RM_RID="some image prefix";
CLOSED_TBL="closed";
OPEN_TBL="open";
CLOSED_IMG= bURL_RM_RID+'166';
OPENED_IMG= bURL_RM_RID+'167';
//collapses/expands tbl (a table) and swaps out the image tblimg
function toggleDisplay(tbl, tblimg) {
var rowVisible;
var tblclass = tbl.getAttribute("class");
var tblRows = tbl.rows;
var img = tblimg;
//Are we expanding or collapsing the table?
if (tblclass == CLOSED_TBL) rowVisible = false;
else rowVisible = true;
for (i = 0; i < tblRows.length; i++) {
if (tblRows[i].className != "headerRow") {
tblRows[i].style.display = (rowVisible) ? "none" : "";
}
}
//set the collapse images to the correct state and swap the class name
rowVisible = !rowVisible;
if (rowVisible) {
img.setAttribute("src", CLOSED_IMG);
tbl.setAttribute("class",OPEN_TBL);
}
else {
img.setAttribute("src", OPENED_IMG);
tbl.setAttribute("class",CLOSED_TBL);
}
}
```
|
setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE.
This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML property directly:
```
img.src= CLOSED_IMAGE;
tbl.className= OPEN_TBL;
```
You can also do the table folding in the stylesheet, which will be faster and will save you the bother of having to loop over the table rows in script:
```
table.closed tr { display: none; }
```
|
Have you tried changing this line
```
tblRows[i].style.display = (rowVisible) ? "none" : "";
```
to something like
```
tblRows[i].style.display = (rowVisible) ? "none" : "table-row";
```
or
```
tblRows[i].style.display = (rowVisible) ? "none" : "auto";
```
|
IE Javascript Clicking Issue
|
[
"",
"javascript",
"internet-explorer",
"click",
""
] |
OK, so practically every database based application has to deal with "non-active" records. Either, soft-deletions or marking something as "to be ignored". I'm curious as to whether there are any radical alternatives thoughts on an `active' column (or a status column).
For example, if I had a list of people
```
CREATE TABLE people (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
active BOOLEAN,
...
);
```
That means to get a list of active people, you need to use
```
SELECT * FROM people WHERE active=True;
```
Does anyone suggest that non active records would be moved off to a separate table and where appropiate a UNION is done to join the two?
Curiosity striking...
**EDIT:** I should make clear, I'm coming at this from a purist perspective. I can see how data archiving might be necessary for large amounts of data, but that is not where I'm coming from. If you do a SELECT \* FROM people it would make sense to me that those entries are in a sense "active"
Thanks
|
You partition the table on the active flag, so that active records are in one partition, and inactive records are in the other partition. Then you create an active view for each table which automatically has the active filter on it. The database query engine automatically restricts the query to the partition that has the active records in it, which is much faster than even using an index on that flag.
Here is an example of how to create a partitioned table in Oracle. Oracle doesn't have boolean column types, so I've modified your table structure for Oracle purposes.
```
CREATE TABLE people
(
id NUMBER(10),
name VARCHAR2(100),
active NUMBER(1)
)
PARTITION BY LIST(active)
(
PARTITION active_records VALUES (0)
PARTITION inactive_records VALUES (1)
);
```
If you wanted to you could put each partition in different tablespaces. You can also partition your indexes as well.
Incidentally, this seems a repeat of [this](https://stackoverflow.com/questions/68323/what-is-the-best-way-to-implement-soft-deletion) question, as a newbie I need to ask, what's the procedure on dealing with unintended duplicates?
**Edit:** As requested in comments, provided an example for creating a partitioned table in Oracle
|
Well, to ensure that you only draw active records in most situations, you could create views that only contain the active records. That way it's much easier to not leave out the active part.
|
`active' flag or not?
|
[
"",
"sql",
"mysql",
"postgresql",
""
] |
Is there a way to determine how many capture groups there are in a given regular expression?
I would like to be able to do the follwing:
```
def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
```
This allows me to do stuff like:
```
first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
```
However, I don't know how to implement `num_of_groups`. (Currently I just work around it.)
**EDIT:** Following the [advice from rslite](https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089), I replaced `re.findall` with `re.search`.
`sre_parse` seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.
MizardX's regular expression seems to cover all bases, so I'm going to go with that.
|
```
def num_groups(regex):
return re.compile(regex).groups
```
|
```
f_x = re.search(...)
len_groups = len(f_x.groups())
```
|
Find out number of capture groups in Python regular expressions
|
[
"",
"python",
"regex",
""
] |
I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last *word* before 200 chars.
|
By using the [wordwrap](http://www.php.net/wordwrap) function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
One thing this one-liner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
```
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}
```
---
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here's a version which solves this problem:
```
function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}
return implode(array_slice($parts, 0, $last_part));
}
```
Also, here is the PHPUnit test class used to test the implementation:
```
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}
public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}
public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}
public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}
public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}
```
Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the regex to handle it:
`$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);`
|
This will return the first 200 characters of words:
```
preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
```
|
How to Truncate a string in PHP to the word closest to a certain number of characters?
|
[
"",
"php",
"string",
"function",
""
] |
I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this', 'is', 'a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
|
You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
```
|
Have a look at the `shlex` module, particularly `shlex.split`.
```
>>> import shlex
>>> shlex.split('This is "a test"')
['This', 'is', 'a test']
```
|
Split a string by spaces -- preserving quoted substrings -- in Python
|
[
"",
"python",
"regex",
""
] |
I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:
```
<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
CommandName="Details" Text="Order Details"
onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
'','scrollbars=yes,resizable=yes, width=350, height=550');"
```
Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.
Any suggestions? Or is there a far better way of achieving the same result?
|
I believe the way to do it is
> ```
> onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
> ```
|
I like @[AviewAnew](https://stackoverflow.com/questions/102343/including-eval-bind-values-in-onclientclick-code#102373)'s suggestion, though you can also just write that from the code-behind by wiring up and event to the grid views ItemDataBound event. You'd then use the FindControl method on the event args you get to grab a reference to your button, and set the *onclick* attribute to your window.open statement.
|
Including eval / bind values in OnClientClick code
|
[
"",
"asp.net",
"javascript",
"visual-studio",
""
] |
Given an array of **n** Objects, let's say it is an **array of strings**, and it has the following values:
```
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
```
What do I have to do to delete/remove all the strings/objects equal to **"a"** in the array?
|
[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]
To flesh out [Dustman's idea](https://stackoverflow.com/a/112507/13):
```
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
```
Edit: I'm now using `Arrays.asList` instead of `Collections.singleton`: singleton is limited to one entry, whereas the `asList` approach allows you to add other strings to filter out later: `Arrays.asList("a", "b", "c")`.
Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a *new* array sized exactly as required, use this instead:
```
array = list.toArray(new String[0]);
```
---
Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:
```
private static final String[] EMPTY_STRING_ARRAY = new String[0];
```
Then the function becomes:
```
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);
```
This will then stop littering your heap with useless empty string arrays that would otherwise be `new`ed each time your function is called.
cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:
```
array = list.toArray(new String[list.size()]);
```
I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling `size()` on the wrong list).
|
An alternative in Java 8:
```
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);
```
|
How do I remove objects from an array in Java?
|
[
"",
"java",
"arrays",
"data-structures",
"data-manipulation",
""
] |
Do you still use session or entity EJBs in your project? Why?
|
EJB3 is a **vast** improvement over previous versions. It's still *technically* the standard server-side implementation toolset for JavaEE and since it now has none of the previous baggage (thanks to annotations and Java Persistence), is quite usable and being deployed as we speak. As one commenter noted, JBoss SEAM is based upon it.
EJB 3 is a viable alternative to Spring, and the two technologies may become more tightly related. [this](http://java.dzone.com/articles/end-spring-vs-ejb-wars-sight) article details that Spring 3.0 will be compatible with EJB Lite (which I'm not sure what that is, exactly) and possibly be part of Java EE 6.
EJB is not going anywhere.
|
We're working with EJB here and it works quite well with JBoss Seam and JSF, Faclets and MyFaces Trinidad. Good UI, Templating, AJAX and stable production 24/7 running on JBoss 4.2.
It's a good stack for business processes, workflows, messageing, webservices and ui control. Fast delivery of features, easy programming and stable ground based on entitybeans with mysql persistance.
I don't want to miss the featureset of EJB 3 for the tasks our product demands.
|
Is EJB still alive?
|
[
"",
"java",
"jakarta-ee",
"ejb",
""
] |
I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop.
The installation footprint for Oracle Client tools was over 200Mb, and quite long winded.
Does anyone know what the minimum workable footprint is? I am hoping that it's a single DLL and a register command, but I have the feeling I need to install an oracle home, and set various environment variables.
I am using Oracle.DataAccess in my code.
|
You need an Oracle Client to connect to an Oracle database. The easiest way is to install the [Oracle Data Access Components](http://www.oracle.com/technology/software/tech/windows/odpnet/index.html).
To minimize the footprint, I suggest the following :
* Use the Microsoft provider for Oracle (System.Data.OracleClient), which ships with the framework.
* Download the [Oracle Instant Client Package](http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html) - Basic Lite : this is a zip file with (almost) the bare minimum. I recommend version 10.2.0.4, which is much smaller than version 11.1.0.6.0.
* Unzip the following files in a specific folder :
+ v10 :
- oci.dll
- orannzsbb10.dll
- oraociicus10.dll
+ v11 :
- oci.dll
- orannzsbb11.dll
- oraociei11.dll
* On a x86 platform, add the CRT DLL for Visual Studio 2003 (msvcr71.dll) to this folder, as Oracle guys forgot to [read this](http://support.microsoft.com/kb/326922)...
* Add this folder to the PATH environment variable.
* Use the [Easy Connect Naming](http://download.oracle.com/docs/cd/B19306_01/network.102/b14212/naming.htm#ABC524382SRI12) method in your application to get rid of the infamous TNSNAMES.ORA configuration file. It looks like this : `sales-server:1521/sales.us.acme.com`.
This amounts to about **19Mb** (v10).
If you do not care about sharing this folder between several applications, an alternative would be to ship the above mentioned DLLs along with your application binaries, and skip the PATH setting step.
If you absolutely need to use the Oracle provider (Oracle.DataAccess), you will need :
* ODP .NET 11.1.0.6.20 (the first version which allegedly works with Instant Client).
* Instant Client 11.1.0.6.0, obviously.
Note that I haven't tested this latest configuration...
|
I use the method suggested by Pandicus above, on Windows XP, using ODAC 11.2.0.2.1. The steps are as follows:
1. Download the "ODAC 11.2 Release 3 (11.2.0.2.1) with Xcopy Deployment" package from oracle.com (53 MB), and extract the ZIP.
2. Collect the following DLLs: oci.dll (1 MB), oraociei11.dll (130 MB!), OraOps11w.dll (0.4 MB), Oracle.DataAccess.dll (1 MB). The remaining stuff can be deleted, and nothing have to be installed.
3. Add a reference to Oracle.DataAccess.dll, add `using Oracle.DataAccess.Client;` to your code and now you can use types like `OracleConnection`, `OracleCommand` and `OracleDataReader` to access an Oracle database. See the [class documentation](http://download.oracle.com/docs/cd/B19306_01/win.102/b14307/intro003.htm#BHCJFIAJ) for details. There is no need to use the tnsnames.ora configuration file, only the [connection string](http://www.connectionstrings.com/oracle) must be set properly.
4. The above 4 DLLs have to be deployed along with your executable.
|
What is the minimum client footprint required to connect C# to an Oracle database?
|
[
"",
"c#",
"oracle",
"client",
""
] |
First of all, this question regards MySQL 3.23.58, so be advised.
I have 2 tables with the following definition:
```
Table A: id INT (primary), customer_id INT, offlineid INT
Table B: id INT (primary), name VARCHAR(255)
```
Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the *offlineid* field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query.
I was first presented with the following query (*query time: ~22 seconds*):
```
SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads
FROM katalogbestilling_katalog a, medie b
WHERE a.offlineid = b.id
GROUP BY b.name
```
Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (*query time: ~6 seconds*):
```
SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads
FROM medie a
INNER JOIN katalogbestilling_katalog b ON a.id = b.offline
GROUP BY b.offline;
```
Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome!
|
You could try making sure there are covering indexes defined on each table. A covering index is just an index where each column requested in the select or used in a join is included in the index. This way, the engine only has to read the index entry and doesn't have to also do the corresponding row lookup to get any requested columns not included in the index. I've used this technique with great success in Oracle and MS SqlServer.
Looking at your query, you could try:
one index for medie.id, medie.name
one index for katalogbestilling\_katalog.offlineid, katalogbestilling\_katalog.kundeid
The columns should be defined in these orders for the index. That makes a difference whether the index can be used or not.
More info here:
[Covering Index Info](http://peter-zaitsev.livejournal.com/6949.html)
|
I'm going to guess that your main problem is that you are using such an old version of MySQL. Maybe MySQL 3 doesn't like the COUNT(DISTINCT()).
Alternately, it might just be system performance. How much memory do you have?
Still, MySQL 3 is really old. I would at least put together a test system to see if a newer version ran that query faster.
|
Optimize SQL query on large-ish table
|
[
"",
"mysql",
"sql",
"optimization",
""
] |
C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really messy.
Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?
|
> Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?
Yes; don't.
The C++ spec permits a compiler to be able to "see" the entire template (declaration *and* definition) at the point of instantiation, and (due to the complexities of any implementation) most compilers retain this requirement. The upshot is that #inclusion of any template header must also #include any and all source required to instantiate the template.
The easiest way to deal with this is to dump everything into the header, inline where posible, out-of-line where necessary.
If you really regard this as an unacceptable affront, a common option is to split the template into the usual header/implementation pair, and then #include the implementation file at the end of the header.
C++'s "export" feature may or may not provide another workaround. The feature is poorly supported and poorly defined; although it in principle should permit some kind of separate compilation of templates, it doesn't necessarily obviate the demand that the compiler be able to see the entire template body.
|
Across how many files? If you just want to separate class definitions from implementation then try [this article](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl) in the C++ faqs. That's about the only way I know of that works at the moment, but some IDEs (Eclipse CDT for example) won't link this method properly and you may get a lot of errors. However, writing your own makefiles or using Visual C++ has always worked for me :-)
|
Templates spread across multiple files
|
[
"",
"c++",
"templates",
""
] |
For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.
I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).
Any help?
**EDIT:** I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.
|
<http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()>
```
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++)
System.out.println("Root["+i+"]:" + roots[i]);
```
google: list drives java, first hit:-)
|
Looking "everywhere" can be very messy.
Look at a CD-rom drive, and it spins up. That can be very noisy.
Look at a network drive, and it may be very slow. Maybe the server is down, and you may need to wait for minutes until it times out.
Maybe (for Windows-machines) you should just look in the start-menu. If nothing there points at OOo, it's probably not installed. If it is, the user is probably an advanced user, that will have no problems pointing out the location manually.
|
Find all drive letters in Java
|
[
"",
"java",
"windows",
""
] |
I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.
Two Questions:
1. I can't seem to get the input loop to work out, what's the best practice for doing so.
2. What is the object-type going to be for the reading method? A double[], or an ArrayList?
1. How do I declare method-type to be an arraylist?
2. How do I prevent the array from having more than 1000 values stored within it?
Let me show what I have so far:
```
public static java.util.ArrayList readRange(double end_signal){
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
System.out.println(input); //debugging
++count;
} while(input(--count) != end_signal);
return input;
}
```
Any help would be appreciated, pardon my newbieness...
|
Answers:
*>1. I can't seem to get the input loop to work out, what's the best practice for doing so.*
I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read:
*while the read number is not end signal and count is lower than limit: do.*
*>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?*
An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation.
*>2.1How do I declare method-type to be an arraylist?*
See code below.
*>2.2. How do I prevent the array from having more than 1000 values stored within it?*
By adding this restriction in the while condition.
```
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class InputTest{
private int INPUT_LIMIT = 10000;
public static void main( String [] args ) {
InputTest test = new InputTest();
System.out.println("Start typing numbers...");
List list = test.readRange( 2.0 );
System.out.println("The input was " + list );
}
/**
* Read from the standar input until endSignal number is typed.
* Also limits the amount of entered numbers to 10000;
* @return a list with the numbers.
*/
public List readRange( double endSignal ) {
List<Double> input = new ArrayList<Double>();
Scanner kdb = new Scanner( System.in );
int count = 0;
double number = 0;
while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){
System.out.println( number );
input.add( number );
}
return input;
}
}
```
Final remarks:
It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class
In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal"
|
What you need in your loop condition is:
```
while ( input.get( input.size()-1 ) != end_signal );
```
What you're doing is decrementing the counter variable.
Also you should declare the `ArrayList` like so:
```
ArrayList<Double> list = new ArrayList<Double>();
```
This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.
|
ArrayList in Java and inputting
|
[
"",
"java",
"arrays",
"arraylist",
""
] |
I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?
|
How about something like this:
```
def itersorted(d):
for key in sorted(d):
yield d[key]
```
|
By far the easiest approach, and almost certainly the fastest, is something along the lines of:
```
def sorted_dict(d):
keys = d.keys()
keys.sort()
for key in keys:
yield d[key]
```
You can't sort without fetching all keys. Fetching all keys into a list and then sorting that list is the most efficient way to do that; list sorting is very fast, and fetching the keys list like that is as fast as it can be. You can then either create a new list of values or yield the values as the example does. Keep in mind that you can't modify the dict if you are iterating over it (the next iteration would fail) so if you want to modify the dict before you're done with the result of sorted\_dict(), make it return a list.
|
Sorting a dict on __iter__
|
[
"",
"python",
"optimization",
"refactoring",
""
] |
The background should be transparent, but the text should not.
|
Enso is open source too.
You can directly peek at they source code.
<http://code.google.com/p/enso/>
Let us know how they do it when you find out!.
**UPDATE**
It looks like they use something called Cairo. If you can link it from C# you're done.
|
By making an "Enso style" application you mean the Enso launcher?
Here is a screenshot of it:
[alt text http://enscreenshots.softonic.com/s2en/68000/68880/3\_ensolauncher03.jpg](http://enscreenshots.softonic.com/s2en/68000/68880/3_ensolauncher03.jpg)
I would suggest at looking at the open-source C# [Cropper](http://www.codeplex.com/cropper) application. He does a similar looking GUI with transparent background. You can open up his project and see how he implements it.
[alt text http://img352.imageshack.us/img352/726/cropperuijt3.png](http://img352.imageshack.us/img352/726/cropperuijt3.png)
|
How can I make a Enso style application in C#
|
[
"",
"c#",
"winforms",
"windows-xp",
""
] |
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:
```
SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
```
Any help would be gratefully received.
|
Have a look at [this article](http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql). Basically, if you want to get the equivalent of IN, you need to construct an inner query first, and then use the Contains() method. Here's my attempt at translating:
```
var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;
var result = from f in Foo where innerQuery.Contains(f.FooId) select f;
```
|
# General way to implement IN in LINQ to SQL
```
var q = from t1 in table1
let t2s = from t2 in table2
where <Conditions for table2>
select t2.KeyField
where t2s.Contains(t1.KeyField)
select t1;
```
# General way to implement EXISTS in LINQ to SQL
```
var q = from t1 in table1
let t2s = from t2 in table2
where <Conditions for table2>
select t2.KeyField
where t2s.Any(t1.KeyField)
select t1;
```
|
How can you handle an IN sub-query with LINQ to SQL?
|
[
"",
"sql",
"linq",
"linq-to-sql",
""
] |
i have a list of products that are being displayed in particular order. store admin can reassign the display order, by moving the "hot" items to the top of the list. what's the best way of implementing the admin functionality **UI** [asp.net C#]? Products table has a [displayOrder(int)] filed which determines the display order.
i'm looking for something intuitive and simple.
thank you.
p.s. i guess i didn't make myself clear, i'm looking for UI advice more than anything.
SOLUTION: ReorderList worked out great, this [article](http://weblogs.asp.net/justinsaraceno/archive/2008/02/22/reorderlist-with-objectdatasource.aspx) helped too. Also, make sure OldValuesParameterFormatString="{0}" in your DataSource.
|
using AJAX you could implement a Reoder list control you can find more information here <http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ReorderList/ReorderList.aspx>
Mauro
[http://www.brantas.co.uk](http://www.brantas.co.uk/)
|
You need a Rank field for each product (which could also be the DisplayOrder field).
When the administrator ups or downs a product, update the rank value.
When you need to list the products, do a select query which sorts in DESC order of rank.
|
Implementing user defined display order UI
|
[
"",
"c#",
"asp.net",
"visual-studio-2005",
""
] |
I am looking for a .NET implementation of a priority queue or heap data structure
> Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.
>
> The basic priority queue supports three primary operations:
>
> * Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.
> * Find-Minimum(Q). Return a pointer to the item
> whose key value is smaller than any other key in the priority queue
> Q.
> * Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum
Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?
|
I like using the `OrderedBag` and `OrderedSet` classes in [PowerCollections](http://www.codeplex.com/PowerCollections) as priority queues.
|
You might like IntervalHeap from the [C5 Generic Collection Library](http://www.itu.dk/research/c5/). To quote the [user guide](https://www.itu.dk/research/c5/latest/ITU-TR-2006-76.pdf)
> Class `IntervalHeap<T>` implements interface `IPriorityQueue<T>` using an interval heap stored as an array of pairs. The `FindMin` and
> `FindMax` operations, and the indexer’s get-accessor, take time O(1). The `DeleteMin`,
> `DeleteMax`, Add and Update operations, and the indexer’s set-accessor, take time
> O(log n). In contrast to an ordinary priority queue, an interval heap offers both minimum
> and maximum operations with the same efficiency.
The API is simple enough
```
> var heap = new C5.IntervalHeap<int>();
> heap.Add(10);
> heap.Add(5);
> heap.FindMin();
5
```
Install from Nuget <https://www.nuget.org/packages/C5> or GitHub <https://github.com/sestoft/C5/>
|
Priority queue in .Net
|
[
"",
"c#",
".net",
"data-structures",
"heap",
"priority-queue",
""
] |
I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?
For example:
1. I have a user setting named `CellBackgroundColor` in `Properties.Settings`.
2. At design time I set the value of `CellBackgroundColor` to `Color.White` using the IDE.
3. User sets `CellBackgroundColor` to `Color.Black` in my program.
4. I save the settings with `Properties.Settings.Default.Save()`.
5. User clicks on the `Restore Default Colors` button.
Now, `Properties.Settings.Default.CellBackgroundColor` returns `Color.Black`. How do I go back to `Color.White`?
|
@ozgur,
```
Settings.Default.Properties["property"].DefaultValue // initial value from config file
```
Example:
```
string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
```
|
Reading "Windows 2.0 Forms Programming", I stumbled upon these 2 useful methods that may be of help in this context:
[ApplicationSettingsBase.Reload](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.reload.aspx)
[ApplicationSettingsBase.Reset](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.reset.aspx)
From MSDN:
> Reload contrasts with Reset in that
> the former will load the last set of
> saved application settings values,
> whereas the latter will load the saved
> default values.
So the usage would be:
```
Properties.Settings.Default.Reset()
Properties.Settings.Default.Reload()
```
|
Reading default application settings in C#
|
[
"",
"c#",
".net",
"winforms",
"application-settings",
""
] |
I'm a PHP developer and now I use [Notepad++](http://en.wikipedia.org/wiki/Notepad_%28software%29) for code editing, but lately I've been searching for an IDE to ease my work.
I've looked into [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29), [Aptana Studio](http://en.wikipedia.org/wiki/Aptana#Aptana_Studio) and several others, but I'm not really decided, they all look nice enough but a bit complicated. I'm sure it'll all get easy once I get used to it, but I don't want to waste my time.
This is what I'm looking for:
* FTP support
* Code highlight
* SVN support would be great
* Ruby and JavaScript would be great
|
Are you sure you're looking for an IDE? The features you're describing, along with the impression of being too complicated that you got from e.g. Aptana, suggest that perhaps all you really want is a good editor with syntax highlighting and integration with some common workflow tools. For this, there are tons of options.
I've used [jEdit](http://www.jedit.org/) on several platforms successfully, and that alone puts it above most of the rest (many of the IDEs are cross-platform too, but Aptana and anything Eclipse-based is going to be pretty heavy-weight, if full-featured). jEdit has ready-made plugins for everything on your list, and syntax highlighting for a wide range of languages. You can also bring up a shell in the bottom of your window, invoke scripts from within the editor, and so forth. It's not perfect (the UI is better than most Java UIs, but not perfect yet I don't think), but I've had good luck with it, and it'll be a hell of a lot simpler than Aptana/Eclipse.
That said, I do like Aptana quite a bit for web development, it does a lot of the grunt work for you once you're over the learning curve.
|
For PHP I would recommend [PhpStorm](http://www.jetbrains.com/phpstorm/).
It supports FTP/SFTP synchronization, integrates well with [Subversion](http://en.wikipedia.org/wiki/Apache_Subversion), [CVS](http://en.wikipedia.org/wiki/Concurrent_Versions_System), [Mercurial](http://en.wikipedia.org/wiki/Mercurial) and even with [Git](http://en.wikipedia.org/wiki/Git_%28software%29). Also, it supports HTML, CSS, JavaScript and handles language-mixing well like SQL or HTML blocks inside PHP code, JSON, etc.
But if you need Ruby you can try another IDE - [RubyMine](http://en.wikipedia.org/wiki/RubyMine) with same capabilities but for Ruby.
|
What is the best IDE for PHP?
|
[
"",
"php",
"ide",
""
] |
I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:
```
/// <summary>
/// Method to calculate distance between two points
/// </summary>
///
/// <param name="pointA">First point</param>
/// <param name="pointB">Second point</param>
///
function calculatePointDistance(pointA, pointB) { ... }
```
Recently I've been looking into other third-party JavaScript libraries and I see syntax like:
```
/*
* some comment here
* another comment here
* ...
*/
function blahblah() { ... }
```
As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style?
|
There's [JSDoc](https://jsdoc.app/)
```
/**
* Shape is an abstract base class. It is defined simply
* to have something to inherit from for geometric
* subclasses
* @constructor
*/
function Shape(color){
this.color = color;
}
```
|
The simpler the better, comments are good, use them :)
```
var something = 10; // My comment
/*
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.
*/
function bigThing() {
// ...
}
```
But for autogenerated doc...
```
/**
* Adds two numbers.
* @param {number} num1 The first number to add.
* @param {number} num2 The second number to add.
* @return {number} The result of adding num1 and num2.
*/
function bigThing() {
// ...
}
```
|
What is the preferred method of commenting JavaScript objects and methods?
|
[
"",
"javascript",
"comments",
""
] |
What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new `Array` with the same strings but in a random order.
Please include a C# example in your answer.
|
First, you should use the most upvoted answer to this question so far, which is <https://stackoverflow.com/a/110570/1757994>.
You can shuffle using LINQ.
`var myShuffledArray = myArray.Shuffle()`.
Add the following code as a file called `EnumerableExtensions.cs` to your project:
```
public static class EnumerableExtensions
{
public static IList<T> Shuffle<T>(this IEnumerable<T> sequence)
{
return sequence.Shuffle(new Random());
}
public static IList<T> Shuffle<T>(this IEnumerable<T> sequence, Random randomNumberGenerator)
{
if (sequence == null)
{
throw new ArgumentNullException("sequence");
}
if (randomNumberGenerator == null)
{
throw new ArgumentNullException("randomNumberGenerator");
}
T swapTemp;
List<T> values = sequence.ToList();
int currentlySelecting = values.Count;
while (currentlySelecting > 1)
{
int selectedElement = randomNumberGenerator.Next(currentlySelecting);
--currentlySelecting;
if (currentlySelecting != selectedElement)
{
swapTemp = values[currentlySelecting];
values[currentlySelecting] = values[selectedElement];
values[selectedElement] = swapTemp;
}
}
return values;
}
}
```
Adapted from <https://github.com/microsoft/driver-utilities/blob/master/src/Sarif.Driver/EnumerableExtensions.cs>
It is a bad idea to use informally authored shuffle algorithms, since they are hard to analyze for flaws.
If you're using C# 7.0 or higher, this other approach is slow for many elements but works correctly in all environments C# is used:
```
var rnd = new Random();
var myRandomArray = myArray
.Select(x => (x, rnd.Next()))
.OrderBy(tuple => tuple.Item2)
.Select(tuple => tuple.Item1)
.ToArray();
```
This is almost as verbose as the Fisher-Yates shuffle, which is much faster for large numbers of elements. This creates random numbers for each element, then sorts by the random number.
This answer used to say something along the lines of `.OrderBy(x => random())`.
Experienced developers will correctly know that `.OrderBy(x => random())` alone is wrong. So if you commit code that contains it, you will look bad.
Why is it wrong? OrderBy expects the keySelector, the function that it is passed, to be pure. That means the keySelector should return the same answer every time it is called and cause no side effects.
C# implementations like Unity's do not cache the result of the selector passed to OrderBy. Games tend to shuffle things. It is hard to generalize across all CLR implementations, so it's better to just use the correct thing. In order to not look bad with code you author, you should use Fisher-Yates instead.
For Visual Basic and versions of C# earlier than 7.0, use Fisher-Yates. A correct implementation using only LINQ is more verbose than implementing Fisher-Yates, so you will have written more code to do a worse implementation.
|
The following implementation uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the 'sort by random' technique, although it is more lines of code. See [here](https://web.archive.org/web/20210510014810/http://aspnet.4guysfromrolla.com/articles/070208-1.aspx) for some comparative performance measurements. I have used System.Random, which is fine for non-cryptographic purposes.\*
```
static class RandomExtensions
{
public static void Shuffle<T> (this Random rng, T[] array)
{
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
```
Usage:
```
var array = new int[] {1, 2, 3, 4};
var rng = new Random();
rng.Shuffle(array);
rng.Shuffle(array); // different order from first call to Shuffle
```
\* For longer arrays, in order to make the (extremely large) number of permutations equally probable it would be necessary to run a pseudo-random number generator (PRNG) through many iterations for each swap to produce enough entropy. For a 500-element array only a very small fraction of the possible 500! permutations will be possible to obtain using a PRNG. Nevertheless, the Fisher-Yates algorithm is unbiased and therefore the shuffle will be as good as the RNG you use.
|
Best way to randomize an array with .NET
|
[
"",
"c#",
".net",
"algorithm",
"sorting",
"random",
""
] |
I would like to wipe out all data for a specific kind in Google App Engine. What is the
best way to do this?
I wrote a delete script (hack), but since there is so much data is
timeout's out after a few hundred records.
|
The [official answer](http://groups.google.com/group/google-appengine/browse_thread/thread/ec0800a3ca92fe69#) from Google is that you have to delete in chunks spread over multiple requests. You can use AJAX, [meta refresh](http://en.wikipedia.org/wiki/Meta_refresh), or request your URL from a script until there are no entities left.
|
I am currently deleting the entities by their key, and it seems to be faster.
```
from google.appengine.ext import db
class bulkdelete(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
try:
while True:
q = db.GqlQuery("SELECT __key__ FROM MyModel")
assert q.count()
db.delete(q.fetch(200))
time.sleep(0.5)
except Exception, e:
self.response.out.write(repr(e)+'\n')
pass
```
from the terminal, I run curl -N http://...
|
Delete all data for a kind in Google App Engine
|
[
"",
"python",
"google-app-engine",
""
] |
Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
|
First download the [JavaMail API](https://java.net/projects/javamail/pages/Home) and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
```
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "lizard.bill@myschool.edu";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
```
Naturally, you'll want to do more in the `catch` blocks than print the stack trace as I did in the example code above. (Remove the `catch` blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
---
Thanks to [@jodonnel](https://stackoverflow.com/users/4223/jodonnell) and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
|
Something like this (sounds like you just need to change your SMTP server):
```
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
```
|
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
|
[
"",
"java",
"email",
"gmail",
"jakarta-mail",
"mail-server",
""
] |
I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.
For example 5 would be converted to "101" and stored as a varchar.
|
Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.
```
declare @intvalue int
set @intvalue=5
declare @vsresult varchar(64)
declare @inti int
select @inti = 64, @vsresult = ''
while @inti>0
begin
select @vsresult=convert(char(1), @intvalue % 2)+@vsresult
select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1
end
select @vsresult
```
|
Actually this is REALLY SIMPLE using plain old SQL. Just use bitwise ANDs. I was a bit amazed that there wasn't a simple solution posted online (that didn't invovled UDFs). In my case I really wanted to check if bits were on or off (the data is coming from dotnet eNums).
Accordingly here is an example that will give you seperately and together - bit values and binary string (the big union is just a hacky way of producing numbers that will work accross DBs:
```
select t.Number
, cast(t.Number & 64 as bit) as bit7
, cast(t.Number & 32 as bit) as bit6
, cast(t.Number & 16 as bit) as bit5
, cast(t.Number & 8 as bit) as bit4
, cast(t.Number & 4 as bit) as bit3
, cast(t.Number & 2 as bit) as bit2
,cast(t.Number & 1 as bit) as bit1
, cast(cast(t.Number & 64 as bit) as CHAR(1))
+cast( cast(t.Number & 32 as bit) as CHAR(1))
+cast( cast(t.Number & 16 as bit) as CHAR(1))
+cast( cast(t.Number & 8 as bit) as CHAR(1))
+cast( cast(t.Number & 4 as bit) as CHAR(1))
+cast( cast(t.Number & 2 as bit) as CHAR(1))
+cast(cast(t.Number & 1 as bit) as CHAR(1)) as binary_string
--to explicitly answer the question, on MSSQL without using REGEXP (which would make it simple)
,SUBSTRING(cast(cast(t.Number & 64 as bit) as CHAR(1))
+cast( cast(t.Number & 32 as bit) as CHAR(1))
+cast( cast(t.Number & 16 as bit) as CHAR(1))
+cast( cast(t.Number & 8 as bit) as CHAR(1))
+cast( cast(t.Number & 4 as bit) as CHAR(1))
+cast( cast(t.Number & 2 as bit) as CHAR(1))
+cast(cast(t.Number & 1 as bit) as CHAR(1))
,
PATINDEX('%1%', cast(cast(t.Number & 64 as bit) as CHAR(1))
+cast( cast(t.Number & 32 as bit) as CHAR(1))
+cast( cast(t.Number & 16 as bit) as CHAR(1))
+cast( cast(t.Number & 8 as bit) as CHAR(1))
+cast( cast(t.Number & 4 as bit) as CHAR(1))
+cast( cast(t.Number & 2 as bit) as CHAR(1))
+cast(cast(t.Number & 1 as bit) as CHAR(1) )
)
,99)
from (select 1 as Number union all select 2 union all select 3 union all select 4 union all select 5 union all select 6
union all select 7 union all select 8 union all select 9 union all select 10) as t
```
Produces this result:
```
num bit7 bit6 bit5 bit4 bit3 bit2 bit1 binary_string binary_string_trimmed
1 0 0 0 0 0 0 1 0000001 1
2 0 0 0 0 0 1 0 0000010 10
3 0 0 0 0 0 1 1 0000011 11
4 0 0 0 1 0 0 0 0000100 100
5 0 0 0 0 1 0 1 0000101 101
6 0 0 0 0 1 1 0 0000110 110
7 0 0 0 0 1 1 1 0000111 111
8 0 0 0 1 0 0 0 0001000 1000
9 0 0 0 1 0 0 1 0001001 1001
10 0 0 0 1 0 1 0 0001010 1010
```
|
SQL Server Convert integer to binary string
|
[
"",
"sql",
"sql-server",
""
] |
I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.
I.e., the same script is included on `/`, `/help`, `/whatever`, and so on, while it will always need to request from `/data.json`. Additionally, the same site is run on different servers, where the `/`-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.
Are there small scripts that will work on all browsers made for this?
|
For this I like to put `<link>` elements in the page's `<head>`, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:
```
<link id="link-action-1" href="${reverse_url ('action_1')}"/>
```
becomes
```
<link id="link-action-1" href="/my/web/root/action-1/"/>
```
and can be retrieved by Javascript with:
```
document.getElementById ('link-action-1').href;
```
|
`document.location.href` will give you the current URL, which you can then manipulate using JavaScript's string functions.
|
Relative urls for Javascript files
|
[
"",
"javascript",
"html",
"url",
""
] |
Given a source color of any hue by the system or user, I'd like a simple algorithm I can use to work out a lighter or darker variants of the selected color. Similar to effects used on Windows Live Messenger for styling the user interface.
Language is C# with .net 3.5.
**Responding to comment:** Color format is (Alpha)RGB. With values as bytes or floats.
**Marking answer:** For the context of my use (a few simple UI effects), the answer I'm marking as accepted is actually the most simple for this context. However, I've given up votes to the more complex and accurate answers too. Anyone doing more advanced color operations and finding this thread in future should definitely check those out. Thanks SO. :)
|
Simply multiply the RGB values by the amount you want to modify the level by. If one of the colors is already at the max value, then you can't make it any brighter (using HSV math anyway.)
This gives the exact same result with a lot less math as switching to HSV and then modifying V. This gives the same result as switching to HSL and then modifying L, as long as you don't want to start losing saturation.
|
In [XNA there is the `Color.Lerp` static method](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.color.lerp.aspx) that does this as the difference between two colours.
`Lerp` is a mathematical operation between two floats that changes the value of the first by a ratio of the difference between them.
Here's an extension method to do it to a `float`:
```
public static float Lerp( this float start, float end, float amount)
{
float difference = end - start;
float adjusted = difference * amount;
return start + adjusted;
}
```
So then a simple lerp operation between two colours using RGB would be:
```
public static Color Lerp(this Color colour, Color to, float amount)
{
// start colours as lerp-able floats
float sr = colour.R, sg = colour.G, sb = colour.B;
// end colours as lerp-able floats
float er = to.R, eg = to.G, eb = to.B;
// lerp the colours to get the difference
byte r = (byte) sr.Lerp(er, amount),
g = (byte) sg.Lerp(eg, amount),
b = (byte) sb.Lerp(eb, amount);
// return the new colour
return Color.FromArgb(r, g, b);
}
```
An example of applying this would be something like:
```
// make red 50% lighter:
Color.Red.Lerp( Color.White, 0.5f );
// make red 75% darker:
Color.Red.Lerp( Color.Black, 0.75f );
// make white 10% bluer:
Color.White.Lerp( Color.Blue, 0.1f );
```
|
How do I determine darker or lighter color variant of a given color?
|
[
"",
"c#",
"colors",
""
] |
Basically, growl notifications (or other callbacks) when tests break or pass. **Does anything like this exist?**
If not, it should be pretty easy to write.. Easiest way would be to..
1. run `python-autotest myfile1.py myfile2.py etc.py`
* Check if files-to-be-monitored have been modified (possibly just if they've been saved).
* Run any tests in those files.
* If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass.
* Wait, and repeat steps 2-5.
The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc..
The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement?
To summarise:
* Is there anything like the Ruby tool `autotest` (part of the [ZenTest package](http://www.zenspider.com/ZSS/Products/ZenTest/)), but for Python code?
* How do you check which functions have changed between two revisions of a script?
* Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback)
|
I found [autonose](https://github.com/gfxmonk/autonose) to be pretty unreliable but [sniffer](http://pypi.python.org/pypi/sniffer/0.2.3) seems to work very well.
```
$ pip install sniffer
$ cd myproject
```
Then instead of running "nosetests", you run:
```
$ sniffer
```
Or instead of `nosetests --verbose --with-doctest`, you run:
```
$ sniffer -x--verbose -x--with-doctest
```
As described in the [readme](http://pypi.python.org/pypi/sniffer/0.2.3), it's a good idea to install one of the platform-specific filesystem-watching libraries, `pyinotify`, `pywin32` or `MacFSEvents` (all installable via `pip` etc)
|
[autonose](http://github.com/gfxmonk/autonose/tree/master) created by [gfxmonk](http://gfxmonk.net/):
> Autonose is an autotest-like tool for python, using the excellent nosetest library.
>
> autotest tracks filesystem changes and automatically re-run any changed tests or dependencies whenever a file is added, removed or updated. A file counts as changed if it has iself been modified, or if any file it `import`s has changed.
>
> ...
>
> Autonose currently has a native GUI for OSX and GTK. If neither of those are available to you, you can instead run the console version (with the --console option).
|
Is there something like 'autotest' for Python unittests?
|
[
"",
"python",
"testing",
""
] |
I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.
I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?
|
Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:
```
class Base {
public Base() {
InitializeComponent();
}
protected virtual void InitializeComponent() {
...
}
}
class Derived : Base {
private Button button1;
public Derived() : base() {
button1 = new Button();
}
protected override void InitializeComponent() {
button1.Text = "I'm gonna throw a null reference exception"
}
}
```
The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.
|
* If you have users that override your virtual methods you can't seal them again without breaking code.
* Any virtual methods you call from the constructor may fall down to derived implementations and if they don't call the base method and the constructor depends on it, the object may be in an invalid state
|
What are the dangers of making a method virtual?
|
[
"",
"c#",
"unit-testing",
"mocking",
"virtual-functions",
""
] |
I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a `SQL server 2000` query.
```
SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1
```
The `RECORD_CREATED_DATE` isn't a field in the existing table. Is there some sort of SQL Function to get this information ?
|
If it's not stored as a field, the info is *lost* after the transaction log recycles (typically daily), and maybe even sooner.
|
No, unfortunately date of insert or last update are not automatically stored with each record.
To do that, you need to create two **datetime** columns in your table (e.g. **CreatedOn**, **UpdatedOn**) and then in an **INSERT** trigger set the **CreatedOn = getdate()** and in the **UPDATE** trigger set the **UpdatedOn = getdate()**.
```
CREATE TRIGGER tgr_tblMain_Insert
ON dbo.tblMain
AFTER INSERT
AS
BEGIN
set nocount on
update dbo.tblMain
set CreatedOn = getdate(),
CreatedBy = session_user
where tblMain.ID = INSERTED.ID
END
```
I also like to create **CreatedBy** and **UpdatedBy varchar(20)** columns which I set to **session\_user** or update through other methods.
|
SQL Server 2000 Function for record created datetime
|
[
"",
"sql",
"sql-server",
""
] |
I have the following enum:
```
public enum Status implements StringEnum{
ONLINE("on"),OFFLINE("off");
private String status = null;
private Status(String status) {
this.status = status;
}
public String toString() {
return this.status;
}
public static Status find(String value) {
for(Status status : Status.values()) {
if(status.toString().equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Unknown value: " + value );
}
}
```
Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?
Thanks.
|
It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: [No static methods in interfaces](http://zoom.z3950.org/bind/java/comment/static.html)
|
Enums already have a [valueOf()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)) (your find method) method. And "toString()" is a java.lang.Object method, so, every class will have that, in other words, you can't force it! I can't see the value of enforcing a constructor since different enums could have different initializations.
Kind Regards
|
How to build interface for such enum
|
[
"",
"java",
"interface",
"enums",
""
] |
Are there any libraries (3rd party or built-in) in `PHP` to calculate text diffs?
|
What sort of diffs? File diffs? There is [array\_diff()](http://php.net/array_diff) which acts on arrays. Then there is also [xdiff](http://php.net/manual/en/book.xdiff.php), which "enables you to create and apply patch files containing differences between different revisions of files.". The latter acts on files or strings.
Edit: I should add xdiff doesn't appear to be out in a release yet. You have to build from source to use it.
|
it depends exactly what you mean and what you want to do but there is
[PEAR Text\_Diff](http://pear.php.net/package/Text_Diff) - Engine for performing and rendering text diffs
|
Calculate text diffs in PHP
|
[
"",
"php",
"diff",
""
] |
Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc.
However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right.
I click on Windows|Preferences and type in "wrap" and get:
```
- Java | Code Style | Formatter
- Java | Editor | Typing
- Web and XML | CSS Files | Source
```
I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect.
How can I get word wrap to work in Eclipse PDT for PHP files?
|
This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in [Eclipse Word-Wrap](http://ahtik.com/blog/projects/eclipse-word-wrap/)
To install it, add the following update site in Eclipse:
[AhtiK Eclipse WordWrap 0.0.5 Update Site](http://ahtik.com/eclipse-update/)
|
[Eclipse Word-Wrap Plug-In](http://dev.cdhq.de/eclipse/word-wrap/) by Florian Weßling works well in Eclispe PDT (3.0.2).
**Installation and update sites**
*It is recommended to restart Eclipse with* `-clean` *option immediately after installation.*
Eclipse Indigo 3.7: <http://dev.cdhq.de/eclipse/updatesite/indigo/>
Eclipse Juno 4.2: <http://dev.cdhq.de/eclipse/updatesite/juno/>
Eclipse Kepler 4.3: <http://dev.cdhq.de/eclipse/updatesite/kepler/>
Eclipse Luna 4.4: <http://dev.cdhq.de/eclipse/updatesite/luna/>
Eclipse Mars 4.5: <http://dev.cdhq.de/eclipse/updatesite/mars/>
Eclipse Neon 4.6: Plugin not necessary.\* Just press `Alt`-`Shift`-`Y` :)
\* See [KrisWebDev's answer](https://stackoverflow.com/a/37103016/1134080) for more details and how to make word wrap permanent.
**Usage**
After the installation of the plugin:
* Context menu: *Right click* > *Toggle Word Wrap*
* Menu bar: *Edit* > *Toggle Word Wrap*
* Keyboard shortcut: `Ctrl`-`Alt`-`E`
* Also you may: *Edit* > *Activate Word Wrap in all open Editors*
There is no dedicated indicator for the current status of the word wrap setting, but you can check the horizontal scroll bar in the Editor.
* Horizontal scroll bar is visible: Word wrap is disabled.
* Horizontal scroll bar is absent: Word wrap is enabled.
|
How can I get word wrap to work in Eclipse PDT for PHP files?
|
[
"",
"php",
"eclipse",
"eclipse-pdt",
"word-wrap",
""
] |
I'm working for a customer with a huge legacy codebase consisting of various Java en JSP based applications.
Most querying is done using the home-build 'orm' system. Some applications use Plain Old JDBC. Some applications are based on Hibernate (yes HQL build with plus signs is a potential problem as well). Some of the older applications are entirely writen in JSP.
I've found a couple of SQL inject bugs manually. But I could really use some sort of tool to search for potential weak spots.
Any ideas?
|
I would recommend [FindBugs](http://findbugs.sourceforge.net) (there is also an eclipse plugin) which can track down these issues and many more.
We are using it at work, it's fast and it's worth the money (as in free). We've solved some common problems with its help.
|
I'd write some searches or load up an IDE that looked for use of java.sql.Statement as opposed to PreparedStatement.
|
Find potential SQL inject problems in Java/JSP code
|
[
"",
"java",
"jsp",
"security",
"sql-injection",
""
] |
I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic.
I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it.
Thanks,
Matt
|
Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that...
You can do something like:
```
CREATE TEMPORARY TABLE myTopCustomers
SELECT customers.*,count(*) num from customers join purchases using(customerID)
join items using(itemID) GROUP BY customers.ID HAVING num > 10;
```
And then do a bunch of queries against myTopCustomers without having to do the joins to purchases and items on each query. Then when your application no longer needs the database handle, no cleanup needs to be done.
Almost always you'll see temporary tables used for derived tables that were expensive to create.
|
First a disclaimer - my job is reporting so I wind up with far more complex queries than any normal developer would. If you're writing a simple CRUD (Create Read Update Delete) application (this would be most web applications) then you really don't want to write complex queries, and you are probably doing something wrong if you need to create temporary tables.
That said, I use temporary tables in Postgres for a number of purposes, and most will translate to MySQL. I use them to break up complex queries into a series of individually understandable pieces. I use them for consistency - by generating a complex report through a series of queries, and I can then offload some of those queries into modules I use in multiple places, I can make sure that different reports are consistent with each other. (And make sure that if I need to fix something, I only need to fix it once.) And, rarely, I deliberately use them to force a specific query plan. (Don't try this unless you really understand what you are doing!)
So I think temp tables are great. But that said, it is *very* important for you to understand that databases generally come in two flavors. The first is optimized for pumping out lots of small transactions, and the other is optimized for pumping out a smaller number of complex reports. The two types need to be tuned differently, and a complex report run on a transactional database runs the risk of blocking transactions (and therefore making web pages not return quickly). Therefore you generally don't want to avoid using one database for both purposes.
My guess is that you're writing a web application that needs a transactional database. In that case, you shouldn't use temp tables. And if you do need complex reports generated from your transactional data, a recommended best practice is to take regular (eg daily) backups, restore them on another machine, then run reports against that machine.
|
How can my application benefit from temporary tables?
|
[
"",
"sql",
"mysql",
""
] |
I have a constructor like as follows:
```
public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
```
I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?
|
~~You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.~~
~~In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts of the derived class are not constructed yet. I would have expected some kind of compiler error if setTopWorldAgent() was abstract.~~
In Java, you can get surprising behavior with the contructor and derived classes -- here is an example
<http://en.wikipedia.org/wiki/Virtual_functions#Java_3>
If you are used to C# or C++, you might think it's safe to call virtual functions and not be calling overridden ones. In Java, the virtual call is made even though the derived class is not fully constructed.
If this isn't what's happening, then presumably, all of the parts of this that setTopWorldAgent() needs are initialized -- if not, it's probably one of the members of this that needs to be initialized.
Edit: thought this was C#
|
Out of curiousity, why are you passing 'this' to a member function of the same class? setTopWorldAgent() can use 'this' directly. It doesn't look like your constructor or setTopWorldAgent() are static, so I'm not sure why you would pass a member function something it already has access to.
Unless I'm missing something...
|
Using 'this' as a parameter to a method call in a constructor
|
[
"",
"java",
"constructor",
"methods",
"call",
"this",
""
] |
How do I get my C# program to sleep (pause execution) for 50 milliseconds?
|
```
System.Threading.Thread.Sleep(50);
```
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the `;` to make it work for VB.net as well.
|
There are basically 3 choices for waiting in (almost) any programming language:
1. **Loose waiting**
* Executing thread blocks for given time (= does not consume processing power)
* No processing is possible on blocked/waiting thread
* Not so precise
2. **Tight waiting** (also called tight loop)
* processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time)
* Some actions can be performed while waiting
* Very precise
3. **Combination** of previous 2
* It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.
---
**for 1. - Loose waiting in C#:**
```
Thread.Sleep(numberOfMilliseconds);
```
However, windows thread scheduler causes acccuracy of `Sleep()` to be around 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).
**for 2. - Tight waiting in C# is:**
```
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do possible
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
}
```
We could also use `DateTime.Now` or other means of time measurement, but `Stopwatch` is much faster (and this would really become visible in tight loop).
**for 3. - Combination:**
```
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do STILL POSSIBLE
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
Thread.Sleep(1); //so processor can rest for a while
}
```
This code regularly blocks thread for 1ms (or slightly more, depending on OS thread scheduling), so processor is not busy for that time of blocking and code does not consume 100% of processor's power. Other processing can still be performed in-between blocking (such as: updating of UI, handling of events or doing interaction/communication stuff).
|
How do I get my C# program to sleep for 50 milliseconds?
|
[
"",
"c#",
"vb.net",
""
] |
This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.
|
`foreach` does *not* require `IEnumerable`, contrary to popular belief. All it requires is a method `GetEnumerator` that returns any object that has the method `MoveNext` and the get-property `Current` with the appropriate signatures.
/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:
```
class EnumerableWrapper {
private readonly TheObjectType obj;
public EnumerableWrapper(TheObjectType obj) {
this.obj = obj;
}
public IEnumerator<YourType> GetEnumerator() {
return obj.TheMethodReturningTheIEnumerator();
}
}
// Called like this:
foreach (var xyz in new EnumerableWrapper(yourObj))
…;
```
/EDIT: The following method, proposed by several people, does *not* work if the method returns an `IEnumerator`:
```
foreach (var yz in yourObj.MethodA())
…;
```
|
Re: If foreach doesn't require an explicit interface contract, does it find GetEnumerator using reflection?
(I can't comment since I don't have a high enough reputation.)
If you're implying *runtime* reflection then no. It does it all compiletime, another lesser known fact is that it also check to see if the returned object that *might* Implement IEnumerator is disposable.
To see this in action consider this (runnable) snippet.
```
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class FakeIterator
{
int _count;
public FakeIterator(int count)
{
_count = count;
}
public string Current { get { return "Hello World!"; } }
public bool MoveNext()
{
if(_count-- > 0)
return true;
return false;
}
}
class FakeCollection
{
public FakeIterator GetEnumerator() { return new FakeIterator(3); }
}
class Program
{
static void Main(string[] args)
{
foreach (string value in new FakeCollection())
Console.WriteLine(value);
}
}
}
```
|
Does Class need to implement IEnumerable to use Foreach
|
[
"",
"c#",
"foreach",
"ienumerable",
""
] |
In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there:
(channels) \* (bits) \* (samples/s) \* (seconds) = (filesize)
Is there a simpler way - a free library, or something in the .net framework perhaps?
How would I do this if the .wav file is compressed (with the mpeg codec for example)?
|
You may consider using the mciSendString(...) function (error checking is omitted for clarity):
```
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Sound
{
public static class SoundInfo
{
[DllImport("winmm.dll")]
private static extern uint mciSendString(
string command,
StringBuilder returnValue,
int returnLength,
IntPtr winHandle);
public static int GetSoundLength(string fileName)
{
StringBuilder lengthBuf = new StringBuilder(32);
mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
mciSendString("close wave", null, 0, IntPtr.Zero);
int length = 0;
int.TryParse(lengthBuf.ToString(), out length);
return length;
}
}
}
```
|
Download NAudio.dll
from the link
<https://www.dll-files.com/naudio.dll.html>
and then use this function
```
public static TimeSpan GetWavFileDuration(string fileName)
{
WaveFileReader wf = new WaveFileReader(fileName);
return wf.TotalTime;
}
```
you will get the Duration
|
How can I determine the length (i.e. duration) of a .wav file in C#?
|
[
"",
"c#",
"audio",
"compression",
""
] |
Now that it's clear [what a metaclass is](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using `__init__` and `__new__` lead to wonder what this bloody `__call__` can be used for.
Could you give me some explanations, including examples with the magic method ?
|
A callable is anything that can be called.
The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either:
* an instance of a class with a `__call__` method or
* is of a type that has a non null *tp\_call* (c struct) member which indicates callability otherwise (such as in functions, methods etc.)
The method named `__call__` is ([according to the documentation](https://docs.python.org/3/reference/datamodel.html#object.__call__))
> Called when the instance is ''called'' as a function
## Example
```
class Foo:
def __call__(self):
print 'called'
foo_instance = Foo()
foo_instance() #this is calling the __call__ method
```
|
From Python's sources [object.c](http://svn.python.org/view/python/trunk/Objects/object.c?rev=64962&view=markup):
```
/* Test whether an object can be called */
int
PyCallable_Check(PyObject *x)
{
if (x == NULL)
return 0;
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "__call__");
if (call == NULL) {
PyErr_Clear();
return 0;
}
/* Could test recursively but don't, for fear of endless
recursion if some joker sets self.__call__ = self */
Py_DECREF(call);
return 1;
}
else {
return x->ob_type->tp_call != NULL;
}
}
```
It says:
1. If an object is an instance of some class then it is callable *iff* it has `__call__` attribute.
2. Else the object `x` is callable *iff* `x->ob_type->tp_call != NULL`
Desciption of [`tp_call` field](http://docs.python.org/api/type-structs.html):
> `ternaryfunc tp_call` An optional
> pointer to a function that implements
> calling the object. This should be
> NULL if the object is not callable.
> The signature is the same as for
> PyObject\_Call(). This field is
> inherited by subtypes.
You can always use built-in `callable` function to determine whether given object is callable or not; or better yet just call it and catch `TypeError` later. `callable` is removed in Python 3.0 and 3.1, use `callable = lambda o: hasattr(o, '__call__')` or `isinstance(o, collections.Callable)`.
Example, a simplistic cache implementation:
```
class Cached:
def __init__(self, function):
self.function = function
self.cache = {}
def __call__(self, *args):
try: return self.cache[args]
except KeyError:
ret = self.cache[args] = self.function(*args)
return ret
```
Usage:
```
@Cached
def ack(x, y):
return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1)
```
Example from standard library, file [`site.py`](http://svn.python.org/projects/python/trunk/Lib/site.py), definition of built-in `exit()` and `quit()` functions:
```
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
```
|
What is a "callable"?
|
[
"",
"python",
"callable",
""
] |
<http://en.wikipedia.org/wiki/Diamond_problem>
I know what it means, but what steps can I take to avoid it?
|
A practical example:
```
class A {};
class B : public A {};
class C : public A {};
class D : public B, public C {};
```
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:
```
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
```
|
I'd stick to using multiple inheritance of interfaces only. While multiple inheritance of classes is attractive sometimes, it can also be confusing and painful if you rely on it regularly.
|
How can I avoid the Diamond of Death when using multiple inheritance?
|
[
"",
"c++",
"multiple-inheritance",
""
] |
It looks quite easy to find such a tool for Java ([Checkstyle](http://checkstyle.sourceforge.net/), [JCSC](http://jcsc.sourceforge.net/)), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.
|
The only tool I know is [Vera](http://bitbucket.org/verateam/vera). Haven't used it, though, so can't comment how viable it is. [Demo](http://www.inspirel.com/vera/ce/demo.html) looks promising.
|
Google [c++lint](https://github.com/google/styleguide/tree/gh-pages/cpplint) from [Google code style guide](https://google.github.io/styleguide/cppguide.html).
|
A free tool to check C/C++ source code against a set of coding standards?
|
[
"",
"c++",
"c",
"coding-style",
""
] |
Greetings!
I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:
```
<Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc" attrib2="222" attrib3="false" />
<Item attrib1="ddd" attrib2="333" attrib3="true" />
</GroupB>
<GroupC>
<Item attrib1="eee" attrib2="444" attrib3="true" />
<Item attrib1="fff" attrib2="555" attrib3="true" />
</GroupC>
</Root>
```
I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:
```
var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
select new
{
attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,
attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
};
```
The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?
|
```
XElement e = XElement.Parse(testStr);
string groupName = "GroupB";
var items = from g in e.Elements(groupName)
from i in g.Elements("Item")
select new {
attr1 = (string)i.Attribute("attrib1"),
attr2 = (string)i.Attribute("attrib2")
};
foreach (var item in items)
{
Console.WriteLine(item.attr1 + ":" + item.attr2);
}
```
|
Yes, .Element() only returns the first matching element. You want .Elements() and you need to re-write your query somewhat:
```
var results = from group in l_theDoc.Root.Elements(groupName)
select new
{
items = from i in group.Elements("Item")
select new
{
attrib1_val = i.Attribute("attrib1").Value,
attrib2_val = i.Attribute("attrib2").Value
}
};
```
|
LINQ to XML Newbie Question: Returning More Than One Result
|
[
"",
"c#",
"linq-to-xml",
""
] |
For our online game, we have written tons of PHP classes and functions grouped by theme in files and then folders. In the end, we have now all our backend code (logic & DB access layers) in a set of files that we call **libs** and we include our libs in our GUI (web pages, presentation layer) using *include\_once('pathtolib/file.inc')*.
The problem is that we have been lazy with inclusions and most include statements are made inside our libs file resulting that from each webpage, each time we include any libs file, we actually load the entire libs, file by file.
This has a significant impact on the performance. Therefore What would be the best solution ?
* Remove all include statements from the libs file and only call the necessary one from the web pages ?
* Do something else ?
Server uses a classic LAMP stack (PHP5).
EDIT: We have a mix of simple functions (legacy reason and the majority of the code) and classes. So autoload will not be enough.
|
* Manage all includes manually, only where needed
* Set your include\_path to only where it has to be, the default is something like .:/usr/lib/pear/:/usr/lib/php, point it only at where it has to be, php.net/set\_include\_path
* Don't use autoload, it's slow and makes APC and equivalent caches jobs a lot harder
* You can turn off the "stat"-operation in APC, but then you have to clear the cache manually every time you update the files
|
If you've done your programming in an object-oriented way, you can make use of the [autoload](https://www.php.net/autoload) function, which will load classes from their source files on-demand as you call them.
**Edit**: I noticed that someone downvoted both answers that referred to autoloading. Are we wrong? Is the overhead of the \_\_autoload function too high to use it for performance purposes? If there is something I'm not realizing about this technique, I'd be really interested to know what it is.
|
How to create a fast PHP library?
|
[
"",
"php",
"include",
""
] |
I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?
|
Looks like they've added controller.UpdateModel to address this issue, signature is:
```
UpdateModel(object model, string[] keys)
```
I haven't upgraded my app personally, so I'm not sure of the actual usage. I'll be interested to find out about this myself, as I'm using `controller.ReadFromRequest` as well.
|
Not sure where it went. You could roll your own extension though:
public static class MyBindingExtensions
{
```
public static T ReadFromRequest < T > (this Controller controller, string key)
{
// Setup
HttpContextBase context = controller.ControllerContext.HttpContext;
object val = null;
T result = default(T);
// Gaurd
if (context == null)
return result; // no point checking request
// Bind value (check form then query string)
if (context.Request.Form[key] != null)
val = context.Request.Form[key];
if (val == null)
{
if (context.Request.QueryString[key] != null)
val = context.Request.QueryString[key];
}
// Cast value
if (val != null)
result = (t)val;
return result;
}
}
```
|
What is the replacement of Controller.ReadFromRequest in ASP.NET MVC?
|
[
"",
"c#",
"asp.net-mvc",
".net-3.5",
"entity-framework-ctp5",
""
] |
I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.
I've been doing this via JavaScript, which works so far, using the following code
```
document.getElementById('chart').src = '/charts/10.png';
```
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.
What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.
I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.
A good suggestion I've had is to use the following
```
<img src="/charts/10.png" lowsrc="/spinner.gif"/>
```
Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.
Any other ideas?
|
I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
```
function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
```
|
You could show a static image that gives the [optical illusion of a spinny-wheel, like these](http://www.ritsumei.ac.jp/~akitaoka/saishin-e.html).
|
How to show a spinner while loading an image via JavaScript
|
[
"",
"javascript",
"jquery",
"dom",
""
] |
Is it possible to modify the title of the message box the confirm() function opens in JavaScript?
I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:
```
confirm("This is the content of the message box", "Modified title");
```
The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this.
|
This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.
There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.
|
YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)
```
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
// what to do if answer "YES"
}else{
// what to do if answer "NO"
}
```
Enjoy it!
|
Changing the default title of confirm() in JavaScript?
|
[
"",
"javascript",
""
] |
I have a properties file in java, in which I store all information of my app, like logo image filename, database name, database user and database password.
I can store the password encrypted on the properties file. But, the key or passphrase can be read out of the jar using a decompiler.
Is there a way to store the db pass in a properties file securely?
|
There are multiple ways to manage this. If you can figure out a way to have a user provide a password for a keystore when the application starts up the most appropriate way would be to encrypt all the values using a key, and store this key in the keystore. The command line interface to the keystore is by using keytool. However JSE has APIs to programmatically access the keystore as well.
If you do not have an ability to have a user manually provide a password to the keystore on startup (say for a web application), one way to do it is to write an exceptionally complex obfuscation routine which can obfuscate the key and store it in a property file as well. Important things to remember is that the obfuscation and deobfuscation logic should be multi layered (could involve scrambling, encoding, introduction of spurious characters etc. etc.) and should itself have at least one key which could be hidden away in other classes in the application using non intuitive names. This is not a fully safe mechanism since someone with a decompiler and a fair amount of time and intelligence can still work around it but is the only one I know of which does not require you to break into native (ie. non easily decompilable) code.
|
You store a SHA1 hash of the password in your properties file. Then when you validate a users password, you hash their login attempt and make sure that the two hashes match.
This is the code that will hash some bytes for you. You can easily ger bytes from a String using the `getBytes()` method.
```
/**
* Returns the hash value of the given chars
*
* Uses the default hash algorithm described above
*
* @param in
* the byte[] to hash
* @return a byte[] of hashed values
*/
public static byte[] getHashedBytes(byte[] in)
{
MessageDigest msg;
try
{
msg = MessageDigest.getInstance(hashingAlgorithmUsed);
}
catch (NoSuchAlgorithmException e)
{
throw new AssertionError("Someone chose to use a hashing algorithm that doesn't exist. Epic fail, go change it in the Util file. SHA(1) or MD5");
}
msg.update(in);
return msg.digest();
}
```
|
Protect embedded password
|
[
"",
"java",
"security",
"passwords",
"embedded-resource",
"copy-protection",
""
] |
Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business.
Now for anyone who is willing to help heres the situation. For my current assignment we have to read a file that is just a block of text. For each word in the file we are to clear any punctuation in the word (ex : "can't" would end up as "can" and "that--to" would end up as "that" obviously with out the quotes, quotes were used just to specify what the example was).
The problem I've run into is that I can clean the string fine and then insert it into the map that we are using but for some reason with the code I have written it is allowing an empty string to be inserted into the map. Now I've tried everything that I can come up with to stop this from happening and the only thing I've come up with is to use the erase method within the map structure itself.
So what I am looking for is two things, any suggestions about how I could a) fix this with out simply just erasing it and b) any improvements that I could make on the code I already have written.
Here are the functions I have written to read in from the file and then the one that cleans it.
Note: the function that reads in from the file calls the clean\_entry function to get rid of punctuation before anything is inserted into the map.
Edit: Thank you Chris. Numbers are allowed :). If anyone has any improvements to the code I've written or any criticisms of something I did I'll listen. At school we really don't get feed back on the correct, proper, or most efficient way to do things.
```
int get_words(map<string, int>& mapz)
{
int cnt = 0; //set out counter to zero
map<string, int>::const_iterator mapzIter;
ifstream input; //declare instream
input.open( "prog2.d" ); //open instream
assert( input ); //assure it is open
string s; //temp strings to read into
string not_s;
input >> s;
while(!input.eof()) //read in until EOF
{
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
input >>s;
}
input.close(); //close instream
for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++)
cnt = cnt + mapzIter->second;
return cnt; //return number of words in instream
}
void clean_entry(const string& non_clean, string& clean)
{
int i, j, begin, end;
for(i = 0; isalnum(non_clean[i]) == 0 && non_clean[i] != '\0'; i++);
begin = i;
if(begin ==(int)non_clean.length())
return;
for(j = begin; isalnum(non_clean[j]) != 0 && non_clean[j] != '\0'; j++);
end = j;
clean = non_clean.substr(begin, (end-begin));
for(i = 0; i < (int)clean.size(); i++)
clean[i] = tolower(clean[i]);
}
```
|
The problem with empty entries is in your while loop. If you get an empty string, you clean the next one, and add it without checking. Try changing:
```
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
input >>s;
```
to
```
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() > 0)
{
mapz[not_s]++; //increment occurence
}
input >>s;
```
EDIT: I notice you are checking if the characters are alphanumeric. If numbers are not allowed, you may need to revisit that area as well.
|
Further improvements would be to
* declare variables only when you use them, and in the innermost scope
* use c++-style casts instead of the c-style (int) casts
* use empty() instead of length() == 0 comparisons
* use the prefix increment operator for the iterators (i.e. `++mapzIter`)
|
Cleaning a string of punctuation in C++
|
[
"",
"c++",
""
] |
I have the following script, where the first and third `document.writeline` are static and **the second is generated**:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
document.write("<script language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");
</script>
```
Firefox and Chrome will display *before*, *during* and *after*, while Internet Explorer first shows *during* and only then does it show *before* and *after*.
I've come across [an article that states](http://www.elctech.com/blog/nesting-document-write) that I'm not the first to encounter this, but that hardly makes me feel any better.
**Does anyone know how I can set the order to be deterministic in all browsers, or hack IE to work like all the other, sane browsers do?**
**Caveats**: The code snippet is a very simple repro. It is generated on the server and the second script is the only thing that changes. It's a long script and the reason there are two scripts before and after it are so that the browser will cache them and the dynamic part of the code will be as small as possible. It may also appears many times in the same page with different generated code.
|
I've found an answer more to my liking:
```
<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'><\/sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript'>alert('during');<\/sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript' src='after.js'><\/sc" + "ript>");
</script>
```
This will defer the loading of both *during* and *after* until the page has finished loading.
I think this is as good as I can get. Hopefully, someone will be able to give a better answer.
|
No, this is the behavior of Internet Explorer.
If you attach scripts dynamically, IE, Firefox, and Chrome will all download the scripts in an asynchronous manner.
Firefox and Chrome will wait till all of the async requests return and then will execute the scripts in the order that they are attached in the DOM but IE executes the scripts in the order that they are returned over the wire.
Since the alert takes less time to "retrieve" than an external javascript file, that likely explains the behavior that you are seeing.
From Kristoffer Henriksson's [post on the subject of asynchronous script loading](http://blogs.msdn.com/kristoffer/archive/2006/12/22/loading-javascript-files-in-parallel.aspx):
> In this scenario IE and Firefox will
> download both scripts but Internet
> Explorer will also execute them in the
> order they finish downloading in
> whereas Firefox downloads them
> asynchronously but still executes them
> in the order they are attached in the
> DOM.
>
> In Internet Explorer this means your
> scripts cannot have dependancies on
> one another as the execution order
> will vary depending on network
> traffic, caches, etc.
Consider using a Javascript loader. It will let you specify script dependencies and order of execution while also loading your scripts asynchronously for speed as well as smoothing out some of the browser differences.
This is a pretty good overview of a few of them: [Essential JavaScript: the top five script loaders](http://www.netmagazine.com/features/essential-javascript-top-five-script-loaders).
I've used both RequireJS and LabJS. In my opinion, LabJS is a little less opinionated.
|
JavaScript's document.write Inline Script Execution Order
|
[
"",
"javascript",
"cross-browser",
"browser",
""
] |
Is there a side effect in doing this:
C code:
```
struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
```
C++ code:
```
class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
```
There's an `extern "C"` around the C++ code and each code is inside its own compilation unit.
Is this portable across compilers?
|
This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.
There is one caveat here. There is *no guarantee* of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.
I *have* had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.
|
I certainly not recommend using such weird subclassing. It would be better to change your design to use composition instead of inheritance.
Just make one member
> foo\* m\_pfoo;
in the bar class and it will do the same job.
Other thing you can do is to make one more class FooWrapper, containing the structure in itself with the corresponding getter method. Then you can subclass the wrapper. This way the problem with the virtual destructor is gone.
|
Is it possible to subclass a C struct in C++ and use pointers to the struct in C code?
|
[
"",
"c++",
"c",
"gcc",
"extern-c",
""
] |
I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.
This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)
Right now, I have a simple:
```
matches += array1[0] == array2[0];
```
repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop)
Is there any other way that could work faster?
Some data about the environment and the data itself:
* I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one.
* The data will be different most of the times. 100% equal data is usually very very rare (maybe less than 1%)
|
UPDATE: This answer has been modified to make my comments match the source code provided below.
There is an optimization available if you have the capability to use SSE2 and popcnt instructions.
16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm registers, and cmp them. This generates a bitmask representing the true/false condition of the compare. You then use a movmsk instruction to load a bit representation of the bitmask into an x86 register; this then becomes a bit field where you can count all the 1's to determine how many true values you had. A hardware popcnt instruction can be a fast way to count all the 1's in a register.
This requires knowledge of assembly/intrinsics and SSE in particular. You should be able to find web resources for both.
If you run this code on a machine that does not support either SSE2 or popcnt, you must then iterate through the arrays and count the differences with your unrolled loop approach.
Good luck
Edit:
Since you indicated you did not know assembly, here's some sample code to illustrate my answer:
```
#include "stdafx.h"
#include <iostream>
#include "intrin.h"
inline unsigned cmpArray16( char (&arr1)[16], char (&arr2)[16] )
{
__m128i first = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr1 ) );
__m128i second = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr2 ) );
return _mm_movemask_epi8( _mm_cmpeq_epi8( first, second ) );
}
int _tmain( int argc, _TCHAR* argv[] )
{
unsigned count = 0;
char arr1[16] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 };
char arr2[16] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 };
count = __popcnt( cmpArray16( arr1, arr2 ) );
std::cout << "The number of equivalent bytes = " << count << std::endl;
return 0;
}
```
Some notes: This function uses SSE2 instructions and a popcnt instruction introduced in the Phenom processor (that's the machine that I use). I believe the most recent Intel processors with SSE4 also have popcnt. This function does not check for instruction support with CPUID; the function is undefined if used on a processor that does not have SSE2 or popcnt (you will probably get an invalid opcode instruction). That detection code is a separate thread.
I have not timed this code; the reason I think it's faster is because it compares 16 bytes at a time, branchless. You should modify this to fit your environment, and time it yourself to see if it works for you. I wrote and tested this on VS2008 SP1.
SSE prefers data that is aligned on a natural 16-byte boundary; if you can guarantee that then you should get additional speed improvements, and you can change the \_mm\_loadu\_si128 instructions to \_mm\_load\_si128, which requires alignment.
|
The key is to do the comparisons using the largest register your CPU supports, then fallback to bytes if necessary.
The below code demonstrates with using 4-byte integers, but if you are running on a SIMD architecture (any modern Intel or AMD chip) you could compare both arrays in one instruction before falling back to an integer-based loop. Most compilers these days have intrinsic support for 128-bit types so will NOT require ASM.
(Note that for the SIMD comparisions your arrays would have to be 16-byte aligned, and some processors (e.g MIPS) would require the arrays to be 4-byte aligned for the int-based comparisons.
E.g.
```
int* array1 = (int*)byteArray[0];
int* array2 = (int*)byteArray[1];
int same = 0;
for (int i = 0; i < 4; i++)
{
// test as an int
if (array1[i] == array2[i])
{
same += 4;
}
else
{
// test individual bytes
char* bytes1 = (char*)(array1+i);
char* bytes2 = (char*)(array2+i);
for (int j = 0; j < 4; j++)
{
same += (bytes1[j] == bytes2[j];
}
}
}
```
I can't remember what exactly the MSVC compiler supports for SIMD, but you could do something like;
```
// depending on compiler you may have to insert the words via an intrinsic
__m128 qw1 = *(__m128*)byteArray[0];
__m128 qw2 = *(__m128*)byteArray[1];
// again, depending on the compiler the comparision may have to be done via an intrinsic
if (qw1 == qw2)
{
same = 16;
}
else
{
// do int/byte testing
}
```
|
Fastest way to see how many bytes are equal between fixed length arrays
|
[
"",
"c++",
"arrays",
"optimization",
""
] |
How would one write a regular expression to use in Python to split paragraphs?
A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.
I am using Python, so the solution can use Python's [regular expression syntax](https://docs.python.org/2/library/re.html) which is extended. (can make use of `(?P...)` stuff)
### Examples:
```
the_str = 'paragraph1\n\nparagraph2'
# Splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# Should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# Should yield ['p1', '\n\tp2']
```
The best I could come with is: `r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'`, i.e.
```
import re
paragraphs = re.split(r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*', the_str)
```
But that is ugly. Is there anything better?
### Suggestions rejected:
`r'\s*?\n\s*?\n\s*?'` -> That would make example 2 and 3 fail, since `\s` includes `\n`, so it would allow paragraph breaks with more than 2 `\n`s.
|
Unfortunately there's no nice way to write "space but not a newline".
I think the best you can do is add some space with the `x` modifier and try to factor out the ugliness a bit, but that's questionable: `(?x) (?: [ \t\r\f\v]*? \n ){2} [ \t\r\f\v]*?`
You could also try creating a subrule just for the character class and interpolating it three times.
|
It is not a regexp, but it is really elegant:
```
from itertools import groupby
def paragraph(lines):
for group_separator, line_iteration in groupby(lines.splitlines(True), key = str.isspace):
if not group_separator:
yield ''.join(line_iteration)
for p in paragraph('p1\n\t\np2\t\n\tstill p2\t \n \n\tp'):
print repr(p)
'p1\n'
'p2\t\n\tstill p2\t \n'
'\tp3'
```
It's up to you to strip the output as you need it of course.
It was inspired by the famous "Python Cookbook" ;-)
|
Python regular expression to split paragraphs
|
[
"",
"python",
"regex",
"parsing",
"text",
"split",
""
] |
I have a side project I do = in Java. It's a pretty straight-forward webapp. It runs in Tomcat on a Linux Server and uses a MySQL database. The majority of the code was written with the Spring Framework. It has a lot of Unit Tests in place. When I'm coding it's in Eclipse. When I deploy the application I run a few shell scripts to move a WAR file to the web server, do Database updates, and make changes to apache configs. I'm the only developer working on it, and right now it's only deployed to 1 environment(production), although some day I might want to have a testing or staging environment as well. I use SVN version control, via the Eclipse plug-in.
I'm always hearing about people using Maven for their projects. Since so many people are using it, I'm saying to myself it must be good. I'd like to learn it in my spare time. The only thing is I'm not quite sold on why I'd want to use Maven? Does my first paragraph sound like a project appropriate for Maven? Does it have any specific advantages for a project that interacts with a Database?
|
Your project does not sound like a project appropriate for Maven. You seem to have a working development environment. Why set up another one? It will just give you one more project file to maintain which breaks the good ol' [DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle.
|
Maven would be a good fit for your project IMO. Maven is an all around build and deployment management tool. It's biggest strength is that it makes build scripts significantly eaiser to maintain than functionally comparable Ant files or shell scripts.
There are a lot of advantages to using maven the biggest being it's preference of convention over configuration. This means that if you have your project laid out using the Maven directory structure there is almost no configuration required to get it building and running your JUnit tests.
The other big win that Maven gives you is dependency management. You can declaratively define your project's dependencies in Maven's config file called the Project Object Model (POM) and Maven does the work of storing all the jars in a local directory structure that it maintains. In the case of publicly available artifacts the jars are automatically downloaded from the Maven central repository and in the case of internal or proprietary 3rd party jars you can install them into your repository with a single command.
In addition to just organizing these artifacts and automatically setting up your build classpath to include all the necessary jars, maven will also manage dependency hierarchies. That means that if your project depends on jar A and A depends on jar B, jar B will automatically be bundled with your WAR even though you don't explicitly list it as a dependency in your build config.
Also, I'll say from a professional development standpoint it makes sense to learn Maven since in my experience Maven has overtaken Ant as the de jure build tool of choice both in open source and proprietary Java projects.
All this being said, if you have a build system that is fast and reliable for you, then it might not be worth the effort to convert over to Maven just for the sake of using the same tool everyone else is.
|
Thinking of learning Maven
|
[
"",
"java",
"maven-2",
""
] |
I am looking for a library that will allow me to look up the status of a windows service to verify that the service is started and running. I looked into the Sigar library, but it is GPL and therefor I cannot use it. A Commercial or BSD(ish) license is required as this will be bundled into commercial software.
|
If nothing else helps, try to think of a slightly different approach (if you can, of course), e.g.:
* There is a plenty of free/non-free software which does monitoring, including Windows service monitoring (e.g. nagios, Zabbix, etc.). These monitors typically have open API where your Java app could integrate into in a number of different ways.
* If you have the control over depending service application, expose another, different way for your Java application to check (e.g. run a dummy listener on a port, create a file, etc.). Windows services aren't a cross-platform thing therefore is not something you would expect to be supported anytime soon.
|
I don't think there is any pure-Java way to do this because some operating systems don't have the notion of "services" like Windows does. In our projects, we wrote a wrapper around calls to the "sc" command from the command line. To get the status of a service, you can do:
> sc \\some-computer query "my service name"
You'll have to manually parse the output but it's pretty straightforward.
|
Is there any way, in java, to check on the status of a windows service?
|
[
"",
"java",
"windows-services",
"system-monitoring",
"system-status",
""
] |
In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.
Thus myapp.war gets deployed to <http://example.com/myapp>.
The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp".
The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <http://example.com/myapp/mypage.jsp>".
However, you can't do that with, say, the IMG tag in HTML. If you do <img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif".
Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly).
It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url.
Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like).
I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for.
What do you do?
|
You can use JSTL for creating urls.
For example, `<c:url value="/images/header.jpg" />` will prefix the context root.
With CSS, this usually isn't an issue for me.
I have a web root structure like this:
/css
/images
In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't need to be aware of the context root.
As for JavaScript, what works for me is including some common JavaScript in the page header like this:
```
<script type="text/javascript">
var CONTEXT_ROOT = '<%= request.getContextPath() %>';
</script>
```
Then you can use the context root in all your scripts (or, you can define a function to build paths - may be a bit more flexible).
Obviously this all depends on your using JSPs and JSTL, but I use JSF with Facelets and the techniques involved are similar - the only real difference is getting the context root in a different way.
|
For HTML pages, I just set the HTML `<base>` tag. Every relative link (i.e. not starting with scheme or `/`) will become relative to it. There is no clean way to grab it immediately by `HttpServletRequest`, so we need little help of JSTL here.
```
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri">${req.requestURI}</c:set>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
<link rel="stylesheet" href="css/default.css">
<script src="js/default.js"></script>
</head>
<body>
<img src="img/logo.png" />
<a href="other.jsp">link</a>
</body>
</html>
```
This has in turn however a caveat: anchors (the `#identifier` URL's) will become relative to the base path as well. If you have any of them, you would like to make it relative to the request URL (URI) instead. So, change like
```
<a href="#identifier">jump</a>
```
to
```
<a href="${uri}#identifier">jump</a>
```
---
In JS, you can just access the `<base>` element from the DOM whenever you'd like to convert a relative URL to an absolute URL.
```
var base = document.getElementsByTagName("base")[0].href;
```
Or if you do jQuery
```
var base = $("base").attr("href");
```
---
In CSS, the image URLs are relative to the URL of the stylesheet itself. So, just drop the images in some folder relative to the stylesheet itself. E.g.
```
/css/style.css
/css/images/foo.png
```
and reference them as follows
```
background-image: url('images/foo.png');
```
If you rather like to drop the images in some folder at same level as CSS folder
```
/css/style.css
/images/foo.png
```
then use `../` to go to the common parent folder
```
background-image: url('../images/foo.png');
```
### See also:
* [Is it recommended to use the `<base>` html tag?](https://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag)
|
Any clever ways of handling the context in a web app?
|
[
"",
"java",
"jsp",
"servlets",
"contextpath",
""
] |
PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.
Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.
Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, ***I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.***
How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages?
Also, how can you do all this while accounting for inheritance in Php? Consider:
```
<?php
class InterfaceClass
{
#...
}
class UsesInterfaceClass
{
function SetObject(&$obj)
{
// What do I put here to make sure that $obj either
// is of type InterfaceObject or inherits from it
}
}
?>
```
Then a user of this code implements the interface with their own concrete class:
```
<?php
class ConcreteClass extends InterfaceClass
{
}
?>
```
I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?
|
Actually for classes you can provide type hinting in PHP (5+).
```
<?php
class UsesBaseClass
{
function SetObject(InterfaceObject $obj)
{
}
}
?>
```
This will also work correctly with inheritance as you would expect it to.
As an aside, don't put the word 'object' in your class names...
|
as an addition to Eran Galperin's response you can also use the type hinting to force parameters to be arrays - not just objects of a certain class.
```
<?php
class MyCoolClass {
public function passMeAnArray(array $array = array()) {
// do something with the array
}
}
?>
```
As you can see you can type hint that the `::passMeAnArray()` method expects an `array` as well as provide a default value in case the method is called w/o any parameters.
|
How do I prevent using the incorrect type in PHP?
|
[
"",
"php",
"oop",
"type-safety",
""
] |
How do I exit a script early, like the `die()` command in PHP?
|
```
import sys
sys.exit()
```
details from the [`sys` module documentation](https://docs.python.org/2/library/sys.html#sys.exit):
> `sys.exit([arg])`
>
> Exit from Python. This is implemented by raising the
> [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit "SystemExit") exception, so cleanup actions specified by finally clauses
> of [`try`](https://docs.python.org/2/reference/compound_stmts.html#try "try") statements are honored, and it is possible to intercept the
> exit attempt at an outer level.
>
> The optional argument *arg* can be an integer giving the exit status
> (defaulting to zero), or another type of object. If it is an integer,
> zero is considered “successful termination” and any nonzero value is
> considered “abnormal termination” by shells and the like. Most systems
> require it to be in the range 0-127, and produce undefined results
> otherwise. Some systems have a convention for assigning specific
> meanings to specific exit codes, but these are generally
> underdeveloped; Unix programs generally use 2 for command line syntax
> errors and 1 for all other kind of errors. If another type of object
> is passed, None is equivalent to passing zero, and any other object is
> printed to [`stderr`](https://docs.python.org/2/library/sys.html#sys.stderr "sys.stderr") and results in an exit code of 1. In particular,
> `sys.exit("some error message")` is a quick way to exit a program when
> an error occurs.
>
> Since [`exit()`](https://docs.python.org/2/library/constants.html#exit "exit") ultimately “only” raises an exception, it will only exit
> the process when called from the main thread, and the exception is not
> intercepted.
Note that this is the 'nice' way to exit. @[glyphtwistedmatrix](https://stackoverflow.com/questions/73663/terminating-a-python-script#76374) below points out that if you want a 'hard exit', you can use `os._exit(*errorcode*)`, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it *does* kill the entire process, including all running threads, while `sys.exit()` (as it says in the docs) only exits if called from the main thread, with no other threads running.
|
A simple way to terminate a Python script early is to use the built-in `quit()` function. There is no need to import any library, and it is efficient and simple.
Example:
```
#do stuff
if this == that:
quit()
```
|
How do I terminate a script?
|
[
"",
"python",
"termination",
""
] |
I'm looking for an answer in MS VC++.
When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.
Example in pseudo code:
```
FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
FunctionB()
...
}
try
{
Function A()
}
catch(e)
{
(<--- breakpoint)
...
}
```
I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in `FunctionA()` or `FunctionB()`, or some other function. (Assuming extensive exception use and a huge version of the above example).
One solution to my problem is to determine and save the call stack **in the exception constructor** (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.
Is there an easier way that requires less work? Without having to change my large code base?
Are there better solutions to this problem in other languages?
|
If you are just interested in where the exception came from, you could just write a simple macro like
```
#define throwException(message) \
{ \
std::ostringstream oss; \
oss << __FILE __ << " " << __LINE__ << " " \
<< __FUNC__ << " " << message; \
throw std::exception(oss.str().c_str()); \
}
```
which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).
Then throw exceptions using
```
throwException("An unknown enum value has been passed!");
```
|
You pointed to a breakpoint in the code. Since you are in the debugger, you could set a breakpoint on the constructor of the exception class, or set Visual Studio debugger to break on all thrown exceptions (Debug->Exceptions Click on C++ exceptions, select thrown and uncaught options)
|
Finding out the source of an exception in C++ after it is caught?
|
[
"",
"c++",
"visual-studio",
"winapi",
"exception",
"visual-c++",
""
] |
Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.
For some reason I thought the following might work:
```
enum MY_ENUM : unsigned __int64
{
LARGE_VALUE = 0x1000000000000000,
};
```
|
I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using:
```
const __int64 LARGE_VALUE = 0x1000000000000000L;
```
As of C++11, it is possible to use enum classes to specify the base type of the enum:
```
enum class MY_ENUM : unsigned __int64 {
LARGE_VALUE = 0x1000000000000000ULL
};
```
In addition enum classes introduce a new name scope. So instead of referring to `LARGE_VALUE`, you would reference `MY_ENUM::LARGE_VALUE`.
|
C++11 supports this, using this syntax:
```
enum class Enum2 : __int64 {Val1, Val2, val3};
```
|
64 bit enum in C++?
|
[
"",
"c++",
"enums",
"64-bit",
""
] |
I have code that references a web service, and I'd like the address of that web service to be dynamic (read from a database, config file, etc.) so that it is easily changed. One major use of this will be to deploy to multiple environments where machine names and IP addresses are different. The web service signature will be the same across all deployments, just located elsewhere.
Maybe I've just been spoiled by the Visual Studio "Add Web Reference" wizard - seems like this should be something relatively easy, though.
|
When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Changing the value to dynamic will put an entry in your app.config.
Here is the [CodePlex article](http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx) that has more information.
|
If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.
Setting the value in the .config file from within your program:
1. Is a mess;
2. Might not be read until the next application start.
If it is only something that needs to be done once per installation, I'd agree with the other posters and use the .config file and the dynamic setting.
|
How can I dynamically switch web service addresses in .NET without a recompile?
|
[
"",
"c#",
"visual-studio",
"web-services",
"url",
"wsdl",
""
] |
A couple of months ago I've coded a tiny tool that we needed at work for a specific task, and I've decided to share it on CodePlex. It's written in C# and honestly it's not big deal but since it's the first project I've ever built from scratch in that language and with the goal of opening it from the very beginning, one ends getting sort of emotionally attached to it, I mean you'd wish that the people will actually participate, be it criticism, bug reporting, or what have you.
So my question is, what can I do to actually encourage participation, stimulate curiosity or just recieve more feedback about it?
By the way this is the project I'm talking about: <http://www.codeplex.com/winxmlcook/>
|
I know I sound like a broken record constantly posting this book, but just about everything you could ever need to know about running an open source project is [here](http://producingoss.com/en/index.html). In particular, pay attention to these two chapters:
* [Getting Started](http://producingoss.com/en/getting-started.html)
* [Managing Volunteers](http://producingoss.com/en/managing-volunteers.html)
|
You should:
* Promote it where you think it would be relevant (forums,mailing lists etc.). Try not to spam though - it will create a backlash.
* continue to provide updates as to create the appearance of an active project until more people pick it up.
* Find project leaders, they are the sort of contributors that encourage others to contribute as well.
* Blog about it and link to relevant blogs (creating ping-backs). Also leave comments at relevant blog posts.
Basically, your generic Internet marketing tactics ;)
|
What should I do to keep a tiny Open Source project active and sustainable?
|
[
"",
"c#",
".net",
"open-source",
""
] |
We've got a Java server application that runs on a number of computers, all connected to the Internet, some behind firewalls. We need to remotely update the JAR files and startup scripts from a central site, with no noticeable interruption to the app itself.
The process has to be unattended and foolproof (i.e. we can't afford to break the app due to untimely internet outages).
In the past we've used a variety of external scripts and utilities to handle similar tasks, but because they have their own dependencies, the result is harder to maintain and less portable. Before making something new, I want to get some input from the community.
Has anyone found a good solution for this already? Got any ideas or suggestions?
*Just to clarify: This app is a server, but not for web applications (no webapp containers or WAR files here). It's just an autonomous Java program.*
|
You didn't specify the type of server apps - I'm going to assume that you aren't running web apps (as deploying a WAR already does what you are talking about, and you very rarely need a web app to do pull type updates. If you are talking about a web app, the following discussion can still apply - you'll just implement the update check and ping-pong for the WAR file instead of individual files).
You may want to take a look at jnlp - WebStart is based on this (this is a client application deployment technology), but I'm pretty sure that it could be tailored to performing updates for a server type app. Regardless, jnlp does a pretty good job of providing descriptors that can be used for downloading required versions of required JARs...
Some general thoughts on this (we have several apps in the same bucket, and are considering an auto-update mechanism):
1. Consider having a bootstrap.jar file that is capable of reading a jnlp file and downloading required/updated jars prior to launching the application.
2. JAR files *can* be updated even while an app is running (at least on Windows, and that is the OS most likely to hold locks on running files). You can run into problems if you are using custom class loaders, or you have a bunch of JARs that might be loaded or unloaded at any time, but if you create mechanisms to prevent this, then overwriting JARs then re-launching the app should be sufficient for update.
3. Even though it is possible to overwrite JARs, you might want to consider a ping-pong approach for your lib path (if you don't already have your app launcher configured to auto-read all jar files in the lib folder and add them to the class path automatically, then that's something you really do want to do). Here's how ping-pong works:
App launches and looks at lib-ping\version.properties and lib-pong\version.properties and determines which is newer. Let's say that lib-ping has a later version. The launcher searches for lib-ping\*.jar and adds those files to the CP during the launch. When you do an update, you download jar files into lib-pong (or copy jar files from lib-ping if you want to save bandwidth and the JAR didn't actually change - this is rarely worth the effort, though!). Once you have all JARs copied into lib-pong, the very last thing you do is create the version.properties file (that way an interrupted update that results in a partial lib folder can be detected and purged). Finally, you re-launch the app, and bootstrap picks up that lib-pong is the desired classpath.
4. ping-pong as described above allows for a roll-back. If you design it properly, you can have one piece of your app that you test the heck out of and then never change that checks to see if it should roll-back a given version. That way if you do mess up and deploy something that breaks the app, you can invalidate the version. This part of the application just has to delete the version.properties file from the bad lib-\* folder, then re-launch. It's important to keep this part dirt simple because it's your fail safe.
5. You can have more than 2 folders (instead of ping/pong, just have lib-yyyymmdd and purge all but the newest 5, for example). This allows for more advanced (but more complicated!) rollback of JARs.
|
You should definitely take a look at OSGi, it was created just for these cases (especially for embedded products) and is used by a large number of companies. You can update jar "bundles", add and remove them, while the app is running. I haven't used it myself, so I don't know about the quality of the open source frameworks/servers, but here is a bunch of useful links to get you started:
<http://www.osgi.org/Main/HomePage>
<http://www.aqute.biz/Code/Bnd>
<http://blog.springsource.com/2008/02/18/creating-osgi-bundles/>
<http://blog.springsource.com/>
<http://www.knopflerfish.org/>
<http://felix.apache.org/site/index.html>
|
How do you remotely update Java applications?
|
[
"",
"java",
"release-management",
""
] |
Tomcat (version 5 here) stores session information in memory. When clustering this information is periodically broadcast to other servers in the cluster to keep things in sync. You can use a database store to make sessions persistant but this information is only written periodically as well and is only really used for failure-recovery rather than actually replacing the in-memory sessions.
If you don't want to use sticky sessions (our configuration doesn't allow it unfortunately) this raises the problem of the sessions getting out of sync.
In other languages, web frameworks tend to allow you to use a database as the primary session store. Whilst this introduces a potential scaling issue it does make session management very straightforward. I'm wondering if there's a way to get tomcat to use a database for sessions in this way (technically this would also remove the need for any clustering configuration in the tomcat server.xml).
|
There definitely is a way. Though I'd strongly vote for sticky sessions - saves so much load for your servers/database (unless something fails)...
<http://tomcat.apache.org/tomcat-5.5-doc/config/manager.html> has information about SessionManager configuration and setup for Tomcat. Depending on your exact requirements you might have to implement your own session manager, but this starting point should provide some help.
|
Take a look at [Terracotta](http://www.terracotta.org/), I think it can address your scaling issues without a major application redesign.
|
Is there a way to specify a different session store with Tomcat?
|
[
"",
"java",
"tomcat",
"session",
""
] |
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
---
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
|
If you on a debian[-like] machine,
```
#!/bin/bash
echo -n "Enter a word: "
read input
grep "^$input" /usr/share/dict/words
```
Takes all of 0.040s on my P200.
|
Use a [trie](http://en.wikipedia.org/wiki/Trie).
Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.
|
List all words in a dictionary that start with <user input>
|
[
"",
"python",
"list",
"dictionary",
""
] |
When I run a particular SQL script in Unix environments, I see a '^M' character at the end of each line of the SQL script as it is echoed to the command line.
I don't know on which OS the SQL script was initially created.
What is causing this and how do I fix it?
|
It's caused by the DOS/Windows line-ending characters. Like Andy Whitfield said, the Unix command dos2unix will help fix the problem. If you want more information, you can read the man pages for that command.
|
Fix line endings in `vi` by running the following:
`:set fileformat=unix`
`:w`
|
'^M' character at end of lines
|
[
"",
"sql",
"unix",
"newline",
"carriage-return",
"line-endings",
""
] |
Table:
```
UserId, Value, Date.
```
I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date.
How do I do this in SQL? (Preferably Oracle.)
I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.
|
This will retrieve all rows for which the my\_date column value is equal to the maximum value of my\_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.
```
select userid,
my_date,
...
from
(
select userid,
my_date,
...
max(my_date) over (partition by userid) max_my_date
from users
)
where my_date = max_my_date
```
"Analytic functions rock"
Edit: With regard to the first comment ...
"using analytic queries and a self-join defeats the purpose of analytic queries"
There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice.
"The default window in Oracle is from the first row in the partition to the current one"
The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified.
The code works.
|
I see many people use subqueries or else window functions to do this, but I often do this kind of query without subqueries in the following way. It uses plain, standard SQL so it should work in any brand of RDBMS.
```
SELECT t1.*
FROM mytable t1
LEFT OUTER JOIN mytable t2
ON (t1.UserId = t2.UserId AND t1."Date" < t2."Date")
WHERE t2.UserId IS NULL;
```
In other words: fetch the row from `t1` where no other row exists with the same `UserId` and a greater Date.
(I put the identifier "Date" in delimiters because it's an SQL reserved word.)
In case if `t1."Date" = t2."Date"`, doubling appears. Usually tables has `auto_inc(seq)` key, e.g. `id`.
To avoid doubling can be used follows:
```
SELECT t1.*
FROM mytable t1
LEFT OUTER JOIN mytable t2
ON t1.UserId = t2.UserId AND ((t1."Date" < t2."Date")
OR (t1."Date" = t2."Date" AND t1.id < t2.id))
WHERE t2.UserId IS NULL;
```
---
Re comment from @Farhan:
Here's a more detailed explanation:
An outer join attempts to join `t1` with `t2`. By default, all results of `t1` are returned, and *if* there is a match in `t2`, it is also returned. If there is no match in `t2` for a given row of `t1`, then the query still returns the row of `t1`, and uses `NULL` as a placeholder for all of `t2`'s columns. That's just how outer joins work in general.
The trick in this query is to design the join's matching condition such that `t2` must match the *same* `userid`, and a *greater* `date`. The idea being if a row exists in `t2` that has a greater `date`, then the row in `t1` it's compared against *can't* be the greatest `date` for that `userid`. But if there is no match -- i.e. if no row exists in `t2` with a greater `date` than the row in `t1` -- we know that the row in `t1` was the row with the greatest `date` for the given `userid`.
In those cases (when there's no match), the columns of `t2` will be `NULL` -- even the columns specified in the join condition. So that's why we use `WHERE t2.UserId IS NULL`, because we're searching for the cases where no row was found with a greater `date` for the given `userid`.
|
Fetch the rows which have the Max value for a column for each distinct value of another column
|
[
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
Working on a project that parses a log of events, and then updates a model based on properties of those events. I've been pretty lazy about "getting it done" and more concerned about upfront optimization, lean code, and proper design patterns. Mostly a self-teaching experiment. I am interested in what patterns more experienced designers think are relevant, or what type of pseudocoded object architecture would be the best, easiest to maintain and so on.
There can be 500,000 events in a single log, and there are about 60 types of events, all of which share about 7 base properties and then have 0 to 15 additional properties depending on the event type. The type of event is the 2nd property in the log file in each line.
So for I've tried a really ugly imperative parser that walks through the log line by line and then processes events line by line. Then I tried a lexical specification that uses a "nextEvent" pattern, which is called in a loop and processed. Then I tried a plain old "parse" method that never returns and just fires events to registered listener callbacks. I've tried both a single callback regardless of event type, and a callback method specific to each event type.
I've tried a base "event" class with a union of all possible properties. I've tried to avoid the "new Event" call (since there can be a huge number of events and the event objects are generally short lived) and having the callback methods per type with primitive property arguments. I've tried having a subclass for each of the 60 event types with an abstract Event parent with the 7 common base properties.
I recently tried taking that further and using a Command pattern to put event handling code per event type. I am not sure I like this and its really similar to the callbacks per type approach, just code is inside an execute function in the type subclasses versus the callback methods per type.
The problem is that alot of the model updating logic is shared, and alot of it is specific to the subclass, and I am just starting to get confused about the whole thing. I am hoping someone can at least point me in a direction to consider!
|
Well... for one thing rather than a single event class with a union of all the properties, or 61 event classes (1 base, 60 subs), in a scenario with that much variation, I'd be tempted to have a single event class that uses a property bag (dictionary, hashtable, w/e floats your boat) to store event information. The type of the event is just one more property value that gets put into the bag. The main reason I'd lean that way is just because I'd be loathe to maintain 60 derived classes of anything.
The big question is... what do you have to *do* with the events as you process them. Do you format them into a report, organize them into a database table, wake people up if certain events occur... what?
Is this meant to be an after-the-fact parser, or a real-time event handler? I mean, are you monitoring the log as events come in, or just parsing log files the next day?
|
Consider a Flyweight factory of Strategy objects, one per 'class' of event.
For each line of event data, look up the appropriate parsing strategy from the flyweight factory, and then pass the event data to the strategy for parsing. Each of the 60 strategy objects could be of the same class, but configured with a different combination of field parsing objects. Its a bit difficult to be more specific without more details.
|
Appropriate design pattern for an event log parser?
|
[
"",
"java",
"logging",
""
] |
While googling, I see that using [`java.io.File#length()`](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29) can be slow.
[`FileChannel`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) has a [`size()`](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#size%28%29) method that is available as well.
Is there an efficient way in java to get the file size?
|
Well, I tried to measure it up with the code below:
For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:
```
LENGTH sum: 10626, per Iteration: 10626.0
CHANNEL sum: 5535, per Iteration: 5535.0
URL sum: 660, per Iteration: 660.0
```
For runs = 5 and iterations = 50 the picture draws different.
```
LENGTH sum: 39496, per Iteration: 157.984
CHANNEL sum: 74261, per Iteration: 297.044
URL sum: 95534, per Iteration: 382.136
```
File must be caching the calls to the filesystem, while channels and URL have some overhead.
Code:
```
import java.io.*;
import java.net.*;
import java.util.*;
public enum FileSizeBench {
LENGTH {
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
return me.length();
}
},
CHANNEL {
@Override
public long getResult() throws Exception {
FileInputStream fis = null;
try {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
fis = new FileInputStream(me);
return fis.getChannel().size();
} finally {
fis.close();
}
}
},
URL {
@Override
public long getResult() throws Exception {
InputStream stream = null;
try {
URL url = FileSizeBench.class
.getResource("FileSizeBench.class");
stream = url.openStream();
return stream.available();
} finally {
stream.close();
}
}
};
public abstract long getResult() throws Exception;
public static void main(String[] args) throws Exception {
int runs = 5;
int iterations = 50;
EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);
for (int i = 0; i < runs; i++) {
for (FileSizeBench test : values()) {
if (!durations.containsKey(test)) {
durations.put(test, 0l);
}
long duration = testNow(test, iterations);
durations.put(test, durations.get(test) + duration);
// System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
}
}
for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
System.out.println();
System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
}
}
private static long testNow(FileSizeBench test, int iterations)
throws Exception {
long result = -1;
long before = System.nanoTime();
for (int i = 0; i < iterations; i++) {
if (result == -1) {
result = test.getResult();
//System.out.println(result);
} else if ((result = test.getResult()) != result) {
throw new Exception("variance detected!");
}
}
return (System.nanoTime() - before) / 1000;
}
}
```
|
The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:
```
file sum___19.0, per Iteration___19.0
raf sum___16.0, per Iteration___16.0
channel sum__273.0, per Iteration__273.0
```
For 100 runs and 10000 iterations I get:
```
file sum__1767629.0, per Iteration__1.7676290000000001
raf sum___881284.0, per Iteration__0.8812840000000001
channel sum___414286.0, per Iteration__0.414286
```
I did run the following modified code giving as an argument the name of a 100MB file.
```
import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
public class FileSizeBench {
private static File file;
private static FileChannel channel;
private static RandomAccessFile raf;
public static void main(String[] args) throws Exception {
int runs = 1;
int iterations = 1;
file = new File(args[0]);
channel = new FileInputStream(args[0]).getChannel();
raf = new RandomAccessFile(args[0], "r");
HashMap<String, Double> times = new HashMap<String, Double>();
times.put("file", 0.0);
times.put("channel", 0.0);
times.put("raf", 0.0);
long start;
for (int i = 0; i < runs; ++i) {
long l = file.length();
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != file.length()) throw new Exception();
times.put("file", times.get("file") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != channel.size()) throw new Exception();
times.put("channel", times.get("channel") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != raf.length()) throw new Exception();
times.put("raf", times.get("raf") + System.nanoTime() - start);
}
for (Map.Entry<String, Double> entry : times.entrySet()) {
System.out.println(
entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
}
}
}
```
|
java get file size efficiently
|
[
"",
"java",
"filesize",
""
] |
I'm using the ProgressBar control in a WPF application and I'm getting this old, Windows 3.1 Progress*Blocks* thing. In VB6, there was a property to show a *smooth* ProgressBar. Is there such a thing for WPF?
|
[This](http://support.microsoft.com/kb/323116) KB article seems to explain what you are looking for... there is a link to a VB version of the article too.
|
I was not able to find a direct solution for this. But I found something even better. In WPF, you can use Windows Themes. I am using Windows XP, and having Vista-Aero Theme on my WPF Application, making all controls look like Vista-Aero.
Here's the code...
Go to Application.xaml.vb and write...
```
Enum appThemes
Aero
Luna
LunaMettalic
LunaHomestead
Royale
End Enum
Private Sub Application_Startup(ByVal sender As Object, ByVal e As System.Windows.StartupEventArgs) Handles Me.Startup
setTheme(appThemes.Aero)
End Sub
''' <summary>
''' Function to set the default theme of this application
''' </summary>
''' <param name="Theme">
''' Theme of type appThemes
''' </param>
''' <remarks></remarks>
Public Sub setTheme(ByVal Theme As appThemes)
Dim uri As Uri
Select Case Theme
Case appThemes.Aero
' Vista Aero Theme
uri = New Uri("PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\\themes/Aero.NormalColor.xaml", UriKind.Relative)
Case appThemes.Luna
' Luna Theme
uri = New Uri("PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\themes/Luna.NormalColor.xaml", UriKind.Relative)
Case appThemes.LunaHomestead
' Luna Mettalic
uri = New Uri("PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\themes/Luna.Metallic.xaml", UriKind.Relative)
Case appThemes.LunaMettalic
' Luna Homestead
uri = New Uri("PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\themes/Luna.Homestead.xaml", UriKind.Relative)
Case appThemes.Royale
' Royale Theme
uri = New Uri("PresentationFramework.Royale;V3.0.0.0;31bf3856ad364e35;component\\themes/Royale.NormalColor.xaml", UriKind.Relative)
End Select
' Set the Theme
Resources.MergedDictionaries.Add(Application.LoadComponent(uri))
End Sub
```
(I hope you can convert it to C#)
|
Smooth ProgressBar in WPF
|
[
"",
"c#",
"wpf",
"progress-bar",
""
] |
I would like to call my unmanaged C++ libraries from my C# code. What are the potential pitfalls and precautions that need to be taken? Thank you for your time.
|
This question is too broad. The only reasonable answer is P/Invoke, but that's kind of like saying that if you want to program for Windows you need to know the Win32 API.
Pretty much entire books have been written about P/Invoke ([http://www.amazon.com/NET-COM-Complete-Interoperability-Guide/dp/067232170X](https://rads.stackoverflow.com/amzn/click/com/067232170X)), and of course entire websites have been made: <http://www.pinvoke.net/>.
|
There are a couple routes you can go with this - one, you can update your unmanaged C++ libraries to have a managed C++ extensions wrapper around them and have C# utilize those classes directly. This is a bit time-consuming, but it provides a nice bridge to legacy unmanaged code. But be aware that managed C++ extensions are sometimes a bit hard to navigate themselves as the syntax is similar to unmanaged C++, but close enough that a very trained eye will be able to see the differences.
The other route to go is have your umnanaged C++ implement COM classes and have C# utilize it via an autogenerated interop assembly. This way is easier if you know your way around COM well enough.
Hope this helps.
|
Mixing C# Code and umanaged C++ code on Windows with Visual Studio
|
[
"",
"c#",
"windows",
"visual-c++",
"unmanaged",
""
] |
I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.
So I'm thinking:
```
UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
```
But my brain hurts going any farther than that.
|
```
SELECT DISTINCT a,b,c FROM t
```
is *roughly* equivalent to:
```
SELECT a,b,c FROM t GROUP BY a,b,c
```
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
```
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
```
|
If you put together the answers so far, clean up and improve, you would arrive at this superior query:
```
UPDATE sales
SET status = 'ACTIVE'
WHERE (saleprice, saledate) IN (
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING count(*) = 1
);
```
Which is *much* faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).
But this is still far from optimal. Use a [**`NOT EXISTS`**](https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS) (anti-)semi-join for even better performance. `EXISTS` is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:
```
UPDATE sales s
SET status = 'ACTIVE'
WHERE NOT EXISTS (
SELECT FROM sales s1 -- SELECT list can be empty for EXISTS
WHERE s.saleprice = s1.saleprice
AND s.saledate = s1.saledate
AND s.id <> s1.id -- except for row itself
)
AND s.status IS DISTINCT FROM 'ACTIVE'; -- avoid empty updates. see below
```
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=postgres_11&fiddle=26c7eb96c3a22330a9c271d554c869fe)*
Old [sqlfiddle](http://sqlfiddle.com/#!17/6b5ef/1)
### Unique key to identify row
If you don't have a primary or unique key for the table (`id` in the example), you can substitute with the system column `ctid` for the purpose of this query (but not for some other purposes):
```
AND s1.ctid <> s.ctid
```
Every table should have a primary key. Add one if you didn't have one, yet. I suggest a `serial` or an `IDENTITY` column in Postgres 10+.
Related:
* [In-order sequence generation](https://stackoverflow.com/questions/17500013/in-order-sequence-generation/17503095#17503095)
* [Auto increment table column](https://stackoverflow.com/questions/9875223/auto-increment-table-column/9875517#9875517)
### How is this faster?
The subquery in the `EXISTS` anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes *way* more efficient.
### Exclude empty updates
For rows that already have `status = 'ACTIVE'` this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another `WHERE` condition like demonstrated above to avoid this and make it even faster:
If `status` is defined `NOT NULL`, you can simplify to:
```
AND status <> 'ACTIVE';
```
The data type of the column must support the `<>` operator. Some types like `json` don't. See:
* [How to query a json column for empty objects?](https://stackoverflow.com/questions/24292575/how-to-query-a-json-column-for-empty-objects/24296054#24296054)
### Subtle difference in NULL handling
This query (unlike the [currently accepted answer by Joel](https://stackoverflow.com/a/54430/939860)) does not treat NULL values as equal. The following two rows for `(saleprice, saledate)` would qualify as "distinct" (though looking identical to the human eye):
```
(123, NULL)
(123, NULL)
```
Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:
* [Create unique constraint with null columns](https://stackoverflow.com/questions/8289100/create-unique-constraint-with-null-columns/8289253#8289253)
OTOH, `GROUP BY`, `DISTINCT` or `DISTINCT ON ()` treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with [`IS NOT DISTINCT FROM`](https://www.postgresql.org/docs/current/functions-comparison.html#FUNCTIONS-COMPARISON-PRED-TABLE) instead of `=` for any or all comparisons to make NULL compare equal. More:
* [How to delete duplicate rows without unique identifier](https://stackoverflow.com/questions/26769454/how-to-delete-duplicate-rows-without-unique-identifier/26773018#26773018)
If all columns being compared are defined `NOT NULL`, there is no room for disagreement.
|
How do I (or can I) SELECT DISTINCT on multiple columns?
|
[
"",
"sql",
"postgresql",
"sql-update",
"duplicates",
"distinct",
""
] |
```
#include <iostream>
using namespace std;
int main()
{
double u = 0;
double w = -u;
cout << w << endl;
return 0;
}
```
Why does this great piece of code output `-0` and not `0`, as one would expect?
|
The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. [Wikipedia](http://en.wikipedia.org/wiki/IEEE_754) should be able to help explain this.
|
In IEEE floating point `0` and `-0` are both distinct values, from [here](http://steve.hollasch.net/cgindex/coding/ieeefloat.html) under "Special Values":
> Note that -0 and +0 are distinct
> values, though they both compare as
> equal.
|
cout prints "-0" instead of "0"
|
[
"",
"c++",
"floating-point",
""
] |
We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.
Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?
|
I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows:
1. Make sure default .NET assembly loading mechanism ("Fusion" engine) can't find either x86 or x64 version of the platform-specific assembly
2. Before the main application attempts loading the platform-specific assembly, install a custom assembly resolver in the current AppDomain
3. Now when the main application needs the platform-specific assembly, Fusion engine will give up (because of step 1) and call our custom resolver (because of step 2); in the custom resolver we determine current platform and use directory-based lookup to load appropriate DLL.
To demonstrate this technique, I am attaching a short, command-line based tutorial. I tested the resulting binaries on Windows XP x86 and then Vista SP1 x64 (by copying the binaries over, just like your deployment).
**Note 1**: "csc.exe" is a C-sharp compiler. This tutorial assumes it is in your path (my tests were using "C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe")
**Note 2**: I recommend you create a temporary folder for the tests and run command line (or powershell) whose current working directory is set to this location, e.g.
```
(cmd.exe)
C:
mkdir \TEMP\CrossPlatformTest
cd \TEMP\CrossPlatformTest
```
**Step 1**: The platform-specific assembly is represented by a simple C# class library:
```
// file 'library.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Library
{
public static class Worker
{
public static void Run()
{
System.Console.WriteLine("Worker is running");
System.Console.WriteLine("(Enter to continue)");
System.Console.ReadLine();
}
}
}
```
**Step 2**: We compile platform-specific assemblies using simple command-line commands:
```
(cmd.exe from Note 2)
mkdir platform\x86
csc /out:platform\x86\library.dll /target:library /platform:x86 library.cs
mkdir platform\amd64
csc /out:platform\amd64\library.dll /target:library /platform:x64 library.cs
```
**Step 3**: Main program is split into two parts. "Bootstrapper" contains main entry point for the executable and it registers a custom assembly resolver in current appdomain:
```
// file 'bootstrapper.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class Bootstrapper
{
public static void Main()
{
System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve;
App.Run();
}
private static System.Reflection.Assembly CustomResolve(
object sender,
System.ResolveEventArgs args)
{
if (args.Name.StartsWith("library"))
{
string fileName = System.IO.Path.GetFullPath(
"platform\\"
+ System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
+ "\\library.dll");
System.Console.WriteLine(fileName);
if (System.IO.File.Exists(fileName))
{
return System.Reflection.Assembly.LoadFile(fileName);
}
}
return null;
}
}
}
```
"Program" is the "real" implementation of the application (note that App.Run was invoked at the end of Bootstrapper.Main):
```
// file 'program.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class App
{
public static void Run()
{
Cross.Platform.Library.Worker.Run();
}
}
}
```
**Step 4**: Compile the main application on command line:
```
(cmd.exe from Note 2)
csc /reference:platform\x86\library.dll /out:program.exe program.cs bootstrapper.cs
```
**Step 5**: We're now finished. The structure of the directory we created should be as follows:
```
(C:\TEMP\CrossPlatformTest, root dir)
platform (dir)
amd64 (dir)
library.dll
x86 (dir)
library.dll
program.exe
*.cs (source files)
```
If you now run program.exe on a 32bit platform, platform\x86\library.dll will be loaded; if you run program.exe on a 64bit platform, platform\amd64\library.dll will be loaded. Note that I added Console.ReadLine() at the end of the Worker.Run method so that you can use task manager/process explorer to investigate loaded DLLs, or you can use Visual Studio/Windows Debugger to attach to the process to see the call stack etc.
When program.exe is run, our custom assembly resolver is attached to current appdomain. As soon as .NET starts loading the Program class, it sees a dependency on 'library' assembly, so it tries loading it. However, no such assembly is found (because we've hidden it in platform/\* subdirectories). Luckily, our custom resolver knows our trickery and based on the current platform it tries loading the assembly from appropriate platform/\* subdirectory.
|
My version, similar to @Milan, but with several important changes:
* Works for ALL DLLs that were not found
* Can be turned on and off
* `AppDomain.CurrentDomain.SetupInformation.ApplicationBase` is used instead of `Path.GetFullPath()` because the current directory might be different, e.g. in hosting scenarios, Excel might load your plugin but the current directory will not be set to your DLL.
* `Environment.Is64BitProcess` is used instead of `PROCESSOR_ARCHITECTURE`, as we should not depend on what the OS is, rather how this process was started - it could have been x86 process on a x64 OS. Before .NET 4, use `IntPtr.Size == 8` instead.
Call this code in a static constructor of some main class that is loaded before all else.
```
public static class MultiplatformDllLoader
{
private static bool _isEnabled;
public static bool Enable
{
get { return _isEnabled; }
set
{
lock (typeof (MultiplatformDllLoader))
{
if (_isEnabled != value)
{
if (value)
AppDomain.CurrentDomain.AssemblyResolve += Resolver;
else
AppDomain.CurrentDomain.AssemblyResolve -= Resolver;
_isEnabled = value;
}
}
}
}
/// Will attempt to load missing assembly from either x86 or x64 subdir
private static Assembly Resolver(object sender, ResolveEventArgs args)
{
string assemblyName = args.Name.Split(new[] {','}, 2)[0] + ".dll";
string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
assemblyName);
return File.Exists(archSpecificPath)
? Assembly.LoadFile(archSpecificPath)
: null;
}
}
```
|
Using Side-by-Side assemblies to load the x64 or x32 version of a DLL
|
[
"",
"c#",
".net",
"64-bit",
""
] |
Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?
For example, I've been using
```
javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
```
so far but wonder if there's something more sophisticated I could use or better practice.
|
Do you want something exactly like the Delicious bookmarklet (as in, something the user actively clicks on to submit the URL)? If so, you could probably just copy their code and replace the target URL:
```
javascript:(function(){
location.href='http://example.com/your-script.php?url='+
encodeURIComponent(window.location.href)+
'&title='+encodeURIComponent(document.title)
})()
```
You may need to change the query string names, etc., to match what your script expects.
If you want to track a user through your website automatically, this probably won't be possible. You'd need to request the URL with AJAX, but the web browser won't allow Javascript to make a request outside of the originating domain. Maybe it's possible with `iframe` trickery.
**Edit:** John beat me to it.
|
```
document.location = "http://url_submitting_to.com?query_string_param=" + window.location;
```
|
What's cleanest, shortest Javascript to submit a URL the user is at to another process via URL?
|
[
"",
"javascript",
"url",
"submission",
""
] |
To make a JavaScript class with a public method I'd do something like:
```
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
```
That way users of my class can:
```
var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
```
How do I create a private method that can be called by the `buy_food` and `use_restroom` methods but not externally by users of the class?
In other words, I want my method implementation to be able to do:
```
Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
```
But this shouldn't work:
```
var r = new Restaurant();
r.private_stuff();
```
How do I define `private_stuff` as a private method so both of these hold true?
I've read [Doug Crockford's writeup](http://javascript.crockford.com/private.html) a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
|
You can do it, but the downside is that it can't be part of the prototype:
```
function Restaurant() {
var myPrivateVar;
var private_stuff = function() { // Only visible inside Restaurant()
myPrivateVar = "I can set this here!";
}
this.use_restroom = function() { // use_restroom is visible to all
private_stuff();
}
this.buy_food = function() { // buy_food is visible to all
private_stuff();
}
}
```
|
# Using self invoking function and call
JavaScript uses [prototypes](http://en.wikipedia.org/wiki/Prototype-based_programming) and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.
Wikipedia quote:
> Unlike many object-oriented languages, there is no distinction between
> a function definition and a method definition. Rather, the distinction
> occurs during function calling; when a function is called as a method
> of an object, the function's local this keyword is bound to that
> object for that invocation.
Solution using a [self invoking function](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) and the [call function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) to call the private "method" :
```
var MyObject = (function () {
// Constructor
function MyObject(foo) {
this._foo = foo;
}
function privateFun(prefix) {
return prefix + this._foo;
}
MyObject.prototype.publicFun = function () {
return privateFun.call(this, ">>");
}
return MyObject;
}());
```
```
var myObject = new MyObject("bar");
myObject.publicFun(); // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined
```
The [call function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) allows us to call the private function with the appropriate context (`this`).
# Simpler with Node.js
If you are using [Node.js](http://nodejs.org/), you don't need the [IIFE](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) because you can take advantage of the [module loading system](http://nodejs.org/api/modules.html):
```
function MyObject(foo) {
this._foo = foo;
}
function privateFun(prefix) {
return prefix + this._foo;
}
MyObject.prototype.publicFun = function () {
return privateFun.call(this, ">>");
}
module.exports= MyObject;
```
Load the file:
```
var MyObject = require("./MyObject");
var myObject = new MyObject("bar");
myObject.publicFun(); // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined
```
# (new!) Native private methods in future JavaScript versions
TC39 [private methods and getter/setters for JavaScript classes](https://github.com/tc39/proposal-private-methods) proposal is stage 3. That means any time soon, JavaScript will implement private methods natively!
Note that [JavaScript private class fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields) already exists in modern JavaScript versions.
Here is an example of how it is used:
```
class MyObject {
// Private field
#foo;
constructor(foo) {
this.#foo = foo;
}
#privateFun(prefix) {
return prefix + this.#foo;
}
publicFun() {
return this.#privateFun(">>");
}
}
```
You may need a [JavaScript transpiler/compiler](https://babeljs.io) to run this code on old JavaScript engines.
PS: If you wonder why the `#` prefix, [read this](https://github.com/tc39/proposal-private-fields/issues/14).
# (deprecated) ES7 with the Bind Operator
Warning: The bind operator TC39 proposition is near dead <https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822>
The bind operator `::` is an ECMAScript [proposal](https://github.com/zenparsing/es-function-bind) and is [implemented in Babel](https://babeljs.io/blog/2015/05/14/function-bind) ([stage 0](https://babeljs.io/docs/plugins/preset-stage-0/)).
```
export default class MyObject {
constructor (foo) {
this._foo = foo;
}
publicFun () {
return this::privateFun(">>");
}
}
function privateFun (prefix) {
return prefix + this._foo;
}
```
|
JavaScript private methods
|
[
"",
"javascript",
"oop",
"private-methods",
""
] |
Does anyone know of a good tool to generate the WSDL for a service contract written in C# (i.e. set of methods that are tagged as "[OperationContract]" using WCF)? All the tools I've found work the other way around: create code stubs from a WSDL. I don't want to have to hand-jam a WSDL file. I've found tools for php and J2EE, but not C#. Thanks!
|
Easiest thing to do is host the service with a base address setup, and then just hit it from a browser with "?wsdl" appended to the end.
Here's an example of a service configuration with a base address specified. Note this goes in the `<configuration><services>` element in your config:
```
<service name="MyServiceName" behaviorConfiguration="MyServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9000/MyService"/>
</baseAddresses>
</host>
<endpoint address="net.tcp://localhost:9001/MyService"
binding="netTcpBinding"
contract="IMyService"
bindingConfiguration="MyServiceBinding"/>
</service>
```
Once you get it hosted, just go to `http://localhost:9000/MyService?wsdl` to see the WSDL definition.
|
[svcutil](http://msdn.microsoft.com/en-us/library/aa702581.aspx) or just host it quickly and hit the MEX point :)
|
WSDL Generator for C#
|
[
"",
"c#",
"wcf",
"wsdl",
""
] |
When you call the `object.__repr__()` method in Python you get something like this back:
> ```
> <__main__.Test object at 0x2aba1c0cf890>
> ```
Is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out?
|
The [Python manual](https://docs.python.org/2/library/functions.html#id) has this to say about `id()`:
> Return the "identity'' of an object.
> This is an integer (or long integer)
> which is guaranteed to be unique and
> constant for this object during its
> lifetime. Two objects with
> non-overlapping lifetimes may have the
> same id() value. (Implementation note:
> this is the address of the object.)
So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.
Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.
|
You could reimplement the default repr this way:
```
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
```
|
Accessing Object Memory Address
|
[
"",
"python",
"object",
"memory-address",
"repr",
""
] |
I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError:
```
>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> f.write('foo')
>>> shutil.copy(f.name, 'bar.txt')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
shutil.copy(f.name, 'bar.txt')
File "C:\Python25\lib\shutil.py", line 80, in copy
copyfile(src, dst)
File "C:\Python25\lib\shutil.py", line 46, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'
>>>
```
Is this not intended when using the 'tempfile' library? Is there a better way to do this? (Maybe I am overlooking something very trivial)
|
The file you create with `TemporaryFile` or `NamedTemporaryFile` is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use `mkstemp` instead (see the docs for [tempfile](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp)).
```
>>> import tempfile, shutil, os
>>> fd, path = tempfile.mkstemp()
>>> os.write(fd, 'foo')
>>> os.close(fd)
>>> shutil.copy(path, 'bar.txt')
>>> os.remove(path)
```
|
hop is right, and dF. is incorrect on why the error occurs.
Since you haven't called `f.close()` yet, the file is **not** removed.
The [doc](http://docs.python.org/library/tempfile.html#tempfile.NamedTemporaryFile) for `NamedTemporaryFile` says:
> Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
And for `TemporaryFile`:
> Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.
Therefore, to persist a temporary file (on Windows), you can do the following:
```
import tempfile, shutil
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
f.write('foo')
file_name = f.name
f.close()
shutil.copy(file_name, 'bar.txt')
os.remove(file_name)
```
The solution Hans Sjunnesson provided is also off, because `copyfileobj` only copies from file-like object to file-like object, not file name:
> shutil.copyfileobj(fsrc, fdst[, length])
>
> > Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.
|
How do I persist to disk a temporary file using Python?
|
[
"",
"python",
"temporary-files",
""
] |
**I want to read the contents of a URL but don't want to "hang" if the URL is unresponsive. I've created a BufferedReader using the URL...**
```
URL theURL = new URL(url);
URLConnection urlConn = theURL.openConnection();
urlConn.setDoOutput(true);
BufferedReader urlReader = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
```
**...and then begun the loop to read the contents...**
```
do
{
buf = urlReader.readLine();
if (buf != null)
{
resultBuffer.append(buf);
resultBuffer.append("\n");
}
}
while (buf != null);
```
**...but if the read hangs then the application hangs.**
**Is there a way, without grinding the code down to the socket level, to "time out" the read if necessary?**
|
I think URLConnection.setReadTimeout is what you are looking for.
|
If you have java 1.4:
I assume the connection timeout (`URLConnection.setConnectTimeout(int timeout)` ) is of no use because you are doing some kind of streaming.
---**Do not kill the thread**--- It may cause unknown problems, open descriptors, etc.
Spawn a java.util.TimerTask where you will check if you have finished the process, otherwise, close the BufferedReader and the OutputStream of the URLConnection
Insert a boolean flag `isFinished` and set it to true at the end of your loop and to false before the loop
```
TimerTask ft = new TimerTask(){
public void run(){
if (!isFinished){
urlConn.getInputStream().close();
urlConn.getOutputStream().close();
}
}
};
(new Timer()).schedule(ft, timeout);
```
This will probably cause an ioexception, so you have to catch it. The exception is not a bad thing in itself.
I'm omitting some declarations (i.e. finals) so the anonymous class can access your variables. If not, then create a POJO that maintains a reference and pass that to the timertask
|
How can I set a timeout against a BufferedReader based upon a URLConnection in Java?
|
[
"",
"java",
"url",
"sockets",
""
] |
What things have to be done before I can honestly tell myself my web application is accessible by anyone? Or even better, convince Joe Clark. I don't have any video or audio to worry about, so I know I won't need transcripts. What else do I have to check?
|
Your question is very vague, but in short, you need to ensure that your site meets one of the three levels (A, AA, or AAA) of the [Web Content Accessibility Guidelines](http://www.w3.org/TR/WCAG10/).
FWIW, in my experience, if you are providing anything other than a purely static HTML site, aim for AA. Trying to follow the WCAG guidelines stringently to triple-A standard for a dynamic website is the road to hair loss IMO. This may change with WCAG 2.0.
Good luck!
**EDIT:** @Blowdart suggests running your site through online checkers. This is fine so long as you realise that many of the WCAG guidelines (especially towards the higher end) are so arbitrary, they can only be validated with a human eye.
Do not trust the output of these online checkers and blindly stick a AAA badge on your site. If you are called on it, you may be in trouble.
+1 Blowdart for suggesting HTML and CSS validation, and Chris Pederick's add-on is *great*!
|
You should also check out the WAI-ARIA stuff:
* <http://www.w3.org/WAI/intro/aria>
* <http://alistapart.com/articles/waiaria>
* <http://juicystudio.com/article/wai-aria-live-regions.php>
And, for a perspective on the challenges actually faced by users with various disabilities when they try to use the web, have a look at some of the presentations and videos from the Scripting Enabled conference in London on Friday: <http://scriptingenabled.org/> (I don't think all of them are uploaded yet)
|
Make Web Application Accessible
|
[
"",
"javascript",
"html",
"usability",
"accessibility",
""
] |
What options are there for building automated tests for GUIs written in Java Swing?
I'd like to test some GUIs which have been written using the [NetBeans Swing GUI Builder](http://www.netbeans.org/features/java/swing.html), so something that works without requiring special tampering of the code under test would be ideal.
|
Recently I came across FEST which seemed promising, except that the developer [announced in 2012 that development would not continue](https://groups.google.com/forum/#!msg/easytesting/bAt1nWx55FM/e3DF0bxGUf8J).
[AssertJ](https://joel-costigliola.github.io/assertj/) is a fork of FEST that is working very well for me. It is actively maintained (at time of writing), supports Java 8, has assertions for a few popular libraries such as Guava and Joda Time, and is very well documented. It is also free and open.
|
I'm currently using [FEST](http://code.google.com/p/fest/). It works with JUnit and will also take screenshots of failed tests.
It has default component hunting methods which look for the name of the component being tested (which need to be set manually), but you can also generate the testers for a given component by passing it the component.
|
Automated tests for Java Swing GUIs
|
[
"",
"java",
"swing",
"testing",
"automated-tests",
""
] |
I need to display many pages of news in a site. Should I do the pagination in the database query using `LIMIT` or with the PHP script after getting all the results?
|
Use limit in SQL! Every time!
Otherwise you're throwing around considerably more data than you need to, which makes your scripts unnecessarily slow, and will lead to scalability problems as the amount of data in your tables increases.
Limit is your friend!
|
Use limit - you don't want to transfer masses of data from the database to the scripting engine if you can avoid it.
|
What is the best way to paginate results in php
|
[
"",
"php",
"pagination",
""
] |
Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:
```
<test>
<route>citytest/:city</route>
<defaults>
<controller>result</controller>
<action>test</action>
</defaults>
<reqs>
<city>.+</city>
</reqs>
</test>
```
and three Urls:
* mysite.local/citytest/Berlin
* mysite.local/citytest/Hamburg
* mysite.local/citytest/M%FCnchen
the last Url does not match and thus the correct controller is not called. Anybody got a clue why?
Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ )
Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great.
Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170):
```
$regex = $this->_regexDelimiter . '^' .
$part['regex'] . '$' .
$this->_regexDelimiter . 'iu';
```
If I change that to
```
$this->_regexDelimiter . 'i';
```
it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading.
|
The problem is the following:
> Using the /u pattern modifier prevents
> words from being mangled but instead
> PCRE skips strings of characters with
> code values greater than 127.
> Therefore, \w will not match a
> multibyte (non-lower ascii) word at
> all (but also won’t return portions of
> it). From the pcrepattern man page;
>
> In UTF-8 mode, characters with values
> greater than 128 never match \d, \s,
> or \w, and always match \D, \S, and
> \W. This is true even when Unicode
> character property support is
> available.
From [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8#w_w_b_b_meta_characters).
Therefore it's actually irrelevant if your URL is ISO-8859-1 encoded (mysite.local/citytest/M%FCnchen) or UTF-8 encoded (mysite.local/citytest/M%C3%BCnchen), the default regex won't match.
I also made experiments with umlauts in URLs in Zend Framework and came to the conclusion that you wouldn't really want umlauts in your URLs. The problem is, that you cannot rely on the encoding used by the browser for the URL. Firefox (prior to 3.0) for example does not UTF-8 encode URLs entered into the address textbox (if not specified in about:config) and IE does have a checkbox within its options to choose between regular and UTF-8 encoding for its URLs. But if you click on links within a page both browsers use the URL in the given encoding (UTF-8 on an UTF-8 page). Therefore you cannot be sure in which encoding the URLs are sent to your application - and detecting the encoding used is not that trivial to do.
Perhaps it's better to use transliterated parameters in your URLs (e.g. change Ä to Ae and so on). There is a really simple way to this (I don't know if this works with every language but I'm using it with German strings and it works quite well):
```
function createUrlFriendlyName($name) // $name must be an UTF-8 encoded string
{
$name=mb_convert_encoding(trim($name), 'HTML-ENTITIES', 'UTF-8');
$name=preg_replace(
array('/ß/', '/&(..)lig;/', '/&([aouAOU])uml;/', '/&(.)[^;]*;/', '/\W/'),
array('ss', '$1', '$1e', '$1', '-'),
$name);
$name=preg_replace('/-{2,}/', '-', $name);
return trim($name, '-');
}
```
|
Please its working perfect for me
```
/^[\p{L}-. ]*$/u
```
* `^` Start of the string
* `[ ... ]*` Zero or more of the following:
* `\p{L}` Unicode letter characters
* `–` dashes
* `.` periods
* spaces
* `$` End of the string
* `/u` Enable Unicode mode in PHP
EXAMPLE:
```
$str= ‘Füße’;
if (!preg_match(“/^[\p{L}-. ]*$/u”, $str))
{
echo ‘error’;
}
else
{
echo “success”;
}
```
|
Route-problem regarding Url-encoded Umlauts (using the Zend-framework)
|
[
"",
"php",
"zend-framework",
""
] |
Could you recommend me a way to place a coundown timer on ASP.NET page?
Now I use this code:
**Default.aspx**
```
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server">60</asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
ontick="Timer1_Tick">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
```
**Default.aspx.cs**
```
protected void Timer1_Tick(object sender, EventArgs e)
{
int seconds = int.Parse(Label1.Text);
if (seconds > 0)
Label1.Text = (seconds - 1).ToString();
else
Timer1.Enabled = false;
}
```
But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET?
|
OK, finally I ended with
```
<span id="timerLabel" runat="server"></span>
<script type="text/javascript">
function countdown()
{
seconds = document.getElementById("timerLabel").innerHTML;
if (seconds > 0)
{
document.getElementById("timerLabel").innerHTML = seconds - 1;
setTimeout("countdown()", 1000);
}
}
setTimeout("countdown()", 1000);
</script>
```
Really simple. Like old good plain HTML with JavaScript.
|
```
time1 = (DateTime)ViewState["time"] - DateTime.Now;
if (time1.TotalSeconds <= 0)
{
Label1.Text = Label2.Text = "TimeOut!";
}
else
{
if (time1.TotalMinutes > 59)
{
Label1.Text = Label2.Text = string.Format("{0}:{1:D2}:{2:D2}",
time1.Hours,
time1.Minutes,
time1.Seconds);
}
else
{
Label1.Text = Label2.Text = string.Format("{0:D2}:{1:D2}",
time1.Minutes,
time1.Seconds);
}
}
```
|
Countdown timer on ASP.NET page
|
[
"",
"asp.net",
"javascript",
"asp.net-ajax",
""
] |
I'm working with PostSharp to intercept method calls to objects I don't own, but my aspect code doesn't appear to be getting called. The documentation seems pretty lax in the Silverlight area, so I'd appreciate any help you guys can offer :)
I have an attribute that looks like:
```
public class LogAttribute : OnMethodInvocationAspect
{
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
// Logging code goes here...
}
}
```
And an entry in my AssemblyInfo that looks like:
```
[assembly: Log(AttributeTargetAssemblies = "System.Windows", AttributeTargetTypes = "System.Windows.Controls.*")]
```
So, my question to you is... what am I missing? Method calls under matching attribute targets don't appear to function.
|
**This is not possible with the present version of PostSharp.**
PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen:
* The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point.
* After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime.
The newest version, 1.5 CTP 3, [removes the first of these two limitations](http://www.postsharp.org/blog/announcing-postsharp-1.5-ctp-3), but it is the second that's really the problem. This is, however, [a heavily requested feature](http://www.postsharp.org/blog/using-postsharp-at-runtime), so keep your eyes peeled:
> Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. **One of the cool things it would enable is to apply aspects on third-party assemblies.**
>
> If you ask whether it is possible, the short answer is yes! **Unfortunately, the long answer is more complex.**
### Runtime/third-party aspect gotchas
The author also proceeds to outline some of the problems that happen if you allow modification at runtime:
> So now, what are the gotchas?
>
> * **Plugging the bootstrapper.** If your code is hosted (for instance in
> ASP.NET or in a COM server), you
> cannot plug the bootstrapper. So any
> runtime weaving technology is bound to
> the limitation that you should host
> the application yourself.
> * **Be Before the CLR.** If the CLR finds the untransformed assembly by its own,
> it will not ask for the transformed
> one. So you may need to create a new
> application domain for the transformed
> application, and put transformed
> assemblies in its binary path. It's
> maybe not a big problem.
> * **Strong names.** Ough. If you modify an assembly at runtime, you will have to
> remove its strong name. Will it work?
> Yes, mostly. Of course, you have to
> remove the strong names from all
> references to this assembly. That's
> not a problem; PostSharp supports it
> out-of-the-box. But there is something
> PostSharp cannot help with: if there
> are some strongly named references in
> strings or files (for instance in
> app.config), we can hardly find them
> and transform them. So here we have a
> real limitation: there cannot be
> "loose references" to strongly named
> assemblies: we are only able to
> transform real references.
> * **LoadFrom.** If any assembly uses Assembly.LoadFrom, Assembly.LoadFile
> or Assembly.LoadBytes, our
> bootstrapper is skipped.
|
I believe if you change AttributeTargetAssemblies to "PresentationFramework", it might work. (Don't have PostSharp down that well yet).
The Assembly for WPF is PresentationFramework.dll. The AttributeTargetAssemblies needs the dll that it should target.
|
Using PostSharp to intercept calls to Silverlight objects?
|
[
"",
"c#",
"postsharp",
""
] |
Never used a cache like this before. The problem is that I want to load 500,000 + records out of a database and do some selecting/filtering wicked fast.
I'm thinking about using a cache, and preliminarily found [EHCache](http://ehcache.org/) and [OSCache](https://java.net/projects/oscache/), any opinions?
|
They're both pretty solid projects. If you have pretty basic caching needs, either one of them will probably work as well as the other.
You may also wish to consider doing the filtering in a database query if it's feasible. Often, using a tuned query that returns a smaller result set will give you better performance than loading 500,000 rows into memory and then filtering them.
|
Judging by their [releases page](http://www.opensymphony.com/oscache/download.action), OSCache has not been actively maintained since 2007. This is not a good thing. EhCache, on the other hand, is under constant development. For that reason alone, I would choose EhCache.
Edit Nov 2013: OSCache, like the rest of OpenSymphony, is dead.
|
OSCache vs. EHCache
|
[
"",
"java",
"caching",
"ehcache",
"oscache",
""
] |
I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.
I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).
|
Treat the following as pseudo-code..
```
try:
from hashlib import sha as hasher
except ImportError:
# You could probably exclude the try/except bit,
# but older Python distros dont have hashlib.
try:
import sha as hasher
except ImportError:
import md5 as hasher
def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
def load_auth_file(path):
"""Loads a comma-seperated file.
Important: make sure the username
doesn't contain any commas!
"""
# Open the file, or return an empty auth list.
try:
f = open(path)
except IOError:
print "Warning: auth file not found"
return {}
ret = {}
for line in f.readlines():
split_line = line.split(",")
if len(split_line) > 2:
print "Warning: Malformed line:"
print split_line
continue # skip it..
else:
username, password = split_line
ret[username] = password
#end if
#end for
return ret
def main():
auth_file = "/home/blah/.myauth.txt"
u = raw_input("Username:")
p = raw_input("Password:") # getpass is probably better..
if auth_file.has_key(u.strip()):
if auth_file[u] == hash_password(p):
# The hash matches the stored one
print "Welcome, sir!"
```
Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.
Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the `~/.myauth.txt` file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful.
|
dbr said:
> ```
> def hash_password(password):
> """Returns the hashed version of a string
> """
> return hasher.new( str(password) ).hexdigest()
> ```
This is a really insecure way to hash passwords. You *don't* want to do this. If you want to know why read the [Bycrypt Paper](http://www.openbsd.org/papers/bcrypt-paper.pdf "\"B-Crypt Paper") by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out [this interview](http://www.securityfocus.com/columnists/388) with the author of Jack the Ripper (the popular unix password cracker).
Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times.
If that didn't make sense here is the code:
```
#note I am using the Python Cryptography Toolkit
from Crypto.Hash import SHA256
HASH_REPS = 50000
def __saltedhash(string, salt):
sha256 = SHA256.new()
sha256.update(string)
sha256.update(salt)
for x in xrange(HASH_REPS):
sha256.update(sha256.digest())
if x % 10: sha256.update(salt)
return sha256
def saltedhash_bin(string, salt):
"""returns the hash in binary format"""
return __saltedhash(string, salt).digest()
def saltedhash_hex(string, salt):
"""returns the hash in hex format"""
return __saltedhash(string, salt).hexdigest()
```
For deploying a system like this the key thing to consider is the HASH\_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file.
Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there.
hope this helps,
Tim
|
Python Authentication API
|
[
"",
"python",
"authentication",
"desktop",
""
] |
WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a [console documentation for Firebug](http://getfirebug.com/wiki/index.php/Console_API), but where can I find the console documentation for Safari/WebKit?
|
Supported methods were originally:
* `console.log()`
* `console.error()`
* `console.warn()`
* `console.info()`
Newer versions of WebKit also add the following methods making the WebKit console API almost identical to [Firebug's console API](http://getfirebug.com/wiki/index.php/Console_API):
* `console.count()`
* `console.debug()`
* `console.profileEnd()`
* `console.trace()`
* `console.dir()`
* `console.dirxml()`
* `console.assert()`
* `console.time()`
* `console.profile()`
* `console.timeEnd()`
* `console.group()`
* `console.groupEnd()`
(New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari)
|
The console API is documented by Apple in the [Console](https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html) section of the Safari Developer Guide.
|
Where is the console API for WebKit/Safari?
|
[
"",
"javascript",
"console",
"safari",
""
] |
I'm developing a restful Web service that runs as a servlet (using blocking IO) in Jetty. Figuring out the optimal setting for max threads seems hard.
Is there a researched formula for deciding the max number of threads from some easily measurable characteristics of the rest of the setup?
|
Very simple and primitive one:
max\_number\_of\_threads = number\_of\_CPUs \* C
Where C depends on other factors of your application :-)
Ask yourself following questions:
* Will your application be CPU intensive (lower C) or spend most time waiting for a third systems (higher C)?
* Do you need quicker response times (lower C) or be able to serve many multiple users at once even if each request takes longer (higher C).
Usually I set C rather low, e.g. 2 - 10.
|
No there is not. Keep you number of threads limited and under control so you not exceed system resources, Java's limit is usually around 100-200 live threads.
Good way to do it is by using Executors from **java.util.concurrent**.
|
How to choose the max thread count for an HTTP servlet container?
|
[
"",
"java",
"http",
"optimization",
"servlets",
"concurrency",
""
] |
So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.
The code I'm working on needs to populate, let's say a `List<Foo>` from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:
```
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 1);
// ....
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 2);
// ....
Expect.Call(reader.Read()).Return(false);
```
Which is rather tedious and rather easily broken, too.
How should I be approaching this issue so that the result won't be a huge mess of brittle tests?
Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.
Edit: I'm also currently limited to C# 2.
|
To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests.
Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.
|
I thought about posting some code and then I remembered about JP Boodhoo's Nothin But .NET course. He has a [sample project](http://code.google.com/p/jpboodhoo/) that he is sharing that was created during one of his classes. The project is hosted on [Google Code](http://code.google.com/) and it is a nice resource. I am sure it has some nice tips for you to use and give you ideas on how to refactor the mapping. The whole project was built with TDD.
|
How should I test a method that populates a list from a DataReader?
|
[
"",
"c#",
"unit-testing",
"tdd",
"mocking",
""
] |
I have defined an interface in C++, i.e. a class containing only pure virtual functions.
I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:
```
class ITest{
public:
virtual void doSomething() = 0;
protected:
~ITest(){}
};
void someFunction(ITest * test){
test->doSomething(); // ok
// deleting object is not allowed
// delete test;
}
```
The GNU compiler gives me a warning saying:
> class 'ITest' has virtual functions but non-virtual destructor
Once the destructor is protected, what is the difference in having it virtual or non-virtual?
Do you think this warning can be safely ignored or silenced?
|
It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case.
See [here](http://www.gotw.ca/publications/mill18.htm) for an excellent article by Herb Sutter on the subject. From the article:
Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.
|
Some of the comments on this answer relate to an earlier answer I gave, which was wrong.
A protected destructor means that it can only be called from a base class, not through delete. That means that an ITest\* cannot be directly deleted, only a derived class can. The derived class may well want a virtual destructor. There is nothing wrong with your code at all.
However, since you cannot locally disable a warning in GCC, and you already have a vtable, you could consider just making the destructor virtual anyway. It will cost you 4 bytes for the program (not per class instance), maximum. Since you might have given your derived class a virtual dtor, you may find that it costs you nothing.
|
GNU compiler warning "class has virtual functions but non-virtual destructor"
|
[
"",
"c++",
"gcc",
""
] |
I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.
|
This is what I could find, maybe it solves your problem:
1. SP to get the current job activiity.
> ```
> exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here)
> ```
You can execute this SP and place the result in a temp table and get the required result from there.
Otherwise have a look at these tables:
* msdb.dbo.sysjobactivity
* msdb.dbo.sysjobhistory
Run the following to see the association between these tables.
> exec sp\_helptext sp\_help\_jobactivity
|
--Copy in Query analizer and format it properly so you can understand it easyly
--To execute your task(Job) using Query
exec msdb.dbo.sp\_start\_job @job\_name ='Job Name',@server\_name = server name
-- After executing query to check weateher it finished or not
Declare @JobId as varchar(36)
Select @JobId = job\_id from sysjobs where name = 'Your Job Name'
Declare @JobStatus as int set @JobStatus = -1
While @JobStatus <= -1
Begin
--Provide TimeDelay according your Job
select @JobStatus = isnull(run\_status ,-1)
from sysjobactivity JA,sysjobhistory JH
where JA.job\_history\_id = JH.instance\_id and JA.job\_id = @JobId
End
select @JobStatus
null = Running
1 = Fininshed successfully
0 = Finished with error
--Once your Job will fininsh you'll get result
|
SQL Job Status
|
[
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I recently started using Eclipse at work for my Java servlet projects. I've been using jEdit for years, which is a uber-powerful text editor. It has syntax highlighting, but it doesn't have any language-specific features like code completion and intelligent refactoring. I'm finding that's hindering my productivity. I *desperately* want to like Eclipse. I really do. But I keep running into problem after problem.
1. Now that Eclipse can use an ant script to build, instead of just creating its own build environment from an ant script then ignoring any changes to it, I found some online guides and set it up. It doesn't seem ready for prime time, though. My ant script builds fine from the command line, but I get all these build errors because I need to tell Eclipse all this stuff the build.xml already has in it, like the CLASSPATH, and where external jars are.
2. When I leave Eclipse running for too long, or sometimes after my laptop wakes up from hibernate, the UI starts breaking. For instance, the tabs on the editor pane disappear, so I can only edit one file at a time, and it doesn't say which one it is.
3. We have faced several instances where classes weren't rebuilt that should have been, leading to inaccurate line numbers in debugging walkthroughs and other unpredictable behavior (this isn't just me; the two other developers trying it out with me are seeing the same thing).
4. I find it a huge hassle that the workspace is in a different place than my source code. I have other files I need to edit (xml files, etc), and for each directory I want to edit files in, I need to set up a special entry, and it doesn't even default to where my source code is when setting that up.
Do others face these same issues?
Are there better alternatives?
|
Try [NetBeans](http://www.netbeans.org/)
> A free, open-source Integrated
> Development Environment for software
> developers. You get all the tools you
> need to create professional desktop,
> enterprise, web, and mobile
> applications with the Java language,
> C/C++, and Ruby.
|
Eclipse works best if you leave the project folder structure to its management. We are working with 15 developers on a project of several thousand classes and even more XML and .properties files.
I agree there are problems with ANT integration, so for production and nightly builds I recommend an external build system based on ANT scripts started from a shell.
However while working in Eclipse make sure you have the automatic build feature on (it should be by default, but checking does not hurt). This should free you from any concerns regarding what to build and when. Sometimes (very rarely for me) there are problems when I have to switch of the automatic build, clean all projects and trigger a manual build via the menu. From time to time I have to trigger the build multiple times (not the cleaning!), but once everything has been built again, turning the auto-build on works great again.
As for long running instances: My machine keeps logged in basically all the time (day and night) and there are at least two Eclipse instances running at all times. I have not seen any problems with these sessions, even when they remain open for literally weeks.
Most of the problems I have seen in the 5 years I have been using Eclipse originated from people installing too many plugins - the only stuff I have added is Checkstyle, the "implementors plugin" and some proprietary stuff for the application framework we are using.
Maybe you can try using a rather clean Eclipse installation the "usual way" for a while (i. e. with the sources imported to the workspace folder).
Regarding NetBeans: I use it from time to time as well, but I think it is a matter of taste and I like Eclipse better. This may be different for you.
|
Is it me, or is Eclipse horribly unpredictable?
|
[
"",
"java",
"eclipse",
"ide",
"editor",
""
] |
Looking for suggestions on file system management tools. We have several terabytes of images, pdfs, excel sheets, etc.
We're looking at some sort of software that will help us to manage, archive, etc the images.
We don't store all the files information in a database but some are and we were hoping to maybe find an app that could help us integrate the archive process into the database.
Thank you!
|
I have always seen these guys in the trade magazines. <http://www.dtsearch.com/> I believe they've been around long before even Google. Not sure if this is what you're looking for.
|
If some of the data is saved on disks perhaps a search application is more appropriate. You can use google, microsoft search or similar program.
|
File System Management Tools
|
[
"",
"sql",
"database",
"file",
"system",
""
] |
I'm developing a Mac App in Java that logs into any one of our client's databases. My users want to have several copies of this program running so they can log into a couple clients at the same time, rather than logging out and logging back in.
How can I allow a user to open several copies of my App at once?
I'm using Eclipse to develop, and Jarbundler to make the app.
Edit: More Importantly, is there a way to do so in the code base, rather than have my user do something funky on their system? I'd rather just give them a 'Open New Window' menu item, then have them typing things into the Terminal.
|
You've probably already gotten enough code that you don't want to hear this, but you should really not be starting up two instances of the same application. There's a reason that you're finding it so difficult and that's because Apple doesn't want you to do it.
The OSX way of doing this is to use the **Cocoa Document-based Application** template in XCode. [Apple Documentation: choosing a project.](http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/030-Creating_Projects/chapter_4_section_2.htm)
This is something users are very accustomed to, and it works just fine. FTP programs, IRC clients, and many other types already use different "document" windows to point to different servers or channels. There's nothing inherently different about pointing to different databases.
Depending on how much code you've written, and how your application is designed, this may be pretty much impossible to implement without starting over. Developers who are encountering this problem during design phase, however, should definitely take Apple's advice.
|
From the Terminal (or in a script wrapper):
```
/Applications/TextEdit.app/Contents/MacOS/TextEdit &
```
Something like that should work for you.
To do this in Java:
```
String[] cmd = { "/bin/sh", "-c", "[shell commmand goes here]" };
Process p = Runtime.getRuntime().exec (cmd);
```
|
Opening more than one of the same Mac Application at once
|
[
"",
"java",
"eclipse",
"macos",
""
] |
I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.
With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.
Any thoughts on how best to approach this issue?
|
Automatically log your 500s, that way:
* You know when they occur.
* You don't need to rely on users sending you stacktraces.
Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to.
Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks.
*Edit* (added code sample to capture traceback):
You can get the exception information from the sys.exc\_info call. While formatting the traceback for display comes from the traceback module:
```
import traceback
import sys
try:
raise Exception("Message")
except:
type, value, tb = sys.exc_info()
print >> sys.stderr, type.__name__, ":", value
print >> sys.stderr, '\n'.join(traceback.format_tb(tb))
```
Prints:
```
Exception : Message
File "exception.py", line 5, in <module>
raise Exception("Message")
```
|
As @zacherates says, you really don't want to display a stacktrace to your users. The easiest approach to this problem is what Django does by default if you have yourself and your developers listed in the ADMINS setting with email addresses; it sends an email to everyone in that list with the full stack trace (and more) everytime there is a 500 error with DEBUG = False.
|
How do I include a stacktrace in my Django 500.html page?
|
[
"",
"python",
"django",
"templates",
"stack-trace",
""
] |
So, I've been reading through and it appears that the Boost libraries get used a lot in practice (not at my shop, though). Why is this? and what makes it so wonderful?
|
[Boost](http://www.boost.org/) is used so extensively because:
* It is open-source and peer-reviewed.
* It provides a [wide range](http://www.boost.org/doc/libs) of platform agnostic functionality that STL missed.
* It is a complement to STL rather than a replacement.
* Many of Boost developers are on the C++ standard committee. In fact, many parts of Boost is considered to be included in the next C++ standard library.
* It is documented nicely.
* Its [license](http://en.wikipedia.org/wiki/Boost_Software_License) allows inclusion in open-source and closed-source projects.
* Its features are not *usually* dependent on each other so you can link only the parts you require. [[Luc Hermitte](https://stackoverflow.com/users/15934/luc-hermitte)'s comment]
|
From the home page:
> "...one of the most highly regarded and expertly designed C++ library projects in the world."
> — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards
>
> "Item 55: Familiarize yourself with Boost."
> — Scott Meyers, Effective C++, 3rd Ed.
>
> "The obvious solution for most programmers is to use a library that provides an elegant and efficient platform independent to needed services. Examples are BOOST..."
> — Bjarne Stroustrup, Abstraction, libraries, and efficiency in C++
So, it's a range of widely used and accepted libraries, but why would you need it?
If you need:
* regex
* function binding
* lambda functions
* unit tests
* smart pointers
* noncopyable, optional
* serialization
* generic dates
* portable filesystem
* circular buffers
* config utils
* generic image library
* TR1
* threads
* uBLAS
and [more](http://www.boost.org/doc/libs/1_36_0) when you code in C++, have a look at [Boost](http://www.boost.org/).
|
What are the advantages of using the C++ Boost libraries?
|
[
"",
"c++",
"boost",
""
] |
I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?
|
1. Add to the docs. it is downright crappy
2. Help out other users on the dev and user mailing lists.
3. TEST PYTHON. bugs in programming languages are real bad. And I have seen someone discover atleast 1 bug in python
4. Frequent the #python channel on irc.freenode.net
|
Build something cool in Python and share it with others. Small values of cool are still cool. Not everyone gets to write epic, world-changing software.
Every problem solved well using Python is a way of showing how cool Python is.
|
Contributing to Python
|
[
"",
"python",
""
] |
I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:
```
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
```
How do I convert the above to something like this:
```
<p>
Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
```
Is this possible with jQuery?
**Edit**: As [Sebastian](https://stackoverflow.com/users/9535/sebastian-hoitz) [pointed out](https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450), this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.
|
~~Try [highlight: JavaScript text highlighting jQuery plugin](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html).~~
**Warning: The source code available on this page contains a cryptocurrency mining script, either use the code below or remove the mining script from the script downloaded from the website.**
```
/*
highlight v4
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>
*/
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
```
Also try the ["updated" version of the original script](http://bartaz.github.com/sandbox.js/jquery.highlight.html).
```
/*
* jQuery Highlight plugin
*
* Based on highlight v3 by Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
*
* Code a little bit refactored and cleaned (in my humble opinion).
* Most important changes:
* - has an option to highlight only entire words (wordsOnly - false by default),
* - has an option to be case sensitive (caseSensitive - false by default)
* - highlight element tag and class names can be specified in options
*
* Usage:
* // wrap every occurrance of text 'lorem' in content
* // with <span class='highlight'> (default options)
* $('#content').highlight('lorem');
*
* // search for and highlight more terms at once
* // so you can save some time on traversing DOM
* $('#content').highlight(['lorem', 'ipsum']);
* $('#content').highlight('lorem ipsum');
*
* // search only for entire word 'lorem'
* $('#content').highlight('lorem', { wordsOnly: true });
*
* // don't ignore case during search of term 'lorem'
* $('#content').highlight('lorem', { caseSensitive: true });
*
* // wrap every occurrance of term 'ipsum' in content
* // with <em class='important'>
* $('#content').highlight('ipsum', { element: 'em', className: 'important' });
*
* // remove default highlight
* $('#content').unhighlight();
*
* // remove custom highlight
* $('#content').unhighlight({ element: 'em', className: 'important' });
*
*
* Copyright (c) 2009 Bartek Szopka
*
* Licensed under MIT license.
*
*/
jQuery.extend({
highlight: function (node, re, nodeName, className) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
for (var i = 0; i < node.childNodes.length; i++) {
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
}
}
return 0;
}
});
jQuery.fn.unhighlight = function (options) {
var settings = { className: 'highlight', element: 'span' };
jQuery.extend(settings, options);
return this.find(settings.element + "." + settings.className).each(function () {
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end();
};
jQuery.fn.highlight = function (words, options) {
var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
jQuery.extend(settings, options);
if (words.constructor === String) {
words = [words];
}
words = jQuery.grep(words, function(word, i){
return word != '';
});
words = jQuery.map(words, function(word, i) {
return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
});
if (words.length == 0) { return this; };
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
jQuery.highlight(this, re, settings.element, settings.className);
});
};
```
|
```
function hiliter(word, element) {
var rgxp = new RegExp(word, 'g');
var repl = '<span class="myClass">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');
```
|
Highlight a word with jQuery
|
[
"",
"javascript",
"jquery",
"html",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.