Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm working through [Josh Smith's CommandSink code](http://www.codeproject.com/KB/WPF/VMCommanding.aspx) obviously do not understand something about the "as" keyword in C#.
I don't understand why he wrote the line:
```
IsValid = _fe != null || _fce != null;
```
since he only needed to write:
```
IsValid = depObj != null;
```
Since it would never be the case the \_fe would be null and \_fce not null, or visa versa, right? Or am I missing something about how "as" casts variables?
```
class CommonElement
{
readonly FrameworkElement _fe;
readonly FrameworkContentElement _fce;
public readonly bool IsValid;
public CommonElement(DependencyObject depObj)
{
_fe = depObj as FrameworkElement;
_fce = depObj as FrameworkContentElement;
IsValid = _fe != null || _fce != null;
}
...
```
# ANSWER:
The answer is what Marc said in his comment "**that is the whole point of "as" - it *won't* throw an exception - it just reports null**."
and here is the proof:
```
using System;
namespace TestAs234
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Employee employee = new Employee();
Person.Test(customer);
Person.Test(employee);
Console.ReadLine();
}
}
class Person
{
public static void Test(object obj)
{
Person person = obj as Customer;
if (person == null)
{
Console.WriteLine("person is null");
}
else
{
Console.WriteLine("person is of type {0}", obj.GetType());
}
}
}
class Customer : Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Employee : Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
``` | `as` will return an object of the type you requested, if the operand is compatible. If it isn't, it will return `null`. If you use `as` and it is possible that the cast will fail, you need to check to make sure the reference is valid.
For example, if depObj was of type `String`, it would not be `null`, but it would also not be able to be converted to either of the requested types and both of those variables would become `null`. | as does "cast, if it is", and equivalent to:
`(X is TYPE) ? (TYPE) X : null`
it is however, more efficient than `is` + `cast`.
depObj may implement either interface, none, or both. | Is there more to the C# "as" keyword than simple casting? | [
"",
"c#",
"casting",
""
] |
I use Ext.form.ComboBox in very similar way as in this example:
<http://extjs.com/deploy/dev/examples/form/forum-search.html>
What annoys me is that when the ajax call is in progress it shows loading text and I cannot see any results from before.
Eg I input 'test' -> it shows result -> I add 'e' (search string is 'teste') -> result dissapear and loading text is shown, so for a second I cannot see any result and think about if it's not what I'm searching for...
How can I change this to simply not to say anything when 'loading'... | The solution is to override 'onBeforeLoad' method of Ext.form.ComboBox:
```
Ext.override(Ext.form.ComboBox,
{ onBeforeLoad:
function() {this.selectedIndex = -1;}
});
```
Please be warned, that this overrides the class method, so all of the ComboBox instances will not have the LoadingText showing. In case you would like to override only one instance - please use plugins (in quite similar way).
You may also look at Ext.LoadingMask to set an appropriate loading mask to aside element if you wish. | If you don't show loading message to user how user will know what is happening? User will notice that its already loading results so may wait to see the results, but if nothing displayed then user wouldn't know if its bringing new data or not. | How to avoid showing loading text in Ext.form.ComboBox? | [
"",
"javascript",
"combobox",
"extjs",
""
] |
In C#, I am trying to use <see cref="blah"/> to reference a method signature that contains the params keyword. I know this converts the parameter list to an array, but I can't even figure out how to refer to an array in a CREF attribute. I am finding nothing in my searches and no one I know has any idea, either. The compiler is choking on the square brackets. I've tried all kinds of different combinations, using curly braces, using the Array class, but nothing is working. Does anyone know this? | The ECMA 334 Standard PDF, Annex E contains a decent overview of XML Documentation comments. You can download the standard at:
<http://www.ecma-international.org/publications/standards/Ecma-334.htm>
Specifically, you'll want section E.3.1, starting on page 496.
Similar content is also at MSDN (though MSDN seems to have terrible navigation on this topic, making it difficult to find the other sections):
<http://msdn.microsoft.com/en-us/library/aa664787(VS.71).aspx>
The equivalent to E.3.1:
<http://msdn.microsoft.com/en-us/library/aa664807(VS.71).aspx>
You may also find Mono's documentation useful:
<http://www.go-mono.com/docs/index.aspx?tlink=29@man%3amdoc(5)>
Specfically, the "CREF FORMAT" section covers the ID string conventions.
# Update 2018/05/23
The URL for the ECMA-334 standard PDF above links to the latest edition of the standard. In 2009, that was the 4th edition of the standard. However, as of December 2017, the 5th edition is current, and section E.3.1 from the 4th edition became section D.4.2 in the 5th edition.
The previous versions of the ECMA-334 standard are available for download from the following page: <https://www.ecma-international.org/publications/standards/Ecma-334-arch.htm>
# Update 2023/11/20
Link to ECMA-334 standard is now <https://ecma-international.org/publications-and-standards/standards/ecma-334/> | According to the [B.3.1 ID string format](http://msdn.microsoft.com/en-us/library/aa664807(VS.71).aspx) article, referencing an array is done with [square brackets] (with optional `lowerbound:size` specifiers) but if you just want to refer to an array of a certain type (or even an Object array), you can't just write
`<see cref="Object[]"/>`
instead you need to specify you're making a type reference with the `T:` prefix, like
`<see cref="T:Object[]"/>`
This does not seem to apply when referencing a specific overload of a method, such as
`<seealso cref="String.Join(String, String[])"/>` | Using C#'s XML comment cref attribute with params syntax | [
"",
"c#",
"xml-comments",
"params-keyword",
""
] |
I wrote a small test program with a sample class containing also self-defined constructor, destructor, copy constructor and assignment operator. I was surprised when I realized that the copy constructor was not called at all, even though I implemented functions with return values of my class and lines like `Object o1; Object o2(o1);`
innerclass.hpp:
```
#include <iostream>
class OuterClass
{
public:
OuterClass()
{
std::cout << "OuterClass Constructor" << std::endl;
}
~OuterClass()
{
std::cout << "OuterClass Destructor" << std::endl;
}
OuterClass(const OuterClass & rhs)
{
std::cout << "OuterClass Copy" << std::endl;
}
OuterClass & operator=(const OuterClass & rhs)
{
std::cout << "OuterClass Assignment" << std::endl;
}
class InnerClass
{
public:
InnerClass() : m_int(0)
{
std::cout << "InnerClass Constructor" << std::endl;
}
InnerClass(const InnerClass & rhs) : m_int(rhs.m_int)
{
std::cout << "InnerClass Copy" << std::endl;
}
InnerClass & operator=(const InnerClass & rhs)
{
std::cout << "InnerClass Assignment" << std::endl;
m_int = rhs.m_int;
return *this;
}
~InnerClass()
{
std::cout << "InnerClass Destructor" << std::endl;
}
void sayHello()
{
std::cout << "Hello!" << std::endl;
}
private:
int m_int;
};
InnerClass innerClass()
{
InnerClass ic;
std::cout << "innerClass() method" << std::endl;
return ic;
}
};
```
innerclass.cpp:
```
#include "innerclass.hpp"
int main(void)
{
std::cout << std::endl << "1st try:" << std::endl;
OuterClass oc;
OuterClass oc2(oc);
oc.innerClass().sayHello();
std::cout << std::endl << "2nd try:" << std::endl;
OuterClass::InnerClass ic(oc.innerClass());
ic = oc.innerClass();
}
```
Output:
```
1st try:
OuterClass Constructor
OuterClass Copy
InnerClass Constructor
innerClass() method
Hello!
InnerClass Destructor
2nd try:
InnerClass Constructor
innerClass() method
InnerClass Constructor
innerClass() method
InnerClass Assignment
InnerClass Destructor
InnerClass Destructor
OuterClass Destructor
OuterClass Destructor
```
After some research I read that there is no guarantee that the compiler will use the explicitely defined copy constructor. I do not understand this behavior. Why does the copy constructor even exist then, if we do not know that it is called? How does the compiler decide if it uses it?
Or, even better, is there a way to force the compiler to use the self-defined copy constructor? | Just for completeness with the other answers, the standard allows the compiler to omit the copy constructor in certain situations (what other answers refer to as "Return Value Optimization" or "Named Return Value Optimization" - RVO/NRVO):
> 12.8 Copying class objects, paragraph 15 (C++98)
>
> Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all, even if the class copy constructor or destructor have side effects. For a function with a class return type, if the expression in the return statement is the name of a local object, and the cv-unqualified type of the local object is the same as the function return type, an implementation is permitted to omit creating the temporary object to hold the function return value, even if the class copy constructor or destructor has side effects. In these cases, the object is destroyed at the later of times when the original and the copy would have been destroyed without the optimization.
So in your `innerClass()` method, the copy constructor you might think would be called at the return is permitted to be optimized away:
```
InnerClass innerClass() {
InnerClass ic;
std::cout << "innerClass() method" << std::endl;
return ic; // this might not call copy ctor
}
``` | You should not design your class with a reliance on the copy constructor being called (or not called) in specific circumstances. The compiler is allowed to elide or add copy constructor calls at all sorts of places, and you really don't want to have to keep track of them.
As for why you need one - well, the compiler may decide it needs a copy, and the copy constructor is what it uses to do so. The advantage of copy constructor calls being elided is performance - copying is usually quite an expensive operation. | How to force the compiler to use explicit copy constructor? | [
"",
"c++",
""
] |
I have a multidimensinal array.. Something like this for example:
```
Array (
[0] => Array
(
[title] => Star Trek - Viaje a las estrellas
[country] => Venezuela, Spain, long title, poster title
)
[1] => Array
(
[title] => Viaje a Las Estrellas
[country] => Venezuela
)
)
```
I want to get te text between commas from [country] and insert each element into separate indexes, for example:
```
Array (
[0] => Array
(
[title] => Star Trek - Viaje a las estrellas
[country] => [0] => Venezuela
[1] => Spain
[2] => long title
[3] => poster title
)
[1] => Array
(
[title] => Viaje a Las Estrellas
[country] => Venezuela
)
)
```
Probably the array layout is incorrect but I just want to explain to you what I need to do.
Note that not always [country] contains elements separated by commas, sometimes is just one single element.
How can I do it??
Thanks! | Try using [`explode()`](http://php.net/explode) on the country element. You can use a separator of `", "`, since these are comma-separated values.
One way to do it (which is similar to how others have suggested) would be:
```
// Assuming that $data contains your multidimensional array...
for ($i = 0; $i < count($data); $i++)
{
if (strstr($data[$i]['country'], ', '))
{
$data[$i]['country'] = explode(', ', $data[$i]['country']);
}
}
```
Also, note that you don't really need to use `strpos()`—`strstr()` works perfectly here. | You could use the `preg_split` function and a regular expression to split the string:
```
foreach ($array as $key => $item) {
if (strpos($item['country'], ',') !== false) { // check if string contains a comma
$array[$key]['country'] = preg_split('/,\s*/', $item['country']);
}
}
``` | PHP: Get text separated by commas | [
"",
"php",
"arrays",
""
] |
I was attempting to dynamically create a Where predicate for a LINQ2SQL query:
```
...Where(SqlMethods.Like(r.Name, "%A%") ||
SqlMethods.Like(r.Name, "%B%") ||
SqlMethods.Like(r.Name, "%C%") || ...)
```
A, B, C, etc. come from some array. So I tried the following:
```
var roleExpression = Expression.Parameter(typeof(Role), r);
var nameExpression = Expression.Property(roleExpression, "Name");
var termExpression = Expression.Constant("%" + term[i] + "%");
var likeExpression = Expression.Call(
typeof(SqlMethods), "Like",
new[] { typeof(string), typeof(string) }, nameExpression, termExpression);
```
However, the last line fails with the message *No method 'Like' on type 'System.Data.Linq.SqlClient.SqlMethods' is compatible with the supplied arguments*.
So I tried the following line:
```
var likeExpression = Expression.Call(null,
typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
nameExpression, searchTermExpression)
```
This works. However, I don't understand what the difference is between these two lines. In my opinion they should deliver the same result.
Could anyone explain this?
Kind regards,
Ronald Wildenberg | I believe that the `Type[]` argument is for *generic type parameters* - i.e. you were trying to call:
```
SqlMethods.Like<string,string>(...); // note the <string,string>
```
Try passing an empty `Type[]`.
---
Edit re the confusion (comments); my point is: you shouldn't be specifying **anything** for the `Type[]` argument. Either an empty array or null would do; for example:
```
var likeExpression = Expression.Call(
typeof(SqlMethods), "Like", null, nameExpression, termExpression);
``` | You can use the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) class from Joseph Albahari and Ben Albahari to build your where predicate | Difference between Expression.Call overloads? | [
"",
"c#",
"linq",
"linq-to-sql",
"lambda",
""
] |
I would like to read an input file in C++, for which the structure (or lack of) would be something like a series of lines with *text = number*, such as
```
input1 = 10
input2 = 4
set1 = 1.2
set2 = 1.e3
```
I want to get the number out of the line, and throw the rest away. Numbers can be either integers or doubles, but I know when they are one or other.
I also would like to read it such as
```
input1 = 10
input2=4
set1 =1.2
set2= 1.e3
```
so as to be more robust to the user. I think this means that it shouldn't be red in a formatted fashion.
Anyway, is there a smart way to do that?
I have already tried the following, but with minimal knowledge of what I've been doing, so the result was as expected... no success.
```
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <string>
using namespace std;
using namespace boost;
int main(){
string tmp;
char temp[100];
int i,j,k;
ifstream InFile("input.dat");
//strtol
InFile.getline(temp,100);
k=strtol(temp,0,10);
cout << k << endl;
//lexical_cast
InFile.getline(temp,100);
j = lexical_cast<int>(temp);
cout << j << endl;
//Direct read
InFile >> tmp >> i;
cout << i << endl;
return 0;
}
``` | Simply read one line at a time.
Then split each line on the '=' sign. Use the stream functionality do the rest.
```
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}
}
```
With error checking:
```
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
double value;
if ((std::getline(str,text,'=')) && (str >> value))
{
// Happy Days..
// Do processing.
continue; // To start next iteration of loop.
}
// If we get here. An error occurred.
// By doing nothing the line will be ignored.
// Maybe just log an error.
}
}
``` | There are already some fine solutions here. However, just to throw it out there, some comments implied that Boost Spirit is an inappropriate solution for this problem. I'm not sure I completely disagree. However, the following solution is very terse, readable (*if* you know EBNF) and error-tolerant. I'd consider using it.
```
#include <fstream>
#include <string>
#include <boost/spirit.hpp>
using namespace std;
using namespace boost::spirit;
int main()
{
ifstream data("input.dat");
string line;
vector<double> numbers;
while(getline(data,line))
{
parse(line.c_str(),
*(+~ch_p('=') >> ch_p('=') >> real_p[push_back_a(numbers)]),
space_p);
}
}
``` | Reading parts of an input file | [
"",
"c++",
"parsing",
"file-io",
""
] |
I'm using the `json` module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and `json.loads()` is taking 20 seconds.
I thought the `json` module had some native code to speed up the decoding?
How do I check if this is being used?
As a comparison, I downloaded and installed the `python-cjson` module, and `cjson.decode()` is taking 1 second for the same test case.
I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.
(I'm developing on Mac OS X, but I getting a similar result on Windows XP.) | It may vary by platform, but the builtin json module is based on [simplejson](http://pypi.python.org/pypi/simplejson/), not including the C speedups. I've found simplejson to be as a fast as python-cjson anyway, so I prefer it since it obviously has the same interface as the builtin.
```
try:
import simplejson as json
except ImportError:
import json
```
Seems to me that's the best idiom for awhile, yielding the performance when available while being forwards-compatible. | The new [Yajl - Yet Another JSON Library](https://github.com/rtyler/py-yajl/) is very fast.
```
yajl serialize: 0.180 deserialize: 0.182 total: 0.362
simplejson serialize: 0.840 deserialize: 0.490 total: 1.331
stdlib json serialize: 2.812 deserialize: 8.725 total: 11.537
```
You can [compare the libraries yourself](https://github.com/rtyler/py-yajl/blob/master/compare.py).
**Update:** [UltraJSON](https://github.com/esnme/ultrajson) is even faster. | Python 2.6 JSON decoding performance | [
"",
"python",
"json",
"python-2.6",
""
] |
If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list)
mi_set.remove('small')
print mi_set
```
I get:
```
set(['three', 'words'])
```
which is what I expect. Whereas If I try:
```
mi_list = ['three', 'small', 'words']
mi_set = set(mi_list).remove('small')
print mi_set
```
I get:
```
None
```
Why?
I suspect there's a clue in that if I try to remove an element that isn't present - eg 'big' - an error gets reported:
```
KeyError: 'big'
``` | `set.remove` returns nothing (None).
Your code assigns the return value of `set.remove` to the variable `mi_set`. Therefore, mi\_set is None. | There is a general convention in python that *methods which cause [side-effects](http://en.wikipedia.org/wiki/Side_effect_(computer_science)) return None*. Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.
This is essentially to help you avoid bugs. Say you had a set called mi\_set. If you could write:
```
mi_set2 = mi_set.remove('small')
```
then a reader might think: "`mi_set2` is different from `mi_set`". But this would not be the case! And the confusion might lead to subtle bugs caused by mistakenly sharing data structures. So by returning `None`, python forces you to remember that methods like those I listed above modify objects, rather than creating new ones.
See also long discussion [here](http://mail.python.org/pipermail/python-list/2004-August/277901.html). Although note that methods like `sorted()` and `reversed()` have been added since that thread.
[note that list.pop is an exception to this rule, for historical reasons – it lets you use a list like a stack. And even then, it returns the object removed, rather than the list.] | can a method call be chained to the 'set()' built-in? (and why not?) | [
"",
"python",
""
] |
This test fails when it is run with the NUnit console runner. It works if I run just that test with TestDriven.NET, but not if I run the entire suite with TestDriven.NET:
```
[Test]
public void BackgroundWorkerFiresRunWorkerCompleted()
{
var runner = new BackgroundWorker();
ManualResetEvent done = new ManualResetEvent(false);
runner.RunWorkerCompleted += delegate { done.Set(); };
runner.RunWorkerAsync();
bool res = done.WaitOne(TimeSpan.FromSeconds(10));
// This assert fails:
Assert.IsTrue(res, "RunWorkerCompleted was not executed within 10 seconds");
}
```
I suspect the problem have something to do with not having a message-loop, but I am not sure.
What are the requirements for using BackgroundWorker?
Is there a workaround to make the test work? | I don't think that it has to do with the message pump, since tests usually run in a blocking fashion anyways. But it may be that the event is invoked on the "UI" thread, which uses a windows message which does not get handled.
So, if the problem was the message pump or windows messages not being handled, you could try like this to replace your current `bool res = done.WaitOne(TimeSpan.FromSeconds(10));` line:
```
DateTime end = DateTime.Now.AddSeconds(10);
bool res = false;
while ((!res) && (DateTime.Now<end)) {
Application.DoEvents();
res = done.WaitOne(0):
}
``` | Are you missing a BGW DoWork event handler? | C#/.NET: Testing BackgroundWorker with NUnit | [
"",
"c#",
".net",
"multithreading",
"unit-testing",
"backgroundworker",
""
] |
I have a `<path id="...">` in my `build.xml`. Before invoking the compiler I want to verify that every jar/directory on the classpath exists and print a warning with the missing ones. Does anybody know an existing solution or do I need to write my own task for that?
---
OK, I decided to go for a custom task. Here it is, in case anybody ever needs such a thing:
```
import java.io.File;
import java.util.Iterator;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.Resources;
public class CheckClasspathTask extends Task {
private Reference reference;
public CheckClasspathTask() {
}
public void setRefId(Reference reference) {
this.reference = reference;
}
public void execute() throws BuildException {
Resources resources = new Resources();
resources.setProject(getProject());
resources.add((ResourceCollection) reference.getReferencedObject());
boolean isFirst = true;
for (Iterator i = resources.iterator(); i.hasNext(); ) {
String f = i.next().toString();
if (!new File(f).exists()) {
if (isFirst) {
isFirst = false;
System.out.println("WARNING: The following entries on your classpath do not exist:");
}
System.out.println(f);
}
}
}
}
``` | I would say probably a custom ant task is in order, a little like the `org.netbeans.modules.bpel.project.anttasks.ValidateBPELProjectTask` done in a '`pre-dist`' target of this [build.xml](http://code.google.com/p/switchtransaccional/source/browse/FrontEnds/nbproject/build-impl.xml?r=34).
Note: the [ValidateBPELProjectTask ant task](http://www.koders.com/java/fid176241E48F72FBB1B5AD8F6DD366BCCC0B3ABD61.aspx?s=AntClassLoader#L95) is a bit more complex than your usual custom task: it needs to have its own classpath to run (classpath not initially passed to the build.xml at first).
Since you cannot modify the classpath of the current ant task classloader, ValidateBPELProjectTask defines a new `AntClassLoader` and calls `setContextClassLoader()`.
You will not need such a mechanism though: you can just pass the list of directories to check to your task as a parameter. | This will check that every file or folder in a classpath exists. If one of them does not, it will fail the build showing the name of the 1st one that can't be found.
```
<target name="check-classpath" depends="create-classpath">
<pathconvert pathsep="," property="myclasspath" refid="compile.classpath"/>
<foreach list="${myclasspath}" param="file" target="check-file-or-folder-exists" />
</target>
<target name="check-file-or-folder-exists">
<fail message="Error: ${file} not found">
<condition>
<not>
<available file="${file}" />
</not>
</condition>
</fail>
</target>
```
Note that `<foreach>` is in ant-contribs -- [Ant Contribs clickable LINK](http://ant-contrib.sourceforge.net/tasks/tasks/foreach.html)
This will be needed to load the ant-contrib jar and hook up all the targets in it:
```
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="${some.lib.dir}/ant-contrib-1.0b3.jar" />
</classpath>
</taskdef>
```
There is supposed to exist a `<for>` task that will allow setting an option to continue through all the path elements and only show an error at the end. I found my version of Eclipse had `<foreach>` already on the classpath, so I figured this was good enough for me. | Classpath validation in ant | [
"",
"java",
"ant",
"build-process",
"build",
"classpath",
""
] |
After an AJAX request, sometimes my application may return an empty object, like:
```
var a = {};
```
How can I check whether that's the case? | You can use a for…in loop with an `Object.hasOwn` ([ECMA 2022+](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility)) test to check whether an object has any own properties:
```
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}
```
If you also need to distinguish `{}`-like empty objects from other objects with no own properties (e.g. `Date`s), you can do various (and unfortunately need-specific) type checks:
```
function isEmptyObject(value) {
if (value == null) {
// null or undefined
return false;
}
if (typeof value !== 'object') {
// boolean, number, string, function, etc.
return false;
}
const proto = Object.getPrototypeOf(value);
// consider `Object.create(null)`, commonly used as a safe map
// before `Map` support, an empty object as well as `{}`
if (proto !== null && proto !== Object.prototype) {
return false;
}
return isEmpty(value);
}
```
Note that comparing against `Object.prototype` like in this example will fail to recognize cross-realm objects.
*Do not use* `Object.keys(obj).length`. It is O(N) complexity because it creates an array containing all the property names only to get the length of that array. Iterating over the object accomplishes the same goal but is O(1).
For compatibility with JavaScript engines that don’t support ES 2022+, `const` can be replaced with `var` and `Object.hasOwn` with `Object.prototype.hasOwnProperty.call`:
```
function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true
}
```
Many popular libraries also provide functions to check for empty objects:
[jQuery](https://api.jquery.com/jQuery.isEmptyObject/):
```
jQuery.isEmptyObject({}); // true
```
[lodash](https://lodash.com/docs#isEmpty):
```
_.isEmpty({}); // true
```
[Underscore](https://underscorejs.org/#isEmpty):
```
_.isEmpty({}); // true
```
[Hoek](https://github.com/hapijs/hoek):
```
Hoek.deepEqual({}, {}); // true
```
[ExtJS](https://docs.sencha.com/extjs/6.0.2/modern/Ext.Object.html#method-isEmpty):
```
Ext.Object.isEmpty({}); // true
```
[AngularJS (version 1)](https://docs.angularjs.org/api/ng/function/angular.equals):
```
angular.equals({}, {}); // true
```
[Ramda](https://ramdajs.com/docs/#isEmpty):
```
R.isEmpty({}); // true
``` | If [ECMAScript 5 support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Browser_compatibility) is available, you can use `Object.keys()`:
```
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
```
For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:
```
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
``` | How do I test for an empty JavaScript object? | [
"",
"javascript",
"javascript-objects",
""
] |
The Javadoc for [BufferedReader.readLine()](http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine()) says:
> A line is considered to be terminated by any one of a line feed ('\n'),
> a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
I need slightly better control than this (e.g. I would like to be able to specify that an end of line is "\r\n", so that an "\n" by itself does not terminate the line).
Is there any JDK or library function which does this? | Try using the [Scanner](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) class:
```
String line = Scanner(file).useDelimiter("\r\n").next();
``` | Depending on what the use case for which you need the BufferedReader, you can maybe change over to using the Scanner class, which is able to read text from different sources (files, streams), and has a direct method th specify the delimiting pattern.
See <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)> | Is there an equivalent of BufferedReader.readLine() that lets me pick what my end of line characters are? | [
"",
"java",
"io",
"newline",
"line-endings",
""
] |
So I have about 4,000 word docs that I'm attempting to extract the text from and insert into a db table. This works swimmingly until the processor encounters a document with the `*.doc` file extension but determines the file is actually an RTF. Now I know POI doesn't support RTFs which is fine, but I do need a way to determine if a `*.doc` file is actually an RTF so that I can choose to ignore the file and continue processing.
I've tried several techniques to overcome this, including using ColdFusion's MimeTypeUtils, however, it seems to base its assumption of the mimetype on the file extension and still classifies the RTF as application/msword. Is there any other way to determine if a `*.doc` is an RTF? Any help would be hugely appreciated. | With CF8 and compatible:
```
<cffunction name="IsRtfFile" returntype="Boolean" output="false">
<cfargument name="FileName" type="String" />
<cfreturn Left(FileRead(Arguments.FileName),5) EQ '{\rtf' />
</cffunction>
```
For earlier versions:
```
<cffunction name="IsRtfFile" returntype="Boolean" output="false">
<cfargument name="FileName" type="String" />
<cfset var FileData = 0 />
<cffile variable="FileData" action="read" file="#Arguments.FileName#" />
<cfreturn Left(FileData,5) EQ '{\rtf' />
</cffunction>
```
**Update:** A better CF8/compatible answer. To avoid loading the whole file into memory, you can do the following to load just the first few characters:
```
<cffunction name="IsRtfFile" returntype="Boolean" output="false">
<cfargument name="FileName" type="String" />
<cfset var FileData = 0 />
<cfloop index="FileData" file="#Arguments.FileName#" characters="5">
<cfbreak/>
</cfloop>
<cfreturn FileData EQ '{\rtf' />
</cffunction>
```
**Based on the comments:**
Here's a very quick way how you might do a generate "what format is this" type of function. Not perfect, but it gives you the idea...
```
<cffunction name="determineFileFormat" returntype="String" output="false"
hint="Determines format of file based on header of the file's data."
>
<cfargument name="FileName" type="String"/>
<cfset var FileData = 0 />
<cfset var CurFormat = 0 />
<cfset var MaxBytes = 8 />
<cfset var Formats =
{ WordNew : 'D0,CF,11,E0,A1,B1,1A,E1'
, WordBeta : '0E,11,FC,0D,D0,CF,11,E0'
, Rtf : '7B,5C,72,74,66' <!--- {\rtf --->
, Jpeg : 'FF,D8'
}/>
<cfloop index="FileData" file="#Arguments.FileName#" characters="#MaxBytes#">
<cfbreak/>
</cfloop>
<cfloop item="CurFormat" collection="#Formats#">
<cfif Left( FileData , ListLen(Formats[CurFormat]) ) EQ convertToText(Formats[CurFormat]) >
<cfreturn CurFormat />
</cfif>
</cfloop>
<cfreturn "Unknown"/>
</cffunction>
<cffunction name="convertToText" returntype="String" output="false">
<cfargument name="HexList" type="String" />
<cfset var Result = "" />
<cfset var CurItem = 0 />
<cfloop index="CurItem" list="#Arguments.HexList#">
<cfset Result &= Chr(InputBaseN(CurItem,16)) />
</cfloop>
<cfreturn Result />
</cffunction>
```
Of course, worth pointing out that all this wont work on 'headerless' formats, including many common text-based ones (CFM,CSS,JS,etc). | The first five bytes in any RTF file should be:
```
{\rtf
```
If they aren't, it's not an RTF file.
The external links section in the [Wikipeida article](http://en.wikipedia.org/wiki/Rich_Text_Format) link to the specifications for the various versions of RTF.
Doc files (at least those since Word '97) use something called "Windows Compound Binary Format", documented [in a PDF here](http://86/WindowsCompoundBinaryFileFormatSpecification.pdf). According to that, these Doc files start with the following sequence:
```
0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1
```
Or in older beta files:
```
0x0e, 0x11, 0xfc, 0x0d, 0xd0, 0xcf, 0x11, 0xe0
```
According to the Wikipedia article on Word, there were at least 5 different formats prior to '97.
Looking for {\rtf should be your best bet.
Good luck, hope this helps. | Best Way to Determine if *.doc File is RTF with Java or ColdFusion | [
"",
"java",
"coldfusion",
"apache-poi",
"mime-types",
""
] |
HI,
How do I move (drag) a Grid Panel inside a WPF Window? The Grid Panel does not have a Position or Location or X and Y coordinate porperty. All I am looking at is to move the Grid Panel from its current location to a new location using Mouse so that the controls that are "burried" underneath it will show up.
Any pointers?
Many Thanks. | Here's some code examples to get you started:
In XAML:
Create a grid and define a render transform on it:
```
<Grid x:Name="grid" Background="Blue"
Width="100" Height="100"
MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp">
<Grid.RenderTransform>
<TranslateTransform x:Name="tt"/>
</Grid.RenderTransform>
</Grid>
```
Name the control that you want the grid to move within:
```
<Window x:Name="window" ...>
<Grid x:Name="grid"...
</Window>
```
In code behind:
```
Point m_start;
Vector m_startOffset;
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
m_start = e.GetPosition(window);
m_startOffset = new Vector(tt.X, tt.Y);
grid.CaptureMouse();
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (grid.IsMouseCaptured)
{
Vector offset = Point.Subtract(e.GetPosition(window), m_start);
tt.X = m_startOffset.X + offset.X;
tt.Y = m_startOffset.Y + offset.Y;
}
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
grid.ReleaseMouseCapture();
}
``` | ***Based on Josh G's answer***
Josh's answer is excellent if you want to move one grid, but lacks capabilities for movement of several elements.
This is how to move several elements separately
XAML
```
<Grid x:Name="gridHost">
<Grid x:Name="gridBlue" Background="Blue" Width="100" Height="100" MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp" Margin="-100,0,0,0">
<Grid.RenderTransform>
<TranslateTransform/>
</Grid.RenderTransform>
</Grid>
<Grid x:Name="gridRed" Background="Red" Width="100" Height="100" MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp" Margin="100,0,0,0">
<Grid.RenderTransform>
<TranslateTransform/>
</Grid.RenderTransform>
</Grid>
</Grid>
```
Code behind
```
Point m_start;
Vector m_startOffset;
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as Grid;
TranslateTransform translate = element.RenderTransform as TranslateTransform;
m_start = e.GetPosition(gridHost);
m_startOffset = new Vector(translate.X, translate.Y);
element.CaptureMouse();
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = sender as Grid;
TranslateTransform translate = element.RenderTransform as TranslateTransform;
if (element.IsMouseCaptured)
{
Vector offset = Point.Subtract(e.GetPosition(gridHost), m_start);
translate.X = m_startOffset.X + offset.X;
translate.Y = m_startOffset.Y + offset.Y;
}
}
private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as Grid;
element.ReleaseMouseCapture();
}
``` | How to move a Grid Panel in WPF Window | [
"",
"c#",
"wpf",
"grid",
"move",
""
] |
Occasionally I need to use fixed-width integers for communication with external devices like PLCs. I also use them to define bitmasks and perform bit manipulation of image data. AFAIK the C99 standard defines fixed-width integers like int16\_t. However the compiler I use, VC++ 2008 doesn't support C99 and AFAIK Microsoft is not planning to support it.
My question is what is the best practice for using fixed-width integers in C++?
I know that VC++ defines non-standard fixed-width integers like \_\_int16, but I am hesitant to use a non-standard type. Will the next C++ standard define fixed-width integers? | Boost has the typedefs for all of the C99 types and more:
["Boost integer library"](http://www.boost.org/doc/libs/1_38_0/libs/integer/index.html) | You can workaround the problem with some `#ifdef` directives.
```
#ifdef _MSC_VER
typedef __int16 int16_t
#else
#include <stdint.h>
#endif
``` | Fixed-width integers in C++ | [
"",
"c++",
"c",
"visual-c++",
"types",
"portability",
""
] |
I have a business object collection (representing data from the database) that inherits from Collection and has a static method that calls a stored proc and then populates its properties with the data returned.
My question is; is it wrong to inherit from Collection as it doesnt really extend the class? or would it be better to not inherit from anything but instead maintain a private variable that is of type Collection? | It is hard to give an answer to this without seeing a lot more detail about what you are trying to do. However, I would not normally inherit from Collection as it does not really give enough virtual methods to override. This can make altering the behaviour of your class a little tricky in the future.
The trouble with inheritance is that if you use it you will be stuck with the Collection base class's behaviour forever more, or face a complex refactoring. For example, you may want to add filtering, searching and sorting operations at which point you will need to switch to List from Collection. You may even want to do data binding where you will need a BindingList instead of a Collection.
A different plan would be to inherit from ICollection or better still IList<T> and then delegate to a private Collection member. This gives you maximum control and allows you to alter the internal representation of your class without affecting the public interface. The trouble with this is that it takes longer to develop you classes.
Therefore, what you are facing is a trade off between faster development and future flexibility, and as I said at the start it is a bit difficult to judge which way to go from the information given in the original post.
**PS:** To make an IList<T> implementation read-only, simply return true from IsReadOnly and then throw a NotSupportedException from all the methods that alter the list. | If it's OK for your business object to provide usual collection methods to the world, then it's quite OK to inherit from `Collection<T>`. And as I guess, in fact you add something to it - you specify `T`.
**Udate:**
According to author's comments, publishing of all collection methods would make object editable which is not acceptable. So instead of inheriting he would make private field and make the class enumerable. | Should a business object collection inherit from Collection<T> when it doesn't extend it? | [
"",
"c#",
"inheritance",
"oop",
""
] |
I have an XML file with a specified schema location such as this:
```
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
```
I want to validate in C#. Visual Studio, when I open the file, validates it against the schema and lists errors perfectly. Somehow, though, I can't seem to validate it automatically in C# without specifying the schema to validate against like so:
```
XmlDocument asset = new XmlDocument();
XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath");
XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler);
asset.Schemas.Add(schema);
asset.Load(filename);
asset.Validate(DocumentValidationHandler);
```
Shouldn't I be able to validate with the schema specified in the XML file automatically ? What am I missing ? | You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the `ValidationEventHandler` in the settings to receive validation errors. Your code will end up looking like this:
```
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD
{
public static void Main()
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read()) ;
}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
``` | A simpler way, if you are using .NET 3.5, is to use `XDocument` and `XmlSchemaSet` validation.
```
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
```
See the [MSDN documentation](http://msdn.microsoft.com/en-us/library/bb340331.aspx) for more assistance. | Validating an XML against referenced XSD in C# | [
"",
"c#",
"xml",
"xsd",
""
] |
I have a database like where:
Table `foo` has columns `id` and `name`
Table `bar` has columns `id` and `foo_id`
I have an incoming HTTP query with a `foo.name`, I'd like to insert a row into `bar` with `bar.foo_id` set appropriately. So, for example:
```
> SELECT * FROM foo;
id name
------ -------
1 "Andrey"
(1 row)
> SELECT * FROM bar;
(0 rows)
```
Given `"Andrey"`, is there a single query I can execute to get:
```
> SELECT * FROM bar;
id foo_id
------ -------
1 1
(1 row)
```
I was thinking along the lines of:
```
> UPDATE bar SET foo_id=(SELECT id FROM foo WHERE foo.name=?)
```
But this seems to be wrong, as SELECT's return sets, not values... | you would have to do
```
SELECT TOP 1 ID FROM foo where foo.name=?
```
but other than that there is nothing wrong with doing a select in an update. | This will work in MS SQL Server, if the sub query returns only one value (Such as a MAX() or TOP 1)
I'm not sure if this syntax forks in MySQL but you can try it...
```
UPDATE
bar
SET
bar.foo_id = foo.id
FROM
bar
INNER JOIN
foo
ON foor.name = bar.name
ORDER BY
foo.id
```
In this case, if the join returns multiple results per record in bar, all of them will be applied. The order by determining whihc order they are applied, and the last one being peristent. | Can I have an inner SELECT inside of an SQL UPDATE? | [
"",
"mysql",
"sql",
"sqlite",
"sql-update",
""
] |
I am mainly looking for good development practices specially when working in conjunction with mysql. I searched through the questions but could not find any related questions. I would appreciate if some one share their practices and wisdom gained through experience.
Apart from some coding standards, I am also looking for design standards and common architectural practices.
Background: I started my career with Java, and over the years I moved to C#/.NET space. I have been practicing architect for over 3 years now. Just added this to give some idea to people. | I would suggest that you familiarize yourself with the history of PHP, I know that doing so has given me a much greater appreciation of what PHP is today and where it has come from.
In short, PHP was written by Rasmus Lerdorf to provide simple wrapper functions for the C code that was actually doing the heavy-lifting so that he could have a simpler language / syntax for writing templates that needed to behave dynamically. The growth of PHP and the community which surrounds it is best described as organic. And much like other things that grow organically, its more than a little messy, asymmetrical, and downright non-congruent.
Once you understand PHP and its community, you need to embrace PHP for everything that it is and everything that it is not. This idea was best presented by Terry Chay in his article [PHP without PHP](http://terrychay.com/blog/article/php-without-php.shtml). He's specifically talking about the concept of funky caching, but he captures the concept of coding for PHP as if it were PHP and not (insert favorite language here) better than anyone I've ever seen. In other words, don't try to make PHP into Java, C#, Ruby, etc because if you do you'll fail and you'll hate your life.
Take a look at
[How is PHP Done the Right Way?](https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way).
I must say that you must first, last, and always avoid the tendency of most beginning PHP developers to use the spaghetti-code anti-pattern. In other words, if you find that you're writing code that contains sql queries, manipulation of data, validation of data, and html output all in a single php script, then you're doing it wrong.
In order to avoid this, it will be helpful to learn something about the nature of web-oriented design patterns. This of course precludes a familiarity with object-oriented programming. But once you've learned the basics of object-oriented programming in PHP, study the MVC design pattern. You don't have to implement this exactly but using the basic ideas of Model-View-Controller will allow you to avoid the blob script problem that most newbies tend to create.
On this point, I would strongly recommend that you take any code snippets you find on the web with a grain of salt. And even if you find it in a book you'll have to consider how old the book is. PHP as a language has advanced quite a long ways and you can't just take code samples at face value because, depending on their age, they may be using workarounds that were valid in 3.x or 4.x but simply are no longer necessary with newer features.
One great thing to do is to study the various frameworks out there. Evaluate what you like and what you don't. Maybe even work up each of the quickstarts that are provided with the framework documentation so that you can start to get an idea of what you like and don't like. And I would strongly recommend that you review the code from the frameworks as well as several other open-source projects so that you can get a feel for how others do things in PHP. Again, take it all with a grain of salt because every PHP developer has their own pet peeves and nuances and none of us is right all the time. In fact, most of the time with PHP there are going to be several pretty good ways to do something.
If you want to get a better understanding of the patterns that are being implemented by the frameworks and are commonly thrown around in the common vernacular on SO, I would suggest that you read [Fowler](https://rads.stackoverflow.com/amzn/click/com/0321127420) and [GoF](https://rads.stackoverflow.com/amzn/click/com/0201633612). They'll teach all about the basic design patterns you'll use in your development efforts.
Specifically watch for the following:
* Function files that contain LOTS of functions. This is most likely representative of a need to either put functions directly in the scripts that need them or it may also indicate an opportunity to create some more generic functions that can be made to fulfill the roles of a couple of highly specific functions. Of course, if you're building cohesive, well-encapsulated classes you shouldn't run into this problem.
* The do everything class. This is a blob anti-pattern and is really nasty. In this case you need to identify where cohesion and encapsulation are breaking down and use those points as opportunities to break up the class into several smaller, more maintainable classes.
* SQL queries that don't use parameterized queries or at least escaped parameters. Very, very, very bad.
* Any instance where validation is not being performed or is only performed client-side. When developing for the web, the only way to keep your site and your users safe is to assume that everyone else is a black hat.
* A sudden obsessive desire to use a template engine. PHP is a templating language. Make certain that you have clear reasons for adding another layer onto your website before using a template engine.
For further reading please look at the following:
[PHP Application Design Patterns](https://stackoverflow.com/questions/548399/what-php-application-design-design-patterns-do-you-use)
[Defend PHP](https://stackoverflow.com/questions/309300/defend-php-convince-me-it-isnt-horrible) -- useful to give you an idea of the most common criticisms.
[Security of strip\_tags and mysqlirealescapestring](https://stackoverflow.com/questions/585358/security-of-striptags-and-mysqlirealescapestring/)
[What should Every PHP Programmer Know](https://stackoverflow.com/questions/306497/what-should-every-php-programmer-know/)
[How to Structure an ORM](https://stackoverflow.com/questions/598332/how-would-an-orm-framework-in-php-be-structured/)
[Best Way to Organize Class Hierarchy](https://stackoverflow.com/questions/220347/best-way-to-organize-php-class-heirarchy/)
[Main Components / Layers of PHP App](https://stackoverflow.com/questions/548378/what-are-the-main-components-layers-of-a-php-application/)
[Why use Framework for PHP](https://stackoverflow.com/questions/474641/why-should-i-use-an-mvc-framework-for-php/)
[Recommended Security Training for PHP](https://stackoverflow.com/questions/612177/recommend-security-training-for-php-mysql-web-developer/) | * Use a coding standard.
* Use unit testing. PHPUnit and SimpleTest are the major xUnit systems in PHP.
* Be object oriented.
* Use version control. Any version control, just use it.
* If applicable, use a framework. Zend, CodeIgniter, Symfony, and CakePHP are the major ones.
* If no framework, at least use an ORM. Propel and Doctrine are the major ones.
* Document. Heavily. Use PHPdoc or similar.
There are a wealth of tools out there for PHP. Please use them, and write good maintainable code. You'll make everyone happier. | What are some of the best patterns and practices for PHP development? | [
"",
"php",
""
] |
I'm using openCV 1.1pre1 under Windows.
I have a network camera and I need to grab frames from openCV. That camera can stream a standard mpeg4 stream over RTSP or mjpeg over http.
I've seen many threads talking about using ffmpeg with openCV but I cannot make it work.
How I can grab frames from an IP camera with openCV?
Thanks
Andrea | rtsp protocol did not work for me.
mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).
Syntax found here:
<http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/>
I did not need to compile OpenCV with ffmpg support. | I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
```
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
```
**Update** You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
```
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:password@10.10.10.10:554/axis-media/media.amp
``` | OpenCV with Network Cameras | [
"",
"c++",
"windows",
"networking",
"opencv",
"ffmpeg",
""
] |
Iam trying to login to a https secured site using Apache commons httpclient.
Iam not getting any way to pass the certificate along with my httprequest , since I cannot find any such classes in HttpClient Package.
If anybody can guide me on where do I need to add the certificate handling?
Any package to do it?
Am open to ideas, any other way to do this in java. The platform must be only java however..
I have posted my code below.
```
import java.net.MalformedURLException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class TestHttpClient {
public static String formPostUrl ="https://login.findmespot.com/faces/welcome.jsp" ;
public static String LOGON_SITE = "login.findmespot.com";
static final int LOGON_PORT = 443;
public static void main(String[] args ) throws MalformedURLException
{
// AuthSSLProtocolSocketFactory ar= new AuthSSLProtocolSocketFactory(uRL, formPostUrl, uRL0, formPostUrl)
//Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(new URL("D:\key\my.keystore"), "4cKR!Z%p",new URL("D:\key\my.truststore"), "4cKR!Z%p"), 443);
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("login.findmespot.com",443,authhttps);
HttpMethod authGetmethod = new GetMethod("/index.jsp");
authGetmethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authGetmethod.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authGetmethod.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authGetmethod.setRequestHeader("Accept-Encoding","gzip,deflate");
authGetmethod.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authGetmethod.setRequestHeader("Keep-Alive","300");
authGetmethod.setRequestHeader("Connection","keep-alive");
authGetmethod.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp");
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
try
{
//send first request to capture cookie information
int status = client.executeMethod(authGetmethod);
BufferedReader br = new BufferedReader(new InputStreamReader(authGetmethod.getResponseBodyAsStream()));
String str ="";
String resultJsessionid="";
while((str=br.readLine())!=null )
{
if(str.indexOf("jsessionid=")!=-1)
{
//capture Session ID
resultJsessionid=getJsessionid(str);
break;
}
}
//release connection for final login request
authGetmethod.releaseConnection();
//Process the Initial Set of Cookies
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] initcookies = cookiespec.match(
LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
System.out.println("Initial set of cookies:");
if (initcookies.length == 0) {
System.out.println("None");
} else {
for (int i = 0; i < initcookies.length; i++) {
System.out.println("- " + initcookies[i].toString());
}
}
//try to login to the form
PostMethod authpost = new PostMethod("/faces/welcome.jsp?jessionid="+resultJsessionid );
// Set Headers
authpost.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authpost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authpost.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authpost.setRequestHeader("Accept-Encoding","gzip,deflate");
authpost.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authpost.setRequestHeader("Keep-Alive","300");
authpost.setRequestHeader("Connection","keep-alive");
authpost.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp");
// Prepare login parameters
NameValuePair inputtext1 = new NameValuePair("inputText1","TANGOFOUR");
NameValuePair inputtext5 = new NameValuePair("inputText5", "4cKR%21Z%25p");
NameValuePair oafF = new NameValuePair("oracle.adf.faces.FORM", "form11");
NameValuePair source = new NameValuePair("source","commandButton1");
NameValuePair event = new NameValuePair("event", "update");
NameValuePair partialTarget = new NameValuePair("partialTarget", "");
NameValuePair partial = new NameValuePair("partial", "true");
authpost.setRequestBody(
new NameValuePair[] {inputtext1,inputtext5,oafF,source,event,partialTarget,partial});
client.executeMethod(authpost);
System.out.println("Login form post: " + authpost.getStatusLine().toString());
// release any connection resources used by the method
authpost.releaseConnection();
// See if we got any cookies
// The only way of telling whether logon succeeded is
// by finding a session cookie
Cookie[] logoncookies = cookiespec.match(
LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
System.out.println("Logon cookies:");
if (logoncookies.length == 0) {
System.out.println("None");
} else {
for (int i = 0; i < logoncookies.length; i++) {
System.out.println("- " + logoncookies[i].toString());
}
}
System.out.println(resultJsessionid);
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
public static String getJsessionid(String responseText)
{
String jsession="";
int start_index= responseText.indexOf("jsessionid=");
if(start_index!=-1)
{
jsession= responseText.substring(start_index+11);
}
int last_index=jsession.indexOf("\"");
if(last_index!=-1)
jsession=jsession.substring(0,last_index);
return jsession;
}
}
``` | Ok finally I did some digging and found out the solution myself,
I am pasting the working code to log in to a SSL powered https site using Http client 3.1 . Looking for any feedback , if there is a better way to this??
```
import java.net.MalformedURLException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class TestHttpClient {
public static String formPostUrl ="https://login.findmespot.com/faces/welcome.jsp" ;
public static String LOGON_SITE = "login.findmespot.com";
static final int LOGON_PORT = 443;
public static void main(String[] args ) throws MalformedURLException
{
String nextHref="";
HttpClient client = new HttpClient();
HttpMethod authGetmethod = new GetMethod("https://login.findmespot.com/index.jsp");
authGetmethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authGetmethod.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authGetmethod.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authGetmethod.setRequestHeader("Accept-Encoding","gzip,deflate");
authGetmethod.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authGetmethod.setRequestHeader("Keep-Alive","300");
authGetmethod.setRequestHeader("Connection","keep-alive");
//authGetmethod.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp");
try
{
//send first request to capture cookie information
int status = client.executeMethod(authGetmethod);
BufferedReader br = new BufferedReader(new InputStreamReader(authGetmethod.getResponseBodyAsStream()));
String str ="";
String resultJsessionid="";
while((str=br.readLine())!=null )
{
if(str.indexOf("jsessionid=")!=-1)
{
//capture Session ID
resultJsessionid=getJsessionid(str);
break;
}
}
//release connection for final login request
authGetmethod.releaseConnection();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
Cookie[] cookies = client.getState().getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
System.err.println(
"Cookie: " + cookie.getName() +
", Value: " + cookie.getValue() +
", IsPersistent?: " + cookie.isPersistent() +
", Expiry Date: " + cookie.getExpiryDate() +
", Comment: " + cookie.getComment());
//PostMethod authpost = new PostMethod("https://login.findmespot.com/faces/welcome.jsp?jessionid="+resultJsessionid );
PostMethod authpost = new PostMethod("https://login.findmespot.com/faces/welcome.jsp");
// Set Headers
authpost.setRequestHeader("http.Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authpost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authpost.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authpost.setRequestHeader("Accept-Encoding","gzip,deflate");
authpost.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authpost.setRequestHeader("Keep-Alive","300");
authpost.setRequestHeader("Connection","keep-alive");
authpost.setRequestHeader("Referer","https://login.findmespot.com/faces/index.jsp");
// Prepare login parameters
NameValuePair inputtext1 = new NameValuePair("inputText1","TANGOFOUR");
NameValuePair inputtext5 = new NameValuePair("inputText5", "~CcxpqFR");
NameValuePair oafF = new NameValuePair("oracle.adf.faces.FORM", "form11");
NameValuePair source = new NameValuePair("source","commandButton1");
NameValuePair event = new NameValuePair("event", "update");
NameValuePair partialTarget = new NameValuePair("partialTarget", "");
NameValuePair partial = new NameValuePair("partial", "true");
authpost.setRequestBody(
new NameValuePair[] {inputtext1,inputtext5,oafF,source,event,partialTarget,partial});
client.executeMethod(authpost);
System.out.println("Login form post: " + authpost.getStatusLine().toString());
// release any connection resources used by the method
String readLine;
br = new BufferedReader(new InputStreamReader(authpost.getResponseBodyAsStream()));
while(((readLine = br.readLine()) != null)) {
System.out.println(readLine);
nextHref=getNexthref(readLine);
}
authpost.releaseConnection();
Cookie[] cookies1 = client.getState().getCookies();
for (int i1 = 0; i < cookies1.length; i++) {
Cookie cookie1 = cookies1[i1];
System.err.println(
"Cookie: " + cookie1.getName() +
", Value: " + cookie1.getValue() +
", IsPersistent?: " + cookie1.isPersistent() +
", Expiry Date: " + cookie1.getExpiryDate() +
", Comment: " + cookie1.getComment());
HttpMethod authGetmethodNext = new GetMethod("https://login.findmespot.com"+nextHref);
authGetmethodNext.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authGetmethodNext.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authGetmethodNext.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authGetmethodNext.setRequestHeader("Accept-Encoding","gzip,deflate");
authGetmethodNext.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authGetmethodNext.setRequestHeader("Keep-Alive","300");
authGetmethodNext.setRequestHeader("Connection","keep-alive");
authGetmethodNext.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp");
client.executeMethod(authGetmethodNext);
System.out.println("Login form post: " + authGetmethodNext.getStatusLine().toString());
PostMethod authpost1 = new PostMethod("https://login.findmespot.com/faces/history.jsp");
// Set Headers
authpost1.setRequestHeader("http.Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9");
authpost1.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
authpost1.setRequestHeader("Accept-Language","en-us,en;q=0.5");
authpost1.setRequestHeader("Accept-Encoding","gzip,deflate");
authpost1.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
authpost1.setRequestHeader("Keep-Alive","300");
authpost1.setRequestHeader("Connection","keep-alive");
authpost1.setRequestHeader("Referer","Referer: https://login.findmespot.com/faces/trackerunit.jsp");
client.executeMethod(authpost1);
br = new BufferedReader(new InputStreamReader(authpost1.getResponseBodyAsStream()));
while(((readLine = br.readLine()) != null))
{
System.out.println(readLine);
}
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
public static String getJsessionid(String responseText) /// retu
{
String jsession="";
int start_index= responseText.indexOf("jsessionid=");
if(start_index!=-1)
{
jsession= responseText.substring(start_index+11);
}
int last_index=jsession.indexOf("\"");
if(last_index!=-1)
jsession=jsession.substring(0,last_index);
return jsession;
}
public static String getNexthref(String inputhref)
{
String result_href="";
int start_index=inputhref.indexOf("href='");
if(start_index!=-1)
{
result_href=inputhref.substring(start_index+6);
}
int last_index=result_href.indexOf("'");
if(last_index!=-1)
result_href=result_href.substring(0,last_index);
return result_href;
}
}
``` | I would ask you what version of Java you were using because based on something that happened to me a long time ago: Java has it's own SSL cert which comes as part of the library. After a while, this cert goes out of date. The fix was to update to a later version of Java. Mind you, this was a long time ago, but I think this could be your issue.
[See also](http://hc.apache.org/httpclient-3.x/sslguide.html). (again, highly dependent on versions of java and httpclient) | Issue with trying to Login to a https secure using apache commons httpclient class | [
"",
"java",
"apache-commons-httpclient",
""
] |
I'm new to C#.Till this moment I used to make every global variable - public static.All my methods are public static so I can access them from other classes.
I read on SO that the less public static methods I have,the better.So I rewrote my applications by putting all the code in one class - the form class.Now all my methods are private and there's no static method.
My question: What should I do,keeping everything in the form class is dump in my opinion.
When should I use public,when private and when static private/public?
I get the public methods as a 'cons' ,because they can be decompiled,but I doubt that.My public methods can be decompiled too.What is so 'private' in a private method?
**EDIT**: I'm not asking how to prevent my program to be decompiled,I'm asking whether I should use static,private and public.And also : Is there are problem in putting all the code in the form class so I dont have to use public methods? | private is for class members that you want only access within the class of the body, and in C# members are default set to private unless specified different
examples of when to use private:
```
class Account
{
private int pin = 1090;
public int Pin
{
get { return pin; }
}
}
```
public on the other hand is the opposite, there are no restrictions with accessing public members, so when things that don't matter with the user having access to should be public.
static on the other hand has no relation to the two, because it doesn't deal with permission to methods, static on the other hand is a constant or type declaration. If the word static is applied to the class then every member in the class must be declared static.
examples of when to use static:
```
static int birth_year= 1985
```
[Modifiers in C# Reference](http://msdn.microsoft.com/en-us/library/6tcf2h8w.aspx) will give you more detail of all modifiers in C# and examples of how they should be used | Everything should be private unless proven otherwise.
The difference between public and private is between what is supposed to be kept compatible and what is not supposed to be kept compatible, what is supposed to be interesting to the world and what is not supposed to be its business.
When you declare something public, the class (and consequently the object) is making a strong statement: this is my visible interface, there are many other like this, but this is mine.
The public interface is a contractual agreement that your class is exporting to the rest of the world (whatever that means) about what it can do. If you modify the public interface, you risk breaking the contract that the rest of the world is assuming about the class.
On the other hand, private stuff is internal to the class. It supports functionality that the class must use to do its job while carrying the object state around (if it's a method) or keeping its internal state (if it's a variable). You are free to hack and tinker the class private stuff as much as you want, without breaking the interface contract, meaning that this gives you wide freedom for refactoring (of the internal data representation, for example, for efficiency). Private stuff is not part of the interface.
Protected is something that involves the openness to reimplementation. Avoid, if you can, deeply nested inheritances. You risk making things very difficult to handle, as your reimplementation class can screw the base class.
Technically, a class should declare an interface (public) and an implementation (private). The interface should not have code at all, just delegate to the private "implementation" logic. This is why in Java and C# you have interface statement, which formalizes the pure abstract class concept in C++.
Static is something that resides logically in the realm of your class but does not depend on the state of the class itself. It should be used sparingly when a design pattern dictates it (e.g., singleton, factory method). | When should I use public/private/static methods? | [
"",
"c#",
"vb.net",
""
] |
What HTTP framework should I use for a simple application with implied scalability, priferable Pythonic? I would like to be able to smoothly add new features to my app when it has already been deployed. | [Web.py](http://www.webpy.org.)
It might look too simple, but it's a joy to use.
It can be deployed on google appengine. Should scale pretty well. Can be used with any [WSGI](http://www.wsgi.org.) server. | I'm a big fan of [Pylons](http://pylonshq.com). It behaves just like a framework should; not excessive on the magic and contains many good components that you can pick-and-choose that help you hit the ground running. It's small and easy to deploy, and requires minimal boilerplate or other syntactic cruft. Scalability seems pretty good -- I've not run into any issues, and major parts of Reddit utilize libraries from Pylons. | What HTTP framework to use for simple but scalable app? | [
"",
"python",
"http",
"frameworks",
"scalability",
""
] |
In Python, the assignment operator can unpack a list or a tuple into variables, like this:
```
l = (1, 2)
a, b = l # Here goes auto unpack
```
But I need to specify exactly the same amount of names to the left as an item count in the list to the right. But sometimes I don't know the size of the list to the right, for example, if I use split().
Example:
```
a, b = "length=25".split("=") # This will result in a="length" and b=25
```
But the following code will lead to an error:
```
a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item
```
Is it possible to somehow unpack the list in the example above so I can get a = "DEFAULT\_LENGTH" and b equals to `None` or not set? A straightforward way looks kind of long:
```
a = b = None
if "=" in string :
a, b = string.split("=")
else :
a = string
``` | ```
# this will result in a="length" and b="25"
a, b = "length=25".partition("=")[::2]
# this will result in a="DEFAULT_LENGTH" and b=""
a, b = "DEFAULT_LENGTH".partition("=")[::2]
``` | This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the [extended tuple unpacking](http://www.python.org/dev/peps/pep-3132/) introduced there allows you to do things like:
```
>>> a, *b = "length=25".split("=")
>>> a,b
("length", ['25'])
>>> a, *b = "DEFAULT_LENGTH".split("=")
>>> a,b
("DEFAULT_LENGTH", [])
```
I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with `*`, and get them as a (possibly empty) list.
Partition is probably the best solution for what you're doing however. | Partial list unpack in Python | [
"",
"python",
""
] |
I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this?
```
import csv
def results_csv(self):
data = ['895', '898', '897']
return data
``` | To tell the browser the type of content you're giving it, you need to set the `Content-type` header to 'text/csv'. In your Pylons function, the following should do the job:
`response.headers['Content-type'] = 'text/csv'` | PAG is correct, but furthermore if you want to suggest a name for the downloaded file you can also set `response.headers['Content-disposition'] = 'attachment; filename=suggest.csv'` | How do I return a CSV from a Pylons app? | [
"",
"python",
"csv",
"pylons",
""
] |
### Duplicate:
> [Submitting data from textarea by hitting “Enter”.](https://stackoverflow.com/questions/789701/submitting-data-from-textarea-by-hitting-enter)
---
I've got a textarea and a submit button:
```
<textarea id="chat"></textarea>
<input type="submit" value="Submit" onclick="send_msg();">
```
The value of the of the texarea is submitted when Enter is hit:
```
textarea.onkeyup = function(e) {
alert(e.keyCode);
e = e || window.event;
if (e.keyCode === 13) {
send_msg();
}
return true;
}
```
Problem is to make the textarea submit its value prior to letting the cursor to jump to the next line. How's it possible to do that? | The trick is to stop the browser from executing the default behaviour on key down and key up. To do that, simply `return false` in your onkeypress/onkeyrelease handlers when you detect keycode 13. | One issue this ignores is users running input method (editors) -- eg. non-latin text entry. The IME i am familiar with is the Kotoeri Hiragana IM on OSX, but there are numerous others both for japanese (Kotoeri alone has multiple different input modes, and there's at least one other major one called ATOK), in addition to modes for hangul, traditional and simplified chinese, as well as numerous other less well known languages. And these input methods exist on all major platforms (esp. Win, Mac, and Linux).
The problem that they introduce from the point of view of code similar to what you're attempting is that the exact physical keypresses does not necessarily correspond to the actual input that the user is entering.
For example typing the sequence of characters `toukyou<enter>` under hiragana by default will produce the string `とうきょう`, note that there is no `<enter>` in the resultant text because enter confirms the composed text. But in addition to this the actual sequence of characters that appears changes as the input is typed:
```
t // t
と // to
とう // tou
とうk // touk
とうky // touky
とうきょ // toukyo
とうきょう // toukyou
```
If memory serves when i implemented this in webkit it was necessary to make the keyCode be 229 on keyDown for all keys typed in an IME (for compat with IE) -- but i cannot recall what the behaviour of keyUp is.
It's also worth noting that in some IMEs you won't necessarily receive keydowns, keypress, or keyup. Or you will receive multiple. Or they're all sent together at the end of input.
In general this is a very... unclean... portion of the DOM event implementations currently. | How might I implement immediate text submission when the enter key is pressed in a textarea? | [
"",
"javascript",
"input",
"textarea",
""
] |
In javascript, what are the pro's and con's of encoding an onclick event in the DOM and in the HTML itself?
Which, if either, is better than the other and why? | Your question almost answers itself when you refer to "the HTML itself".
JavaScript is not HTML -- Keeping the HTML and the JavaScript in separate locations is a benefit all by itself. Makes it easier to (humanly) read the HTML, and keeping all the JS in the same location makes it easier to track everything down all at once. | It is better to write your Javascript in Javascript, as OtherMichael says. It is even better to use proper DOM events (`addEventListener` and `attachEvent`) rather than `on_____`, in order to avoid conflicts and allow multiple callbacks for the same event. | onClick w/ DOM vs. onClick hardcoded | [
"",
"javascript",
"dom",
""
] |
In jQuery, the `map` and `each` functions seem to do the same thing. Are there any practical differences between the two? When would you choose to use one instead of the other? | The [`each`](http://docs.jquery.com/Utilities/jQuery.each) method is meant to be an immutable iterator, where as the [`map`](http://docs.jquery.com/Utilities/jQuery.map) method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.
Another important thing to note is that the `each` function returns the original array while the `map` function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.
For example:
```
var items = [1,2,3,4];
$.each(items, function() {
alert('this is ' + this);
});
var newItems = $.map(items, function(i) {
return i + 1;
});
// newItems is [2,3,4,5]
```
You can also use the map function to remove an item from an array. For example:
```
var items = [0,1,2,3,4,5,6,7,8,9];
var itemsLessThanEqualFive = $.map(items, function(i) {
// removes all items > 5
if (i > 5)
return null;
return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]
```
You'll also note that the `this` is not mapped in the `map` function. You will have to supply the first parameter in the callback (eg we used `i` above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.
```
map(arr, function(elem, index) {});
// versus
each(arr, function(index, elem) {});
``` | **1: The arguments to the callback functions are reversed.**
[`.each()`](http://api.jquery.com/each/)'s, [`$.each()`](http://api.jquery.com/jquery.each/)'s, and [`.map()`](http://api.jquery.com/map/)'s callback function take the index first, and then the element
```
function (index, element)
```
[`$.map()`](http://api.jquery.com/jquery.map/)'s callback has the same arguments, but reversed
```
function (element, index)
```
**2: [`.each()`](http://api.jquery.com/each/), [`$.each()`](http://api.jquery.com/jquery.each/), and [`.map()`](http://api.jquery.com/map/) do something special with `this`**
`each()` calls the function in such a way that `this` points to the current element. In most cases, you don't even need the two arguments in the callback function.
```
function shout() { alert(this + '!') }
result = $.each(['lions', 'tigers', 'bears'], shout)
// result == ['lions', 'tigers', 'bears']
```
For [`$.map()`](http://api.jquery.com/jquery.map/) the `this` variable refers to the global window object.
**3: `map()` does something special with the callback's return value**
`map()` calls the function on each element, and stores the result in a new array, which it returns. You usually only need to use the first argument in the callback function.
```
function shout(el) { return el + '!' }
result = $.map(['lions', 'tigers', 'bears'], shout)
// result == ['lions!', 'tigers!', 'bears!']
``` | jQuery map vs. each | [
"",
"javascript",
"jquery",
""
] |
I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time empty or null.
I am trying to write code that checks if this field isnull. The logic behind this is:
If the field "Additional" contains text then display the info otherwise hide the field.
I have tried:
```
if (myReader["Additional"] != null)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
```
The above code gives me this error:
Exception Details: **System.IndexOutOfRangeException: Additional**
Any help would be greatly appreciated...
---
### See Also:
> [Check for column name in a SqlDataReader object](https://stackoverflow.com/questions/373230/check-for-column-name-in-a-sqldatareader-object) | ```
if (myReader["Additional"] != DBNull.Value)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
``` | ```
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
``` | how to check if a datareader is null or empty | [
"",
"c#",
"null",
"sqldatareader",
""
] |
Google Maps just made the API exactly like the real thing. So now I want the map to display the hybrid map by default, I looked all over [Google's Documentation](http://code.google.com/apis/maps/documentation/controls.html#DefaultUI), but I can't seem to find a way to do this.
Thanks in advance! | Did you try the [constructor](http://code.google.com/apis/maps/documentation/reference.html#GMapOptions)?
```
map = new GMap2(document.getElementById("map_canvas"), { mapTypes:[G_HYBRID_MAP] });
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
``` | you can also pass the map-type with
```
map.setCenter(point, zoom, G_HYBRID_MAP);
``` | How to make the hybrid the default map on Google maps API? | [
"",
"javascript",
"google-maps",
""
] |
Can you please let me know if my code is correct? I'm studying for my test in two hours so I dont really have time to write an application to test it.
Question is: if I have a JLabel with a number as its label. simply a label that says 34 for example. I want to extract the number from the label. but i need to handle exceptions, i.e it's not a number, it can be a letter.
would my code below handle the exception correctly?
```
JLabel label = new JLabel("34");
int extracted;
```
this is what i would do
```
try{
extracted = Integer.parseInt(extracted.getText());
System.out.println("the number was: "+ extracted);
}
catch(IOException exception){
System.out.println(label.getText() + " is not a number");
}
``` | Close, but catching an IOException won't work because that exception type is not thrown by the parseInt() method. Try catching a NumberFormatException instead:
```
try{
extracted = Integer.parseInt(extracted.getText());
System.out.println("the number was: "+ extracted);
} catch(NumberFormatException exception) {
System.out.println(label.getText() + " is not a number");
}
``` | I would check the documentation for [Integer.parseInt()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String))
Furthermore, I'd strongly recommend setting up a test project in whatever IDE you use so you can test this stuff yourself with a rapid turnaround! Even if it's a vim/javac+make script. | Simple exception handling in Java | [
"",
"java",
"exception",
""
] |
If I create a set of actions to be used in a JFace application and I assign images to those actions, those images show up in both the toolbar (where I want them) and in the menus (where I don't want them).
Other than supplying two completely separate sets of actions (which eliminates part of the point of actions in the first place), how can I arrange to have those images displayed ONLY in the toolbar, and have the menus display only text? | I ended up essentially duplicating the actions, making pairs, one with an image, one without, thereby eliminating the benefit of actions in the first place (sigh). On the other hand, since each action does just invoke a single method in the controller to perform the work, it's not too insidious and grouping the pairs together makes it reasonably clear what's going on. | I ran into this problem as well (except I wanted different text for the toolbar and menu.) I ended up using the same action, but two different instances of it.
```
// Use this one in the menu
Action a = new Action();
// Use this one in the toolbar
Action a2 = new Action();
a2.setImageDescriptor(img);
```
Alternately, you could store the image descriptor in the action for the toolbar version and set it to null for the menu version. | How can I disable all images for an JFace menu but leave them enabled in the toolbar | [
"",
"java",
"swt",
"jface",
""
] |
I am trying to implement some sort of MVC in Java. Actually it's more of a MVP but this doesn't really matter to my problem.
Following situation:
I've got a GUI, made with Netbeans (because of the better GUIeditor) which is updated and changed frequently.
As my main project is easier to maintain in Eclipse I chose to import the Netbeans project into Eclipse as a separate project. So here I am with a project "`App`" containing the controller and the model package and a project "`GUI`" containing the view package.
The problem is that the pattern I am following along has a cyclic dependecy between the view and the controller. Whenever the view changes, the controller gets notified decides which data to get from the model and then makes the changes to the view.
When I add `App` to the build path of `GUI` and the other way round, I will end up with this error message "A cycle was detected in the build path of project 'GUI'". *I mean that's true, this cycle is already in my design.*
Currently at startup I register a view to its controller in the following way (this is no real code, I am trying to shorten it)
```
package view;
import controller.*;
class viewA{
...
public viewA() {
controllerA.register(this);
}
...
}
package controller;
import view.*;
class controllerA implements SomeListener{
...
protected viewA[] registeredViews;
public static register(viewA interestedView){
arrayPush(registeredViews,interestedView);
interestedView.addSomeListener(this)
}
...
}
```
So you see the connection is made by passing a reference to the controller and then registering a listener onto this view. The problem is: if I don't have the `GUI` project in `App`'s buildpath the import can't be resolved, same happens for not having `App` in `GUI`'s build path.
I'd like to keep this project structure and also stick to my MVC architecture. How can I work around it? What are your suggestions? | You have your listeners backwards from the usual way - normally, the controller has the initiative. It creates the view object and registers itself as a listener for view events.
Additionally, the listener type should be an interface defined in the View project. Then, the Contoller implements that interface and the view does not have to know about the concrete controller classes. Cycle resolved. You can do this in your "reverse" setup too, of course. | Circular dependencies between classes is not a problem per se (its a feature).
However, you should check your design and justify the dependencies.
Eclipse projects are perhaps a bit overused. Unfortunately, Eclipse doesn't really handle having many (10+ or so ) projects, and the othervise excellent partial compiler gets slower and the compiling process seems to get more buggy.
In several development projects i've been involved in, merging and reducing the number of projects has led to shorter build times and less build problems.
In inhouse applications, large and small, and if it is likely that everyone working on the code will have access to all the code, then there is actually little point in dividing the code between projects.
If you are worried about keeping track of the dependencies, it is possible to enforce rules for dependencies between packages.
Its quite common to have a "business layer" project, a "data" layer project and a gui project for each "module" in a large application, and then you are bound to end up with a few circular dependencies if you are not creating artifical "interface projects" etc.
Before you go to a great length to remove dependecies, consider if the dependcies in fact are real and the projects maybe should be merged instead.
Remember that abstract concepts like "modules" or "layers" does not neccesarily mean that you have to have matching projects or folders (or whatever.) Eclipse projects are a groups of files that you work on, nothing more or less really.
You might want to read about [the-mythical-business-layer](http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx). | Cyclic dependency of two eclipse projects | [
"",
"java",
"eclipse",
"architecture",
"classpath",
""
] |
I have class with a forwarding method `foo`:
```
void foo( Concrete c, String s ) { c.bar( s ); }
```
I wish to test whether `foo` does, in fact, forward. Unfortunately for me, `Concrete` is a class in a third-party library, and is a concrete type, not an interface. Thus I must use `ClassImposteriser` in JMock to mock `Concrete`, so in my test case, I do this:
```
@Test
public final void testFoo() {
Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
final Concrete c = context.mock(Concrete.class);
final String s = "xxx" ;
// expectations
context.checking(new Expectations() {{
oneOf (c).bar(s); // exception gets thrown from here
}});
new ClassUnderTest.foo( c, s );
context.assertIsSatisfied();
```
}
Unfortunately, `Concrete.bar` in turn calls a method that throws. That method is final, so I can't override it. Further, even if I comment out the line `new ClassUnderTest.foo( c, s );`, the exception is thrown when JMock sets up exceptions, not when `foo` is called.
So how can I test that method `ClassUnderTest.foo` does forward to `Concrete.bar`?
Edit:
Yes, bar is final.
My solution, which is *not* a general one, was to use a "Tester" class in the third-party library to correctly set up `Concrete`. | It's not clear from the question text if Concrete.bar() is final or if Concrete.somethingElse() is final and called from Concrete.bar().
If Concrete.bar() **is not final**, create a hand-written stub for Concrete like this:
```
public class ConcreteStub extends Concrete
{
public int numCallsToBar = 0;
@Override
public void bar(String s) { numCallsToBar++; }
}
```
and in your test code:
```
ConcreteStub c = new ConcreteStub();
foo(c,"abc");
assertEquals(1,c.numCallsToBar);
```
If Concrete.bar() **is final**, it is more complicated and the answer depends on the complexity of Concrete and your project's use of the Concrete class. If your use of Concrete is simple enough, I would consider wrapping Concrete in an interface ([Adapter Pattern](http://en.wikipedia.org/wiki/Adapter_pattern)) that you can then mock out easier.
Benefits to the Adapter Pattern solution: Possibly clarify behavior by naming interface after your project's use of Concrete. Easier to test.
Drawbacks to the Adapter Pattern solution: Introduces more classes with possibly little benefit to production code. I don't know what Concrete does and it may not be practical to wrap Concrete in an interface. | See <http://www.jmock.org/mocking-classes.html> for info about mocking classes and how to bypass final limitations. | Testing a concrete third-party class with JMock | [
"",
"java",
"unit-testing",
"jmock",
""
] |
I write:
```
CREATE TABLE Person (
name CHAR(10),
ssn INTEGER);
```
and save it to a file "a.sql".
If I then run it by typing "@a" in the SQL\*Plus command prompt, it will tell me that the line starting with "ssn" is not recognized as a command, and is ignored.
From what I gather, it seems that sqlplus terminates a command if it encounters multiple newline characters in a row. Is this an accurate statement? If so, does anyone know if this is necessary/ why it chooses to do this? | I don't know about the why, but a completely blank line terminates a command in SQL\*Plus.
Quote from [the SQL\*Plus docs](http://download.oracle.com/docs/cd/A91202_01/901_doc/server.901/a88827/ch24.htm) :
**Ending a SQL Command**:
You can end a SQL command in one of three ways:
* with a semicolon (;)
* with a slash (/) on a line by itself
* with a blank line
You can also change how blank lines are treated with SET SQLBLANKLINES
> **SQLBL[ANKLINES] {ON|OFF}**
>
> Controls whether SQL\*Plus allows blank lines within a SQL command or script. ON interprets blank lines and new lines as part of a SQL command or script. OFF, the default value, does not allow blank lines or new lines in a SQL command or script or script.
>
> Enter the BLOCKTERMINATOR to stop SQL command entry without running the SQL command. Enter the SQLTERMINATOR character to stop SQL command entry and run the SQL statement. | By default, SQLPlus does terminate (but not execute) a statement when a blank line is entered. It has always done this. It probably seemed like a good idea in the days before screen editors and query tools.
You can change that default behaviour with
set SQLBLANKLINES on
In which case you'd have to enter a line with just a full stop to terminate (but not execute) a statement. | Why doesn't ORACLE allow consecutive newline characters in commands? | [
"",
"sql",
"oracle",
"language-design",
"whitespace",
"sqlplus",
""
] |
I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?
Python:
```
class MyClass:
def __init__(self):
x = MyClass()
```
Ruby:
```
class AnotherClass
def initialize()
end
end
x = AnotherClass.new()
```
I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"? | Actually in Python the constructor is [`__new__()`](http://docs.python.org/reference/datamodel.html#object.__new__), while [`__init__()`](http://docs.python.org/reference/datamodel.html#object.__init__) is instance initializer.
`__new__()` is static class method, thus it has to be called first, as a first parameter (usually named `cls` or `klass`) it gets the class . It creates object instance, which is then passed to `__init__()` as first parameter (usually named `self`), along with all the rest of `__new__`'s parameters. | When you are creating an object of a class, you are doing more than just initializing it. You are allocating the memory for it, then initializing it, then returning it.
Note also that in Ruby, `new()` is a class method, while `initialize()` is an instance method. If you simply overrode `new()`, you would have to create the object first, then operate on that object, and return it, rather than the simpler `initialize()` where you can just refer to `self`, as the object has already been created for you by the built-in `new()` (or in Ruby, leave `self` off as it's implied).
In Objective-C, you can actually see what's going on a little more clearly (but more verbosely) because you need to do the allocation and initialization separately, since Objective-C can't pass argument lists from the allocation method to the initialization one:
```
[[MyClass alloc] initWithFoo: 1 bar: 2];
``` | Is there any particular reason why this syntax is used for instantiating a class? | [
"",
"python",
"ruby",
"constructor",
""
] |
Never seen this one before.
```
WebService.Implementation imp = new WebService.Implementation();
WebService.ImplementationRequest req = new WebService.ImplementationRequest();
return imp.GetValue(req);
```
The object that imp returns is not null. It's returning an ImplementationResponse, as expected. But all of the fields in that object are null. Which is not expected. The WebService, currently, just returns some constant dummy data. We've tested this on another developer's machine, works just fine.
I suppose I should also note that the WebService should throw an exception if I pass null into the GetValue method. It doesn't. Not for me.
Any idea what could be wrong with my environment that could make a WebService return an object, but make every value in that object null? And somehow 'magically' return this mystery object when it should be throwing an exception? | That usually happens when there's a discrepancy between the generated code and the xml being returned by the web service so it cannot be deserialized.
Grab the wsdl again, regenerate all the proxy classes and try again. Make sure you are sending the correct dummy data.
Update:
This used to happen to me a lot because the web services weren't managed by my team and we wouldn't get any notice of changes made to the service. We ended up intercepting the soap messages in the web service pipeline for debugging. [Here](http://msdn.microsoft.com/en-us/magazine/cc164007.aspx)'s a great resource to get you on your way.
You don't need to change anything in the pipeline, just grab the soap messages and save them so you have debug later. Most of the times it turned out to be just that, a change in the contract. Other times we wouldn't have a contract so there was no way of knowing of changes without catching the envelopes.
Anyway, even if it's not your problem I think it's a good thing to have. | Are the fields marked with < DataMember()> attributes as they won't serialize otherwise?
```
<DataMember()> _
Public Property SomeField() As String
Get
Return m_strSomeField
End Get
Private Set(ByVal value As String)
m_strSomeField= value
End Set
End Property
```
Also, consider using trace viewer to analyse the messages sent between the client and server. For info see:
<https://stackoverflow.com/questions/560370/handling-wcf-proxy-null-return-issue> | Web Service returning object with null fields | [
"",
"c#",
".net",
"wcf",
"web-services",
""
] |
I have a csv file with 350,000 rows, each row has about 150 columns.
What would be the best way to insert these rows into SQL Server using ADO.Net?
The way I've usually done it is to create the SQL statement manually. I was wondering if there is any way I can code it to simply insert the entire datatable into SQL Server? Or some short-cut like this.
By the way I already tried doing this with SSIS, but there are a few data clean-up issues which I can handle with C# but not so easily with SSIS. The data started as XML, but I changed it to CSV for simplicity. | Make a class "CsvDataReader" that implements IDataReader. Just implement Read(), GetValue(int i), Dispose() and the constructor : you can leave the rest throwing NotImplementedException if you want, because SqlBulkCopy won't call them. Use read to handle the read of each line and GetValue to read the i'th value in the line.
Then pass it to the SqlBulkCopy with the appropriate column mappings you want.
I get about 30000 records/per sec insert speed with that method.
If you have control of the source file format, make it tab delimited as it's easier to parse than CSV.
Edit : <http://www.codeproject.com/KB/database/CsvReader.aspx> - tx Mark Gravell. | SqlBulkCopy if it's available. Here is a very helpful explanation of using [SqlBulkCopy in ADO.NET 2.0 with C#](http://dotnetslackers.com/articles/ado_net/SqlBulkCopy_in_ADO_NET_2_0.aspx)
I think you can load your XML directly into a DataSet and then map your SqlBulkCopy to the database and the DataSet. | How to best insert 350,000 rows with ADO.Net | [
"",
"c#",
".net",
"ado.net",
"csv",
"etl",
""
] |
Given two DateTimes in C#, how can I display the difference in years and months?
I can do basic arithmatic on the timespan that comes from a simple subtraction but this won't take into account the differing lengths of months, leap years etc.
Thanks for any help. | Because the underlying representation is measured in 100-nanosecond ticks since 12:00 midnight, January 1, 1 A.D., a subtraction will handle leap years etc. quite correctly:
```
DateTime date1 = ...
DateTime date2 = ...
// date2 must be after date1
TimeSpan difference = date2.Subtract(date1);
DateTime age=new DateTime(tsAge.Ticks);
int years = age.Years - 1;
int months = age.Month - 1;
Console.WriteLine("{0}Y, {1}M", years, months);
``` | FWIW here's what i've ended up with
```
DateTime servicelength = new DateTime(DateTime.Now.Subtract(employee.StartDate).Ticks);
LengthOfService.Text = String.Format("{0}Y {1}M", servicelength.Year - 1, servicelength.Month - 1);
``` | How to display difference between two dates as 00Y 00M | [
"",
"c#",
"datetime",
""
] |
I tried to split data as below, but the error "dat.split is not a function" displays. Anyone know how can I solve this problem?
```
var dat = new Date("2009/12/12");
var r = dat.split('/');
``` | You can't `split()` a Date - you can `split()` a String, though:
```
var dat = "2009/12/12";
var r = dat.split('/');
```
returns:
```
["2009", "12", "12"]
```
To do the equivalent with a date, use something like this:
```
var dat = new Date();
var r = [dat.getFullYear(), dat.getMonth() + 1, dat.getDate()];
```
returns:
```
[2009, 4, 17]
``` | try
```
dat.toString().split('/');
```
but this solution is locale dependent | Splitting strings in JavaScript | [
"",
"javascript",
"string",
""
] |
A while back a post by Jon Skeet planted the idea in my head of building a `CompiledFormatter` class, for using in a loop instead of `String.Format()` and similar.
The idea is the portion of a call to `String.Format()` spent parsing the format string is overhead; we *should* be able to improve performance by moving that code outside of the loop. The trick, of course, is the new code should *exactly* match the `String.Format()` behavior.
This week I finally did it. I went through using the [.Net framework source provided by Microsoft](http://weblogs.asp.net/scottgu/archive/2008/01/16/net-framework-library-source-code-now-available.aspx) to do a direct adaption of their parser (it turns out `String.Format()` actually farms the work to `StringBuilder.AppendFormat()`). The code I came up with works, in that my results are accurate within my (admittedly limited) test data.
Unfortunately, I still have one problem: performance. In my initial tests the performance of my code closely matches that of the normal `String.Format()`. There's no improvement at all; it's even consistently a few milliseconds slower. At least it's still in the same order (ie: the amount slower doesn't increase; it stays within a few milliseconds even as the test set grows), but I was hoping for something better.
It's possible that the internal calls to `StringBuilder.Append()` are what actually drive the performance, but I'd like to see if the smart people here can help improve things.
Here is the relevant portion:
```
private class FormatItem
{
public int index; //index of item in the argument list. -1 means it's a literal from the original format string
public char[] value; //literal data from original format string
public string format; //simple format to use with supplied argument (ie: {0:X} for Hex
// for fixed-width format (examples below)
public int width; // {0,7} means it should be at least 7 characters
public bool justify; // {0,-7} would use opposite alignment
}
//this data is all populated by the constructor
private List<FormatItem> parts = new List<FormatItem>();
private int baseSize = 0;
private string format;
private IFormatProvider formatProvider = null;
private ICustomFormatter customFormatter = null;
// the code in here very closely matches the code in the String.Format/StringBuilder.AppendFormat methods.
// Could it be faster?
public String Format(params Object[] args)
{
if (format == null || args == null)
throw new ArgumentNullException((format == null) ? "format" : "args");
var sb = new StringBuilder(baseSize);
foreach (FormatItem fi in parts)
{
if (fi.index < 0)
sb.Append(fi.value);
else
{
//if (fi.index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
if (fi.index >= args.Length) throw new FormatException("Format_IndexOutOfRange");
object arg = args[fi.index];
string s = null;
if (customFormatter != null)
{
s = customFormatter.Format(fi.format, arg, formatProvider);
}
if (s == null)
{
if (arg is IFormattable)
{
s = ((IFormattable)arg).ToString(fi.format, formatProvider);
}
else if (arg != null)
{
s = arg.ToString();
}
}
if (s == null) s = String.Empty;
int pad = fi.width - s.Length;
if (!fi.justify && pad > 0) sb.Append(' ', pad);
sb.Append(s);
if (fi.justify && pad > 0) sb.Append(' ', pad);
}
}
return sb.ToString();
}
//alternate implementation (for comparative testing)
// my own test call String.Format() separately: I don't use this. But it's useful to see
// how my format method fits.
public string OriginalFormat(params Object[] args)
{
return String.Format(formatProvider, format, args);
}
```
#### Additional notes:
I'm wary of providing the source code for my constructor, because I'm not sure of the licensing implications from my reliance on the original .Net implementation. However, anyone who wants to test this can just make the relevant private data public and assign values that mimic a particular format string.
Also, I'm very open to changing the `FormatInfo` class and even the `parts` List if anyone has a suggestion that could improve the build time. Since my primary concern is sequential iteration time from front to end maybe a `LinkedList` would fare better?
### [Update]:
Hmm... something else I can try is adjusting my tests. My benchmarks were fairly simple: composing names to a `"{lastname}, {firstname}"` format and composing formatted phone numbers from the area code, prefix, number, and extension components. Neither of those have much in the way of literal segments within the string. As I think about how the original state machine parser worked, I think those literal segments are exactly where my code has the best chance to do well, because I no longer have to examine each character in the string.
#### Another thought:
This class is still useful, even if I can't make it go faster. As long as performance is *no worse* than the base String.Format(), I've still created a strongly-typed interface which allows a program to assemble it's own "format string" at run time. All I need to do is provide public access to the parts list. | ## Here's the final result:
I changed the format string in a benchmark trial to something that should favor my code a little more:
> The quick brown {0} jumped over the lazy {1}.
As I expected, this fares much better compared to the original; 2 million iterations in 5.3 seconds for this code vs 6.1 seconds for `String.Format`. This is an undeniable improvement. You might even be tempted to start using this as a no-brainer replacement for many `String.Format` situations. After all, you'll do no worse and you might even get a small performance boost: as much 14%, and that's nothing to sneeze at.
Except that it is. Keep in mind, we're still talking less than half a second difference for 2 *million* attempts, under a situation specifically designed to favor this code. Not even busy ASP.Net pages are likely to create that much load, unless you're lucky enough to work on a top 100 web site.
Most of all, this omits one important alternative: you can create a new `StringBuilder` each time and manually handle your own formatting using raw `Append()` calls. With that technique my benchmark finished in *only 3.9 seconds.* That's a much greater improvement.
---
In summary, if performance doesn't matter as much, you should stick with the clarity and simplicity of the built-in option. But when in a situation where profiling shows this really is driving your performance, there is a better alternative available via `StringBuilder.Append()`. | Don't stop now!
Your custom formatter might only be slightly more efficient than the built-in API, but you can add more features to your own implementation that would make it more useful.
I did a similar thing in Java, and here are some of the features I added (besides just pre-compiled format strings):
1) The format() method accepts either a varargs array or a Map (in .NET, it'd be a dictionary). So my format strings can look like this:
```
StringFormatter f = StringFormatter.parse(
"the quick brown {animal} jumped over the {attitude} dog"
);
```
Then, if I already have my objects in a map (which is pretty common), I can call the format method like this:
```
String s = f.format(myMap);
```
2) I have a special syntax for performing regular expression replacements on strings during the formatting process:
```
// After calling obj.toString(), all space characters in the formatted
// object string are converted to underscores.
StringFormatter f = StringFormatter.parse(
"blah blah blah {0:/\\s+/_/} blah blah blah"
);
```
3) I have a special syntax that allows the formatted to check the argument for null-ness, applying a different formatter depending on whether the object is null or non-null.
```
StringFormatter f = StringFormatter.parse(
"blah blah blah {0:?'NULL'|'NOT NULL'} blah blah blah"
);
```
There are a zillion other things you can do. One of the tasks on my todo list is to add a new syntax where you can automatically format Lists, Sets, and other Collections by specifying a formatter to apply to each element as well as a string to insert between all elements. Something like this...
```
// Wraps each elements in single-quote charts, separating
// adjacent elements with a comma.
StringFormatter f = StringFormatter.parse(
"blah blah blah {0:@['$'][,]} blah blah blah"
);
```
But the syntax is a little awkward and I'm not in love with it yet.
Anyhow, the point is that your existing class might not be much more efficient than the framework API, but if you extend it to satisfy all of your personal string-formatting needs, you might end up with a very convenient library in the end. Personally, I use my own version of this library for dynamically constructing all SQL strings, error messages, and localization strings. It's enormously useful. | Performance issue: comparing to String.Format | [
"",
"c#",
"performance",
"string",
""
] |
I think I must be doing something wrong here because my code only sent an email to the last subscriber in the table. When I log the array of subscribers, its obvious that there are more than one that it is trying to send to. I think the problem has to do with trying to batch them together...What is the best way for me to do this? I'm trying to create one message, with an attachment, then send address each one individually, and send them all out as one batched process. Here's my code:
```
$subscribersManager = new DD_Subscribers_Manager();
$subscribers = $subscribersManager->getAllSubscribers();
$subject = $form->getElement('subject')->getValue();
$body = $form->getElement('body')->getValue();
$filename = $form->getElement('bulletin')->getValue();
$filepath = Zend_Registry::get('rootDir') . '/public/downloads/archive/' . $filename;
$config = array('ssl' => 'tls', 'port' => 587, 'auth' => 'login', 'username' => 'fake@email.com', 'password' => 'password');
$smtpConnection = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
foreach ($subscribers as $subscriber) {
$message = new Zend_Mail('utf-8');
$message->setFrom('fake@email.com', 'My Fake Mailing List')
->addTo($subscriber->email)
->setSubject($subject)
->setBodyText($body);
$attachment = $message->createAttachment(file_get_contents($filepath));
$attachment->type = 'application/pdf';
$attachment->filename = $filename;
}
$message->send($smtpConnection);
``` | This looks like a scope issue: You create $message inside the foreach loop and only send the last one (since $message->send() is called after the foreach.
Basically, you overwrite the value of $message each time the foreach loop iterates. Move $message->send into the foreach loop to send one email per iteration. There may be another way to create an array of messages and send them all at once, but I'm not familiar with ZendMail.
EDIT: Actually, if you read the documentation on Zend\_Mail you can call $message->addTo() to add additiional recipients (more than 1) to a single message. Your code could change to something like:
```
$message = new Zend_Mail();
$message->setFrom('fake@email.com', 'My Fake Mailing List')
->setSubject($subject)
->setBodyText($body);
foreach($subscribers as $subscriber){
$message->addTo($subscriber->email);
}
$message->send();
```
[Zend\_Mail - adding recipients](http://framework.zend.com/manual/en/zend.mail.adding-recipients.html) | Looks to me like you're creating one object for each subscriber, and then not doing anything with any of them except the last. Move the `$message->send` call inside the `foreach` loop. | Sending emails to multiple subscribers with the Zend Framework | [
"",
"php",
"email",
"zend-framework",
"gmail",
"attachment",
""
] |
I want to output my InnerXml property for display in a web page. I would like to see indentation of the various tags. Is there an easy way to do this? | Here's a little class that I put together some time ago to do exactly this.
It assumes that you're working with the XML in string format.
```
public static class FormatXML
{
public static string FormatXMLString(string sUnformattedXML)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(sUnformattedXML);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = null;
try
{
xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xd.WriteTo(xtw);
}
finally
{
if(xtw!=null)
xtw.Close();
}
return sb.ToString();
}
}
``` | You should be able to do this with code formatters. You would have to html encode the xml into the page first.
Google has [a nice prettifyer](http://code.google.com/p/google-code-prettify/) that is capable of visualizing XML as well as several programming languages.
Basically, put your XML into a pre tag like this:
```
<pre class="prettyprint">
<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>
</pre>
``` | Is there a quick way to format an XmlDocument for display in C#? | [
"",
"c#",
"asp.net",
"xml",
""
] |
Is there anyway of having a base class use a derived class's static variable in C#? Something like this:
```
class Program
{
static void Main(string[] args)
{
int Result = DerivedClass.DoubleNumber();
Console.WriteLine(Result.ToString()); // Returns 0
}
}
class BaseClass
{
public static int MyNumber;
public static int DoubleNumber()
{
return (MyNumber*2);
}
}
class DerivedClass : BaseClass
{
public new static int MyNumber = 5;
}
```
I'm trying to have it return 10, but I'm getting 0.
Here's where I'm using this: I have a class called ProfilePictures with a static function called GetTempSavePath, which takes a user id as an argument and returns a physical path to the temp file. The path base is a static variable called TempPath. Since I'm using this class in multiple projects and they have different TempPaths, I'm creating a derived class that sets that variable to whatever the path is for the project.
### See Also
> [Why can’t I declare C# methods virtual and static?](https://stackoverflow.com/questions/248263/why-cant-i-declare-c-methods-virtual-and-static) | Apart from the fact that has already been pointed out... that static variables are tied or bound to the specific class declaring them and cannot be overridden. Overriding/Polymorphism needs instances to work.
Your problem can be solved with a change in design.
```
string ProfilePictures.GetTempSavePath(SomeType UserId, string sBasePath)
```
if it just needs these 2 variables to compute the return value, you can keep it as a utility/static method. Now you can feed in different base paths..
Now it seems from your question, that you need to use this class in multiple projects (which have fixed base paths) and kind of hardcode the base path so that you dont have to specify it for each call.
**Type/Class hierarchies should be defined based on behavior and not on data**. Variables can handle change in data. Hence I'd **suggest holding the basepath value as a static member variable, which is initialized from a resource file** (DoubleClick your project properties node > Settings > Add a new Settings file > add a new setting called BasePath - string - Application scope - VALUE=`C:\Users`). Now you just need to tweak the app.config file for each project, no code changes, no hardcoding and not more than one type needed.
```
public class PathHelper
{
static string _sBasePath;
static PathHelper()
{
_sBasePath = Properties.Settings.Default.BasePath;
}
static string GetTempSavePath(string sUserId)
{
// dummy logic to compute return value, replace to taste
return Path.Combine(_sBasePath, sUserId.Substring(0, 4));
}
}
```
Hope that made sense | The problem is that you're re-declaring the static variable in the derived class. The MyNumber declaration in DerivedClass hides the declaration in the base class. If you remove that declaration, then references to the "MyNumber" in derived class static functions will refer to the base class variable. Of course, if you remove the declaration then you can't use a static initializer in the derived class.
You might want to consider requiring users to instantiate an instance of ProfilePictures rather than provide a static function for GetTempSavePath. That way you could overide the GetTempSavePath method to provide the correct TempPath. Or, you could simply set the value of the static path value in your derived class constructor.
Although it is possible to use inheritance with static members, you can't relly have polymorphic behavior without a "this" pointer. | C#: Can a base class use a derived class's variable in a static function? | [
"",
"c#",
""
] |
Need a tutorial or some instruction on how to use the XML-RPC library built in to PHP (version PHP Version 5.2.6) for a XML-RPC client. The server is in Python and works.
Google and php.net are failing me.
## Update:
Per phpinfo I have **xmlrpc-epi v. 0.51** installed. I visited <http://xmlrpc-epi.sourceforge.net/> but the xmlrpc-epi-php examples section on the left showed me sf.net's version of a 404.
## Update2:
I'm going to use <http://phpxmlrpc.sourceforge.net/> and hopefully that will work out for me.
## Update3:
The code at <http://phpxmlrpc.sourceforge.net/> was straightforward and I got working.
Not closing the question. If anyone wants to chime in with ultra-simple solutions, that would be great! | A very simple xmlrpc client, I use a cURL class, you can get it from: <https://github.com/dcai/curl/blob/master/src/dcai/curl.php>
```
class xmlrpc_client {
private $url;
function __construct($url, $autoload=true) {
$this->url = $url;
$this->connection = new curl;
$this->methods = array();
if ($autoload) {
$resp = $this->call('system.listMethods', null);
$this->methods = $resp;
}
}
public function call($method, $params = null) {
$post = xmlrpc_encode_request($method, $params);
return xmlrpc_decode($this->connection->post($this->url, $post));
}
}
header('Content-Type: text/plain');
$rpc = "http://10.0.0.10/api.php";
$client = new xmlrpc_client($rpc, true);
$resp = $client->call('methodname', array());
print_r($resp);
``` | Looking for the same solution. This is a super simple class that can theoretically work with any XMLRPC server. I whipped it up in 20 minutes, so there is still a lot to be desired such as introspection, some better error handling, etc.
```
file: xmlrpcclient.class.php
<?php
/**
* XMLRPC Client
*
* Provides flexible API to interactive with XMLRPC service. This does _not_
* restrict the developer in which calls it can send to the server. It also
* provides no introspection (as of yet).
*
* Example Usage:
*
* include("xmlrpcclient.class.php");
* $client = new XMLRPCClient("http://my.server.com/XMLRPC");
* print var_export($client->myRpcMethod(0));
* $client->close();
*
* Prints:
* >>> array (
* >>> 'message' => 'RPC method myRpcMethod invoked.',
* >>> 'success' => true,
* >>> )
*/
class XMLRPCClient
{
public function __construct($uri)
{
$this->uri = $uri;
$this->curl_hdl = null;
}
public function __destruct()
{
$this->close();
}
public function close()
{
if ($this->curl_hdl !== null)
{
curl_close($this->curl_hdl);
}
$this->curl_hdl = null;
}
public function setUri($uri)
{
$this->uri = $uri;
$this->close();
}
public function __call($method, $params)
{
$xml = xmlrpc_encode_request($method, $params);
if ($this->curl_hdl === null)
{
// Create cURL resource
$this->curl_hdl = curl_init();
// Configure options
curl_setopt($this->curl_hdl, CURLOPT_URL, $this->uri);
curl_setopt($this->curl_hdl, CURLOPT_HEADER, 0);
curl_setopt($this->curl_hdl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl_hdl, CURLOPT_POST, true);
}
curl_setopt($this->curl_hdl, CURLOPT_POSTFIELDS, $xml);
// Invoke RPC command
$response = curl_exec($this->curl_hdl);
$result = xmlrpc_decode_request($response, $method);
return $result;
}
}
?>
``` | Need sample XML-RPC client code for PHP5 | [
"",
"php",
"xml-rpc",
""
] |
I am having a hard time to find a way to detect if **two words has the same rhyme in English**. It has not to be the same syllabic ending but something closer to **phonetically similarity**.
I can not believe in 2009 the only way of doing it is using those old fashioned rhyme dictionaries. Do you know any resources (in PHP would be a plus) to help me in this painful task?
Thank you.
Your hints were all really hepful. I will take some time to investigate it. Anyway, more info about DoubleMetaPhone can be found [here in a proper PHP code](http://swoodbridge.com/DoubleMetaPhone/) (the other one is an extension).
There are interesting information about MethaPhone function and doublemetaphone [in Php.net](http://es2.php.net/metaphone).
They specially alert about how slow double metaphone is compared with metaphone (something like 100 times slower). | Soundex won't help you. Soundex focuses on the beginning of the word, not its ending. Generally it think you'll have hard time finding any tool to do this. Even to the linguist the root of the word is more interesting, than it's ending.
Generally what you'll have to do is to divide words in syllables and compare their last syllable. Even better if you could divide it in phonemes, reverse their order and do comparison on reversed word.
You might trying comparing last part of [metaphone keys](http://pecl.php.net/package/doublemetaphone). | See [Bradley Buda's CS project summary from U. Michigan](http://www.bradleybuda.com/rhymes/595-final-report.pdf), which uses Levenshtein distance as an atom in finding rhyming English words. I believe combining Levenshtein and soundex should give better results. | Rhyme in PHP | [
"",
"php",
"nlp",
""
] |
I don't understand the output from the following code:
```
public static void main(String[] args) {
int i1, i2, i3, i4;
byte b;
i1 = 128;
b = (byte) i1;
i2 = (int) b;
i3 = 0 | b;
i4 = 1 << 7;
System.out.format("i1: %d b: %d i2: %d i3: %d i4: %d\n", i1, b, i2, i3, i4);
}
```
Output:
```
i1: 128 b: -128 i2: -128 i3: -128 i4: 128
```
Because `byte` is an 8-bit [two's-complement](http://en.wikipedia.org/wiki/Twos_complement) signed integer, the binary representations with a 1 in the most significant bit are interpreted as negative values, which is why `b` becomes `-128`, which I'm totally fine with. I also understand that it's probably a good idea to keep the interpretation consistent when casting, as with `i2`. But shouldn't `i3` and `i4` have identical bit patterns and therefore map to identical `int` values? | Sign extension is what is making `i2` and `i3` negative.
In the expression `(0 | b)`, `b` is promoted to an int, and sign extension occurs as part of this promotion.
That's not happening in the expression assigned to `i4`. The constants `1` and `7` are already ints so there's no sign extension involved. | In this line:
```
i3 = 0 | b;
```
The "b" variable is automatically promoted to `int` type with sign extension because of the `|` operator, so becomes `(int)-128`, i.e. `0xffffff80`.
When "or"ed with zero, its still the same value, namely -128 | Java: Why doesn't binary OR work as expected (see code below)? | [
"",
"java",
"binary",
""
] |
I got a comment to [an answer](https://stackoverflow.com/questions/712926/safe-way-of-allocating-memory-for-a-list-node/712969#712969) I posted on a C question, where the commenter suggested the code should be written to compile with a C++ compiler, since the original question mentioned the code should be "portable".
Is this a common interpretation of "portable C"? As I said in a further comment to that answer, it's totally surprising to me, I consider portability to mean something completely different, and see very little benefit in writing C code that is also legal C++. | No. My response [Why artificially limit your code to C?](https://stackoverflow.com/questions/649789/why-artificially-limit-your-code-to-c/650533#650533) has some examples of standards-compliant C99 not compiling as C++; earlier C had fewer differences, but C++ has stronger typing and different treatment of the `(void)` function argument list.
As to whether there is benefit to making C 'portable' to C++ - the particular project which was referenced in that answer was a virtual machine for a traits based language, so doesn't fit the C++ object model, and has a lot of cases where you are pulling `void*` of the interpreter's stack and then converting to structs representing the layout of built-in object types. To make the code 'portable' to C++ it would have add a lot of casts, which do nothing for type safety. | The current C++ (1998) standard incorporates the C (1989) standard. Some fine print regarding type safety put aside, that means "good" C89 should compile fine in a C++ compiler.
The problem is that the current C standard is that of 1999 (C99) - which is *not* yet officially part of the C++ standard (AFAIK)(\*). That means that many of the "nicer" features of C99 (long long int, stdint.h, ...), while *supported* by many C++ compilers, are *not* strictly compliant.
"Portable" C means something else entirely, and has little to do with official ISO/ANSI standards. It means that your code does not make assumptions on the host environment. (The size of int, endianess, non-standard functions or errno numbers, stuff like that.)
From a coding style guide I once wrote for a cross-platform project:
**Cross-Platform DNA (Do Not Assume)**
* There are no native datatypes. The only datatypes you might use are those declared in the standard library.
* char, short, int and long are of different size each, just like float, double, and long double.
* int is not 32 bits.
* char is neither signed nor unsigned.
* char cannot hold a number, only characters.
* Casting a short type into a longer one (int -> long) breaks alignment rules of the CPU.
* int and int\* are of different size.
* int\* and long\* are of different size (as are pointers to any other datatype).
* You do remember the native datatypes do not even exist?
* 'a' - 'A' does not yield the same result as 'z' - 'Z'.
* 'Z' - 'A' does not yield the same result as 'z' - 'a', and is not equal to 25.
* You cannot do anything with a NULL pointer except test its value; dereferencing it will crash the system.
* Arithmetics involving both signed and unsigned types do not work.
* Alignment rules for datatypes change randomly.
* Internal layout of datatypes changes randomly.
* Specific behaviour of over- and underflows changes randomly.
* Function-call ABIs change randomly.
* Operands are evaluated in random order.
* Only the compiler can work around this randomness. The randomness will change with the next release of the CPU / OS / compiler.
* For pointers, == and != only work for pointers to the exact same datatype.
* <, > work only for pointers into the same array. They work only for char's explicitly declared unsigned.
* You still remember the native datatypes do not exist?
* size\_t (the type of the return value of sizeof) can not be cast into any other datatype.
* ptrdiff\_t (the type of the return value of substracting one pointer from the other) can not be cast into any other datatype.
* wchar\_t (the type of a "wide" character, the exact nature of which is implementation-defined) can not be cast into any other datatype.
* Any ...\_t datatype cannot be cast into any other datatype
**(\*)**: This was true at the time of writing. Things have changed a bit with C++11, but the gist of my answer holds true. | Should "portable" C compile as C++? | [
"",
"c++",
"c",
"compatibility",
"portability",
""
] |
What's the best/smoothest solution to import an Excel-file to SQL Server, on a 64 bit Windows system?
What I'm specifically after is to import an Excel 97-2003 file, to a SQL 2005 database, from an ASP.NET/C# page. The import data will demand users to use a "template", so the data looks the same every time.
Previously the system has used Microsoft Jet OleDb 4.0 for this kind of import, but now it has moved to a 64 bit environment. I know Jet can run on 64 bit, if IIS is run in 32 bit mode, but that is in my opinion not an option.
So, what are the 64 bit alternatives here? | You should use Integration Services.
Create an Integration Services package that load the Excel file (relatively easy thing to do; you can even use the [Import and Export wizard](http://msdn.microsoft.com/en-us/library/ms141209.aspx)), and then [call the package from asp.net](http://blogs.msdn.com/michen/archive/2007/03/22/running-ssis-package-programmatically.aspx) | Another way to read Excel into an ADO.NET DataTable:
<http://www.aspspider.com/resources/Resource510.aspx>
Although I would also recommend just using an SSIS package to do the work. | What’s the best way to import an Excel-file to SQL Server on a 64 bit Windows platform in ASP.NET? | [
"",
"c#",
"asp.net",
"sql-server",
"excel",
"64-bit",
""
] |
In every large application there is an ADMIN section.
In such cases, when not using ZF, I usually put all the admin stuff in a separate directory with extra security measures (like adding .htaccess based authentication and/or a second login etc). This also makes it pretty obvious in the file tree what file is what.
How can I achieve the same design in ZF? Or are there any best practices to create an admin section?
Should I do it in the router level (if there is "admin" in the url, then I use a different index.php/ bootstrap file....)
I guess the simplest was just using a controller for all the admin stuff, but I have too much of that. So I have several admin controllers side by side with the regular app controllers. It makes a mess in my controllers directory - which controller is admin and which is not? | I generally create a separate "application" folder - complete with its own controller and view directory as well as a public directory for static content - for the entire administration system. The Administration usually has different requirements for key things such as access management, and might differ from the actual application in numerous other ways. Therefore I think it's a good idea to separate the source code entirely. Some of the source code can still be common, though. Examples include library folders and database models.
This approach also gives you larger flexibility when deciding where the admin utility should be available. You could use the apache alias directice to put it in a sub directory on the same domain, or put it on a separate vhost. It's all up to you. | I've done it as a [module](http://framework.zend.com/manual/en/zend.controller.front.html). In addition to the module link provided by Brett Bender see section 12.3.2.2 in the link I provided. | best practice to create an Admin section in a ZF based application | [
"",
"php",
"security",
"zend-framework",
"admin",
""
] |
Soon i'll start working on a parallel version of a mesh refinement algorithm using shared memory.
A professor at the university pointed out that we have to be very careful about thread safety because neither the compiler nor the stl is thread aware.
I searched for this question and the answer depended on the compiler (some try to be *somewhat* thread-aware) and the plattform (if the system calls used by the compiler are thread-safe or not).
So, in linux, the gcc 4 compiler produces thread-safe code for the new operator?
If not, what is the best way to overcome this *problem*? Maybe lock each call to the new operator? | You will have to look very hard to find a platform that supports threads but doesn't have a thread safe `new`. In fact, the thread safety of `new` (and `malloc`) is one of the reasons it's so slow.
If you want a thread safe STL on the other hand, you may consider [Intel TBB](http://www.threadingbuildingblocks.org/) which has thread aware containers (although not all operations on them are thread safe). | Generally the `new` operator is thread safe - however thread safety guarantees for calls into the STL and the standard library are governed by the standard - this doesn't mean that they are thread unaware - they tend to have very well defined guarantees of thread safety for certain operations. For example iterating through a list in a read-only fashion is thread safe for multiple readers, while iterating through a list and making updates is not. You have to read the documentation and see what the various guarantees are, although they aren't that onerous and they tend to make sense. | C++ new operator thread safety in linux and gcc 4 | [
"",
"c++",
"linux",
"gcc",
"thread-safety",
""
] |
I have an application where I need to write a new getpid function to replace the original one of the OS. The implementation would be similar to:
```
pid_t getpid(void)
{
if (gi_PID != -1)
{
return gi_PID;
}
else
{
// OS level getpid() function
}
}
```
How can I call the original getpid() implementation of the OS through this function?
EDIT: I tried:
```
pid_t getpid(void)
{
if (gi_PID != -1)
{
return gi_PID;
}
else
{
return _getpid();
}
}
```
as Jonathan has suggested. This gave me the following errors when compiling with g++:
> In function `pid_t getpid()':
> SerendibPlugin.cpp:882: error:`\_getpid' undeclared (first use this
> function) SerendibPlugin.cpp:882:
> error: (Each undeclared identifier is
> reported only once for each function
> it appears in.)
EDIT 2: I've managed to get this to work by using a function pointer and setting it to the next second symbol with the id "getpid", using dlsym(RTLD\_NEXT, "getpid").
Here's my sample code:
```
vi xx.c
"xx.c" 23 lines, 425 characters
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <dlfcn.h>
using namespace std;
pid_t(*___getpid)();
pid_t getpid(void)
{
cout << "My getpid" << endl;
cout << "PID :" << (*___getpid)() << endl;
return (*___getpid)();
}
int main(void)
{
___getpid = (pid_t(*)())dlsym(RTLD_NEXT, "getpid");
pid_t p1 = getpid();
printf("%d \n", (int)p1);
return(0);
}
```
g++ xx.c -o xout
```
My getpid
PID :7802
7802
``` | On many systems, you will find that `getpid()` is a 'weak symbol' for `_getpid()`, which can be called in lieu of `getpid()`.
---
The first version of the answer mentioned `__getpid()`; the mention was removed swiftly since it was erroneous.
This code works for me on Solaris 10 (SPARC) - with a C++ compiler:
```
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
extern "C" pid_t _getpid();
pid_t getpid(void)
{
return(-1);
}
int main(void)
{
pid_t p1 = getpid();
pid_t p2 = _getpid();
printf("%d vs %d\n", (int)p1, (int)p2);
return(0);
}
```
This code works for me on Solaris 10 (SPARC) - with a C compiler:
```
Black JL: cat xx.c
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
pid_t getpid(void)
{
return(-1);
}
int main(void)
{
pid_t p1 = getpid();
pid_t p2 = _getpid();
printf("%d vs %d\n", (int)p1, (int)p2);
return(0);
}
Black JL: make xx && ./xx
cc xx.c -o xx
"xx.c", line 13: warning: implicit function declaration: _getpid
-1 vs 29808
Black JL:
``` | You can use a macro:
in a .h, included in every file where you want to replace the `getpid` function
```
#define getpid() mygetpid()
```
Then, put your own implementation in a .cpp
```
pid_t mygetpid() {
// do what you want
return (getpid)();
}
``` | Replacing getpid with my own implementation | [
"",
"c++",
""
] |
I have List collection that is populated in specific order (the requirement is that, this order can not be changed). This list contains entity type objects.
After initial population of the list, I need to insert few more object, that are coming from another data source. These objects need to be inserted at specific position, so that sorting is correct.
For example if initial list has following elements
1. AAA
2. AAB
3. AAC
4. ACC
5. ADA
After initial population I want to insert "ABB" element, it need to be inserted between 3 and 4.
At moment I have following method of finding correct position for new elements.
```
private static int FindPositionForArticle(string word)
{
string key = word.ToLower();
for (int i = word.Length; i >= 0; i--)
{
if(i < word.Length)
key = key.Remove(i, 1);
int pos = 0;
int insertPos = 0;
foreach(ArticleEntity article in list)
{
if(article.Text.ToLower().StartsWith(key))
insertPos = pos;
else if (!article.Text.ToLower().StartsWith(key) && insertPos > 0)
return insertPos++;
pos++;
}
}
return 0;
}
```
The purpose idea behind this method:
1. Take "word" that need to be inserted and try to find position of element with same name as "word"
2. If nothing has been found, remove last character from "word" and search again.
3. Repeat removal of last characters until best position has been found.
Unfortunately my methods has bugs(implemented incorrectly). Currently my methods suggests that best position would be 0, which is totally incorrect.
If You want to play with my example code You may download it at:
<http://dl.getdropbox.com/u/204110/FindPosition.cs.txt>
Thank You in advance. | ```
int index = list.BinarySearch(word);
```
If index is positive or zero, the item has been found in the list. If negative, it contains the bitwise complement of the index of the next highest item in the list.
So, for this:
```
List<string> list = new List<string>{"AAA","AAB","AAC","ACC","ADA"};
int index = list.BinarySearch("ABB"); // => -4
int insertIndex = ~index; // => 3
list.Insert(insertIndex, "ABB");
``` | Wouldn't a [SortedList](http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx) of type string work better? | Finding best position for element in list | [
"",
"c#",
".net",
"algorithm",
"list",
"sorting",
""
] |
The Sys Admin guy is writing some common housekeeping Power Shell scripts. Predominantly for AD management (updating exchange details, moving people around security groups etc.)
I'd like to use these scripts from C# (I intend to write it as a library, consumed by a web site).
I've seen this [code project article](http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx) which looks interesting and a good place to start.
Does anyone have any experience of Power Shell interop? Can anyone think of any major gotchas before I jump head first into a spike?
**Extra Information:**
I appreciate there are logistical challenges particularly with CI and versioning.
The plan was initially to use Directory Services, exposing services through a web API and CmdLets. Unfortunately we’re having difficulties with Directory Services (e.g. truncated results for large sets).
In the meanwhile, rather than use an inconsistent mix, I figured I should investigate using the Sys Admins’ scripts. Why re-invent the wheel?
I’ve already written my domain model. I intend to implement the repository pattern so I can abstract out AD / Exchange integration allowing different implementations in the future. | If the scripts have dependencies on system or user profile, then you will need to explicitly dot-source the profile into your runspace first.
Higher levels of control (e.g. session carried from one command to another, ... accessing debug output) require more advanced/low-level/complex work.
Other than that, it all just works. | I don't think there are many Gotchas to this approach over the usual problems of running a script from a compiled program. I find the biggest problems tend to be
1. Keeping people from moving the script
2. Making sure people don't add hidden dependencies in the script that are not reflected in the calling program.
But I do think you should consider another model for your development. Instead of having a program reference a script, why not add all of the logic into a compiled library. This can be easily linked into the program and exposed to PowerShell via a CmdLet. I find this is an easier way to maintain shared code between scripts in programs. | C# Powershell Interop | [
"",
"c#",
"powershell",
"interop",
"active-directory",
"exchange-server",
""
] |
How can i arrange columns in asp.net gridview? i want to change 4 columns' location. ForExample:
column1 | column2 | column3 | column4 |
ChangeOrder()
column2 | column1 | column3 | column4 |
ChangeOrder()
column4 | column2 | column3 | column1 |
---
I want to move columns in Gridview. | 2 options from the top of my head:
1. Turn AutoGenerateColumns off and add
the columns yourself, mapping them
to what you want in the dataset and
in the order you want them.
2. Change your SQL query to return the
columns in the order that you want. | I don't know if this is an option for you, but the Telerik RadGrid supports this. See this [online demo](http://demos.telerik.com/aspnet-ajax/grid/examples/client/resizing/defaultcs.aspx) for details. | How can i arrange columns in asp.net gridview? | [
"",
"c#",
".net",
"asp.net",
"gridview",
""
] |
The following code is giving me a `NullPointerException`. The problem is on the following line:
```
...
dataMap.put(nextLine[0], nextLine[6]);
```
What is strange is that I have run this code without the above line and the call to `nextLine[0]` and `nextLine[6]` work exactly as expected - that is they give me back elements of a csv file. I declare and initialise the `HashMap` with the code
```
HashMap<String, String> dataMap = null;
```
earlier in the method
```
String[] nextLine;
int counter=0;
while (counter<40) {
counter++;
System.out.println(counter);
nextLine = reader.readNext();
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + " - " + nextLine[6] +" - " + "etc...");
dataMap.put(nextLine[0], nextLine[6]);
}
return dataMap;
}
``` | ```
HashMap<String, String> dataMap = new HashMap<String,String>();
```
Your `dataMap` variable isn't initialized at this point. You should be getting a compiler warning about that. | Where is datamap initialised ? It's always null.
To clarify, you declare the variable and set it to null. But you need to instantiate a new Map, whether it's a HashMap or similar.
e.g.
```
datamap = new HashMap();
```
(leaving aside generics etc.) | NullPointerException while using put method of HashMap | [
"",
"java",
"hashmap",
"nullpointerexception",
""
] |
I am calling functions using dynamic function names (something like this)
```
$unsafeFunctionName = $_POST['function_name'];
$safeFunctionName = safe($unsafeFunctionName); // custom safe() function
```
Then I am wanting to wrap some xml around the returned value of the function (something like this):
```
// xml header etc already created
$result = "<return_value>" . $safeFunctionName() . "</return_value>";
```
Problem is, sometimes the function returns a value, but sometimes, the function echo's a value. What I want to do is capture that echo into a variable, but, the code I write would need to work either way (meaning, if function returns a value, or echo's a string).
Not quite sure where to start ~ any ideas? | Let me preface this by saying:
Be careful with that custom function calling business. I am assuming you know how dangerous this can be which is why you're cleaning it somehow.
Past that, what you want is known as [output buffering](http://www.php.net/outcontrol):
```
function hello() {
print "Hello World";
}
ob_start();
hello();
$output = ob_get_clean();
print "--" . $output . "--";
```
(I added the dashes to show it's not being printed at first)
The above will output `--Hello World--` | [PHP: ob\_get\_contents](http://www.php.net/manual/en/function.ob-get-contents.php)
```
ob_start(); //Start output buffer
echo "abc123";
$output = ob_get_contents(); //Grab output
ob_end_clean(); //Discard output buffer
``` | capturing echo into a variable | [
"",
"php",
""
] |
I've got a queue, which is basically the producer/consumer queue in the albahari.com
threading book, which takes an queue item off the queue, which is an action execution block off the queue and then calls a method to execute the actionlist within the queue item.
I can kill the queue easily enough by enqueing a null actionblock and block the main thread by doing a spin/wait with a thread.sleep() until the queue count goes to zero, and all the threads fall through the while !=null loop, thereby completing, but the method executing the last actionlist may still be executing the last thread.
Question is, is their anyway to detect if that method still has a thread executing it, like maybe using a Semaphore or counter with an Interlock to count the semaphore up at the beginning of the method and count it down at the end. So if it reaches zero, them I know its not threaded.
This is the implementing a destroy method on the interface, to close it down before calling dispose. | If you start a thread like this:
```
System.Threading.Thread mythread = new System.Threading.Thread();
mythread.Start();
```
You can check:
```
mythread.IsAlive()
```
at any point to determine its status. | Use the Backgroundworker which has a completed event | Anyway to detect if a threaded method has completed | [
"",
"c#",
"multithreading",
"blocking",
""
] |
I want to represent **threaded comments** in Java. This would look similar to the way comments are threaded on ***reddit.com***
```
hello
hello
hello
hello
hello
hello
hello
```
As in the example above, responses are nested in the HTML with appropriate indentation to reflect their relationship to prior comments.
What would be an efficient way to represent this in Java?
I'm thinking some kind of **tree data structure** would be appropriate.
But is there one in particular which would be *most efficient* to minimize tree traversals?
This would be important if I have voting on each comment. Because then the tree would need to be reordered after each vote - a potentially expensive operation computationally.
By the way, if anyone knows of an open source existing implementation of this in Java, that would help too. | I would use levels of linked lists.
```
message1
message2
message3
message4
message5
message6
message7
```
Each node would have a pointer to its:
```
- forward sibling (2->5, 3->4, 5->6, 1/4/6/7->NULL).
- backward sibling (4->3, 5->2, 6->5, 1/2/3/7->NULL).
- first child (1->2, 2->3, 6->7, 3/4/5/7->NULL).
- parent (2->1, 3->2, 4->2, 5->1, 6->1, 7->6, 1->NULL).
```
Within each level, messages would be sorted in the list by vote count (or whatever other score you wanted to use).
That would give you maximum flexibility for moving things around and you could move whole sub-trees (e.g., `message2`) just by changing the links at the parent and that level.
For example, say `message6` gets a influx of votes that makes it more popular than `message5`. The changes are (adjusting both the next and previous sibling pointers):
* `message2 -> message6`
* `message6 -> message5`
* `message5 -> NULL`.
to get:
```
message1
message2
message3
message4
message6
message7
message5
```
If it continues until it garners more votes than `message2`, the following occurs:
* `message6 -> message2`
* `message2 -> message5`
*AND* the first-child pointer of `message1` is set to `message6` (it was `message2`), still relatively easy, to get:
```
message1
message6
message7
message2
message3
message4
message5
```
Re-ordering only needs to occur when a score change results in a message becoming more than its upper sibling or less than its lower sibling. You don't need to re-order after every score change. | The tree is right (with getLastSibling and getNextSibling), but if you're storing/querying the data, you probably want to store a lineage for each entry, or number by a preorder traversal:
<http://www.sitepoint.com/article/hierarchical-data-database/2/>
For loss of the exact number of subnodes, you can leave gaps to minimise renumbering. Still, I'm not certain that this will be noticeably faster than traversing the tree each time. I guess it depends how deep your tree grows.
See also:
[SQL - How to store and navigate hierarchies?](https://stackoverflow.com/questions/38801/sql-how-to-store-and-navigate-hierarchies)
<http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html> (this scheme is also call a Celko tree) | Most efficient data structure to represent threaded comments in Java? | [
"",
"java",
"data-structures",
"tree",
"reddit",
"threaded-comments",
""
] |
I would like to extract the SQL queries from Crystal Report .rpt files, is there a way to do this?
I don't have any of the Crystal Reports products, just the .rpt files. | My experience is with older versions of Crystal (8,9) - I've no idea what the file formats look like for more recent versions. However, it's worth opening the files up in a text editor just in case, but for the file formats I've seen, the query text is not accessible this way.
If I remember correctly, some versions of Visual Studio 2003 came with tools for manipulating Crystal .rpt files (but I guess this isn't of much use to you, since if you had this already, you wouldn't be asking!).
It's not a very imaginative suggestion, but perhaps your quickest route would be to download the [30-day trial version of the current Crystal Reports](http://www.sap.com/solutions/sapbusinessobjects/sme/freetrials/index.epx), and see if that will open the files for you. | Here's a .Net example of code that grabs the Command Sql from all Crystal Reports in a given directory. It requires the Crystal 2008 .Net SDK to be installed (you can download a trial from SAP):
```
foreach (string file in Directory.GetFiles("c:\\projects\\Reports", "*.rpt"))
{
Console.WriteLine(String.Format("Processing {0}...", file));
var doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
doc.Load(file);
foreach (dynamic table in doc.ReportClientDocument.DatabaseController.Database.Tables)
{
if (table.ClassName == "CrystalReports.CommandTable")
{
string commandSql = table.CommandText;
//TODO: do something with commandSql
}
}
}
```
To get the SQL as Crystal would build it when running a report, see this link: [SAP Note 1280515 - How to extract SQL query from Crystal reports using RAS sdk.](http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bi/sap%28bD1lbiZjPTAwMQ==%29/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233383330333533313335%7D.do)
I believe to do this, you need to supply the report parameter values so that Crystal can connect to the database in order to build the SQL. In the example, since a Report Viewer control is used, Crystal can prompt the user for the parameters. | I would like to extract the SQL queries from Crystal Report .rpt files, is there a way to do this? | [
"",
"sql",
"crystal-reports",
"report",
""
] |
I've got the next problem up from this one: [Comparing date ranges](https://stackoverflow.com/questions/143552/comparing-date-ranges)
The solution to comparing two ranges is the query:
SELECT \*
FROM periods
WHERE NOT (range\_start > @check\_period\_end
OR range\_end < @check\_period\_start)
I have the added problem. I am allowing people to enter a range of periods. To be precise they enter a duration (i.e 1 week) and a range of start dates (i.e. first 2 weeks in may) and I have to find out if there is a one week slot in the range they specified.
The naive solution is to run the above query for every day in my range. So - to check for 3 days slots in a month range I'd have to run 30 queries. Is there a more efficient way?
For bonus points - I am using Django. Is there a good solution using the Django ORM?
Edit - In an effort to simplify the question I think I've turned it into a different question! My actual problem is to find 'free gaps'. I think this invalidates some of the 'pure SQL' approaches below. I thought it would be sensible to [start a new question](https://stackoverflow.com/questions/781221/finding-free-slots-in-a-booking-system) rather than muddling this one. Others are likely to find this question useful in it's current form. | The problem is simpler than it may seem at first glance, as the user is not directly specifying an end date in their criteria.
```
SELECT * FROM periods p
WHERE p.range_start >= @min_start
AND p.range_start <= @max_start
AND DATE_ADD(p.range_start, INTERVAL @duration DAY) <= p.range_end
``` | In some cases, it turns out to be orders of magnitude faster to create one query that gets all of the data you might need, and then use the business logic language to filter these before testing.
It made for a saving of over 100x when doing something similar to this with rolling averages in an app I was working on. | Comparing two date ranges when one range has a range of starting dates | [
"",
"sql",
"mysql",
"django",
"date",
""
] |
I'm looking for the easiest solution to implement a folder browse dialog with checkboxes in front of the directories in my (C#) WinForms project.
I saw this kind of dialog in Vista in the backup center. It was just like a normal Folder browse dialog, but in front of every folder there was a checkbox. If you checked a folder, all folders and files in it were checked as well, while you could still deselect them separately afterwards.
If there's no prefab control or whatever for this, then what's the easiest way to either:
- Manipulate a normal folder browse dialog to include the checkbox functionality; or
- Manipulate a TreeView control to use Shell icons for paths (so the correct *system* icons for Desktop, My Music, normal folders, files, etc) so I can build one myself?
Note: I want the dialog/control to show both files *and* folders.
Thanks in advance for any tips and hints. =) | Start with tree vew. (you will have to take care of dynamically fetching children yourself, though).
If you don't care about the Explorer Namespace (i. e. having Control Panel below My Computer, or Desktop with Recycle Bin, Network Neigborhood and some more stuff below), and only need files on drives with drive letters, you can start with enumerating drive letters (using System.IO.Directory.GetLogicalDrives).
You can get the shell icons by calling ExtendedFileInfo.GetIconForFilename from the ManagedWinapi library (<http://mwinapi.sourceforge.net/>), which works both for files and folders. | The simplest way to implement something like this would be to use a standard TreeView control with the CheckBoxes property set to true. You should also be able to use images with it if you'd like to add a little folder image next to each node.
[See this MSDN article for more info.](http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.checkboxes.aspx) | Folder browse dialog with checkboxes? | [
"",
"c#",
"winforms",
"treeview",
"checkbox",
"folderbrowserdialog",
""
] |
I'm having issues with internet Explorer. I have a link which duplicates a file upload element on a form. The code which duplicates also appends a hyperlink to the duplicated upload element which is supposed to remove the duplicated element a simple remove this link.
The issue is that this code runs fine in firefox but it doesn't run at all in IE. Forget how the code is written out - the onClick event which I attach to the element doesn't fire at all!
I'm creating my remove link element like this in the function:
```
var a = document.createElement('a');
a.setAttribute('href', "javascript:void(0);");
a.setAttribute('class', 'delete');
a.setAttribute('onClick', 'removeThisElement(idOfParentContainer, this)');
container.appendChild(a);
```
This works fine in firefox but it doesn't fire at all in IE. I checked the dom using IE inspector and the link has rendered nicely however the class attached to it hasn't rendered or been applied and neither has the event fired even though it has physically been appended to the link on the html. For some reason the onClick event is not even firing no matter what code I put in it even if its an alert. Am I missing something here. :(
---
Great got part one of the issue solved by attaching events using AddEvent however why isn't the css rendering I mean the class attached to the element doesn't render at all for some weird reason :(
---
Good advice indeed - I'm rewriting my code to avoid the setAttribute function and instead porting all this DOM manipulation to jquery. Thanks for the helps guys | Event handlers are not DOM attributes, the attribute exists in markup only - I'm not sure why FF oks this. I'll go research that now cause I want to know.
Update: seems to be mixed feelings about whether eventhandlers are DOM-valid attributes or not. Looks to me like this is MS's fault as they internally do not treat them as attributes, whilst the HTML spec indicates that they very much are. The direct consequences of this are that a number of things !IE would consider attributes cannot be set with setAttribute in IE including eventhandler bindings and importantly also **style, class and name**. apparently IE8 fixes this but I still haven't installed that so I can't check.
Meanwhile, for event binding use the [addEventListener/attachEvent](http://www.quirksmode.org/js/events_advanced.html) pair instead, or (less preferably because it's a direct assignment) set a.onclick directly to your target method (or more likely a closure on your method).
To fix your styling not being correctly applied use `element.style = foo;` or (better) `element.className = bar`.
**Essentially the problem is setAttribute. Avoid using it.**
[For reference...](http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html) | As annakata said you should use addEventListener/attachEvent. However if you wan't to set the onclick direct you can use:
```
a.onclick = function() { removeThisElement(idOfParentContainer, this); };
``` | IE not allowing onClick event on dynamically created DOM 'a' element | [
"",
"javascript",
"css",
"internet-explorer",
"firefox",
"events",
""
] |
I have a `List<bool>` which I want to convert to a `byte[]`. How do i do this?
`list.toArray()` creates a `bool[]`. | Here's two approaches, depending on whether you want to pack the bits into bytes, or have as many bytes as original bits:
```
bool[] bools = { true, false, true, false, false, true, false, true,
true };
// basic - same count
byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);
// pack (in this case, using the first bool as the lsb - if you want
// the first bool as the msb, reverse things ;-p)
int bytes = bools.Length / 8;
if ((bools.Length % 8) != 0) bytes++;
byte[] arr2 = new byte[bytes];
int bitIndex = 0, byteIndex = 0;
for (int i = 0; i < bools.Length; i++)
{
if (bools[i])
{
arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);
}
bitIndex++;
if (bitIndex == 8)
{
bitIndex = 0;
byteIndex++;
}
}
``` | ## Marc's answer is good already, but...
*Assuming* you are the kind of person that is comfortable doing bit-twiddling, or just want to write less code *and* squeeze out some more performance, then this here code is for you good sir / madame:
```
byte[] PackBoolsInByteArray(bool[] bools)
{
int len = bools.Length;
int bytes = len >> 3;
if ((len & 0x07) != 0) ++bytes;
byte[] arr2 = new byte[bytes];
for (int i = 0; i < bools.Length; i++)
{
if (bools[i])
arr2[i >> 3] |= (byte)(1 << (i & 0x07));
}
}
```
It does the exact same thing as Marc's code, it's just more succinct.
Of course if we *really* want to go all out we could unroll it too...
...and while we are at it lets throw in a curve ball on the return type!
```
IEnumerable<byte> PackBoolsInByteEnumerable(bool[] bools)
{
int len = bools.Length;
int rem = len & 0x07; // hint: rem = len % 8.
/*
byte[] byteArr = rem == 0 // length is a multiple of 8? (no remainder?)
? new byte[len >> 3] // -yes-
: new byte[(len >> 3)+ 1]; // -no-
*/
const byte BZ = 0,
B0 = 1 << 0, B1 = 1 << 1, B2 = 1 << 2, B3 = 1 << 3,
B4 = 1 << 4, B5 = 1 << 5, B6 = 1 << 6, B7 = 1 << 7;
byte b;
int i = 0;
for (int mul = len & ~0x07; i < mul; i += 8) // hint: len = mul + rem.
{
b = bools[i] ? B0 : BZ;
if (bools[i + 1]) b |= B1;
if (bools[i + 2]) b |= B2;
if (bools[i + 3]) b |= B3;
if (bools[i + 4]) b |= B4;
if (bools[i + 5]) b |= B5;
if (bools[i + 6]) b |= B6;
if (bools[i + 7]) b |= B7;
//byteArr[i >> 3] = b;
yield return b;
}
if (rem != 0) // take care of the remainder...
{
b = bools[i] ? B0 : BZ; // (there is at least one more bool.)
switch (rem) // rem is [1:7] (fall-through switch!)
{
case 7:
if (bools[i + 6]) b |= B6;
goto case 6;
case 6:
if (bools[i + 5]) b |= B5;
goto case 5;
case 5:
if (bools[i + 4]) b |= B4;
goto case 4;
case 4:
if (bools[i + 3]) b |= B3;
goto case 3;
case 3:
if (bools[i + 2]) b |= B2;
goto case 2;
case 2:
if (bools[i + 1]) b |= B1;
break;
// case 1 is the statement above the switch!
}
//byteArr[i >> 3] = b; // write the last byte to the array.
yield return b; // yield the last byte.
}
//return byteArr;
}
```
**Tip:** As you can see I included the code for returning a `byte[]` as comments. Simply comment out the two yield statements instead if that is what you want/need.
---
**Twiddling Hints:**
Shifting `x >> 3` is a cheaper `x / 8`.
Masking `x & 0x07` is a cheaper `x % 8`.
Masking `x & ~0x07` is a cheaper `x - x % 8`.
---
**Edit:**
Here is some example documentation:
```
/// <summary>
/// Bit-packs an array of booleans into bytes, one bit per boolean.
/// </summary><remarks>
/// Booleans are bit-packed into bytes, in order, from least significant
/// bit to most significant bit of each byte.<br/>
/// If the length of the input array isn't a multiple of eight, then one
/// or more of the most significant bits in the last byte returned will
/// be unused. Unused bits are zero / unset.
/// </remarks>
/// <param name="bools">An array of booleans to pack into bytes.</param>
/// <returns>
/// An IEnumerable<byte> of bytes each containing (up to) eight
/// bit-packed booleans.
/// </returns>
``` | Convert bool[] to byte[] | [
"",
"c#",
"boolean",
"arrays",
""
] |
How can we invoke a python script using AIR 1.5? | You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives.
If it's really really (that's two reallys) important to run an executable from AIR lookup the CommandProxy demo. | For example through AMF: <http://pyamf.org/> | Call python script from AIR application? | [
"",
"python",
"flex3",
"air",
""
] |
In this code :
```
public class MyClass {
private Object innerValue;
public Object getInnerValue() {
return this.innerValue;
}
public void setInnerValue(Object innerValue) {
this.innerValue = innerValue;
}
}
public class MyClassReadOnly extends MyClass {
MyClassReadOnly(MyClass cls) {
// Make a field by field copy
super.setInnerValue(cls.getInnerValue());
}
public void setInnerValue(Object innerValue) {
throw new UnsupportedOperationException(
"This is a read-only instance"
);
}
}
```
The compiler complains rightly about the unused parameter(never read) *innerValue* in *MyClassReadOnly.setInnerValue()*.
I don't want to disable this kind of warnings since it's quite useful usually, and I don't want to have any warnings either to have a high signal/noise ratio.
I cannot use the *@SuppressWarnings()* construct as another question suggested since it's Java 1.4 only.
I thought about inserting dummy code like this, but it's not very satisfactory :
```
public void setInnerValue(Object innerValue) {
if (innerValue != null) { /* Do Nothing, but keep the compiler happy */ }
throw new UnsupportedOperationException("This is a read-only instance");
}
``` | The warning is not the problem, I'm afraid that the design is.
Your current hierarchy violates Liskov's principle of substitution since a class receiving an instance of a MyClass expects setInnerValue to work, and may not handle this exception correctly. You can say that a read-and-write X is a type of readable-X, but you cannot say that a readable-X is a type of read-and-writable X.
When I am faced with this sort of situation, I create an interface called IMyX with the reads, a subinterface called IMutableMyX with the writes, and then the actual class implements IMutableMyX and thus also IMyX. I am then very careful to only pass IMutableMyX when I need to, and pass IMyX in all other cases.
I feel that it is better to use the compiler and types to restrict access than it is to count on runtime exceptions. It also makes your code a lot clearer, and forces you to explicitly downcast the interface when you do want write-access.
I realize this does not answer your question about getting rid of the warnings. But warnings can either be suppressed, ignored, or addressed. An unused parameter is often a bad smell that indicates your method might not be doing what it's expected to do. Methods should only get essential parameters. If the parameter is not used, the parameter is not essential, and therefore something needs to be changed. | I'm afraid you're stuck with dummy code. In C/C++, you could use a macro (`#define _unused(x) ((void) x)`), but `(void) variable;` isn't a valid statement in Java.
If it makes you feel better, the compiler will likely optimize away the empty if-block. | How to avoid the "unused param" warning when overriding a method in java 1.4? | [
"",
"java",
"parameters",
"overriding",
"suppress-warnings",
""
] |
say i have a file `/var/www/foo/test.php`
how do i find out it's path from within it.
i'm trying to create an "Add To Include Path" action, and for that i need absolute paths. | > **Note:** I am leaving my original answer intact, but don't use it. The solutions involving the `__FILE__` constant are preferred.
You can use `$_SERVER['DOCUMENT_ROOT']` to find the path to the current script. If you need the name of the .php file included, add on `$_SERVER["SCRIPT_NAME"]`, like this:
```
$_SERVER['DOCUMENT_ROOT'].$_SERVER["SCRIPT_NAME"];
``` | You can use the magic constant, `__FILE__`
<https://www.php.net/manual/en/language.constants.predefined.php> | How do i fetch my file's absolute path | [
"",
"php",
""
] |
What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.
So far I have this code:
```
from datetime import datetime
tstart = datetime.now()
print t1
# code to speed test
tend = datetime.now()
print t2
# what am I missing?
# I'd like to print the time diff here
``` | [`datetime.timedelta`](http://docs.python.org/3.2/library/datetime.html#timedelta-objects) is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds
```
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543
```
Be aware that `c.microseconds` only returns the microseconds portion of the timedelta! For timing purposes always use `c.total_seconds()`.
You can do all sorts of maths with datetime.timedelta, eg:
```
>>> c / 10
datetime.timedelta(0, 0, 431654)
```
It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command. | Since Python 2.7 there's the `timedelta.total_seconds()` method. So, to get the elapsed milliseconds:
```
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print delta
0:00:05.077263
>>> int(delta.total_seconds() * 1000) # milliseconds
5077
``` | Python speed testing - Time Difference - milliseconds | [
"",
"python",
"datetime",
"time",
"time-measurement",
""
] |
```
typedef boost::variant<long long,double,string> possibleTypes ;
set<possibleTypes,less<possibleTypes> > ascSet ;
set<possibleTypes,greater<possibleTypes> > descSet ;
```
When I try to compile I get a bunch of errors in some library headers.
But, if I remove the third line (the one with `descSet` ) the code compile just fine.
What's the problem? Can't boost::variant objects be sorted in descendant order??
**Edit:**
I'm using Visual Studio 2005 and Boost 1.38.0 and the following command line:
```
cl /EHsc /I"C:\boost_1_38_0" test.cpp
```
**Edit2**
As it was suggested, by Doug T, if I define this:
```
bool operator>(const possibleTypes& a, const possibleTypes& b){
return b < a ;
}
```
Then the following code doesn't compile:
```
possibleTypes pt1="a", pt2="b" ;
greater<possibleTypes> func ;
cout << func(pt1,pt2) << endl ;
```
However, this code compiles just fine:
```
possibleTypes pt1="a", pt2="b" ;
cout << (pt1 > pt2) << endl ;
```
Could anyone help me to understand why??
I tried with VC++ 2005 and GCC 3.4.6 | As it was suggested, if I define this:
```
bool operator>(const possibleTypes& a, const possibleTypes& b){
return b < a ;
}
```
Then the following code doesn't compile:
```
possibleTypes pt1="a", pt2="b" ;
greater<possibleTypes> func ;
cout << func(pt1,pt2) << endl ;
```
However, this code compiles just fine:
```
possibleTypes pt1="a", pt2="b" ;
cout << (pt1 > pt2) << endl ;
```
Could anyone help me to understand why??
I tried with VC++ 2005 and GCC 3.4.6 | It appears a < operator is defined for boost::variant but not a > operator. Thus perhaps std::less<> works but not std::greater<>
See [here](http://www.boost.org/doc/libs/1_38_0/doc/html/boost/variant.html)
I would try defining a a free > operator.
```
bool operator > (boost::variant<...> lhs, boost::variant<..> rhs)
{
return (rhs < lhs) // thanks Chris Jester Young
}
``` | std::set filled with boost::variant elements cannot be sorted descendantly? | [
"",
"c++",
"boost",
""
] |
I am writing a piece of code designed to do some data compression on CLSID structures. I'm storing them as a compressed stream of 128 bit integers. However, the code in question has to be able to place invalid CLSIDs into the stream. In order to do this, I have left them as one big string. On disk, it would look something like this:
```
+--------------------------+-----------------+------------------------+
| | | |
| Length of Invalid String | Invalid String | Compressed Data Stream |
| | | |
+--------------------------+-----------------+------------------------+
```
To encode the length of the string, I need to output the 32 bit integer that is the length of the string one byte at a time. Here's my current code:
```
std::vector<BYTE> compressedBytes;
DWORD invalidLength = (DWORD) invalidClsids.length();
compressedBytes.push_back((BYTE) invalidLength & 0x000000FF);
compressedBytes.push_back((BYTE) (invalidLength >>= 8) & 0x000000FF));
compressedBytes.push_back((BYTE) (invalidLength >>= 8) & 0x000000FF));
compressedBytes.push_back((BYTE) (invalidLength >>= 8));
```
This code won't be called often, but there will need to be a similar structure in the decoding stage called many thousands of times. I'm curious if this is the most efficient method or if someone can come up with one better?
Thanks all!
Billy3
EDIT:
After looking over some of the answers, I created this mini test program to see which was the fastest:
```
// temp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <ctime>
#include <iostream>
#include <vector>
void testAssignedShifts();
void testRawShifts();
void testUnion();
int _tmain(int argc, _TCHAR* argv[])
{
std::clock_t startTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testAssignedShifts();
}
std::clock_t assignedShiftsFinishedTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testRawShifts();
}
std::clock_t rawShiftsFinishedTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testUnion();
}
std::clock_t unionFinishedTime = std::clock();
std::printf(
"Execution time for assigned shifts: %08u clocks\n"
"Execution time for raw shifts: %08u clocks\n"
"Execution time for union: %08u clocks\n\n",
assignedShiftsFinishedTime - startTime,
rawShiftsFinishedTime - assignedShiftsFinishedTime,
unionFinishedTime - rawShiftsFinishedTime);
startTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testAssignedShifts();
}
assignedShiftsFinishedTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testRawShifts();
}
rawShiftsFinishedTime = std::clock();
for (register unsigned __int32 forLoopTest = 0; forLoopTest < 0x008FFFFF; forLoopTest++)
{
testUnion();
}
unionFinishedTime = std::clock();
std::printf(
"Execution time for assigned shifts: %08u clocks\n"
"Execution time for raw shifts: %08u clocks\n"
"Execution time for union: %08u clocks\n\n"
"Finished. Terminate!\n\n",
assignedShiftsFinishedTime - startTime,
rawShiftsFinishedTime - assignedShiftsFinishedTime,
unionFinishedTime - rawShiftsFinishedTime);
system("pause");
return 0;
}
void testAssignedShifts()
{
std::string invalidClsids("This is a test string");
std::vector<BYTE> compressedBytes;
DWORD invalidLength = (DWORD) invalidClsids.length();
compressedBytes.push_back((BYTE) invalidLength);
compressedBytes.push_back((BYTE) (invalidLength >>= 8));
compressedBytes.push_back((BYTE) (invalidLength >>= 8));
compressedBytes.push_back((BYTE) (invalidLength >>= 8));
}
void testRawShifts()
{
std::string invalidClsids("This is a test string");
std::vector<BYTE> compressedBytes;
DWORD invalidLength = (DWORD) invalidClsids.length();
compressedBytes.push_back((BYTE) invalidLength);
compressedBytes.push_back((BYTE) (invalidLength >> 8));
compressedBytes.push_back((BYTE) (invalidLength >> 16));
compressedBytes.push_back((BYTE) (invalidLength >> 24));
}
typedef union _choice
{
DWORD dwordVal;
BYTE bytes[4];
} choice;
void testUnion()
{
std::string invalidClsids("This is a test string");
std::vector<BYTE> compressedBytes;
choice invalidLength;
invalidLength.dwordVal = (DWORD) invalidClsids.length();
compressedBytes.push_back(invalidLength.bytes[0]);
compressedBytes.push_back(invalidLength.bytes[1]);
compressedBytes.push_back(invalidLength.bytes[2]);
compressedBytes.push_back(invalidLength.bytes[3]);
}
```
Running this a few times results in:
```
Execution time for assigned shifts: 00012484 clocks
Execution time for raw shifts: 00012578 clocks
Execution time for union: 00013172 clocks
Execution time for assigned shifts: 00012594 clocks
Execution time for raw shifts: 00013140 clocks
Execution time for union: 00012782 clocks
Execution time for assigned shifts: 00012500 clocks
Execution time for raw shifts: 00012515 clocks
Execution time for union: 00012531 clocks
Execution time for assigned shifts: 00012391 clocks
Execution time for raw shifts: 00012469 clocks
Execution time for union: 00012500 clocks
Execution time for assigned shifts: 00012500 clocks
Execution time for raw shifts: 00012562 clocks
Execution time for union: 00012422 clocks
Execution time for assigned shifts: 00012484 clocks
Execution time for raw shifts: 00012407 clocks
Execution time for union: 00012468 clocks
```
Looks to be about a tie between assigned shifts and union. Since I'm going to need the value later, union it is! Thanks!
Billy3 | Just use a union:
```
assert(sizeof (DWORD) == sizeof (BYTE[4])); // Sanity check
union either {
DWORD dw;
struct {
BYTE b[4];
} bytes;
};
either invalidLength;
invalidLength.dw = (DWORD) invalidClsids.length();
compressedBytes.push_back(either.bytes.b[0]);
compressedBytes.push_back(either.bytes.b[1]);
compressedBytes.push_back(either.bytes.b[2]);
compressedBytes.push_back(either.bytes.b[3]);
```
**NOTE: Unlike the bit-shifting approach in the original question, this code produces endian-dependent output.** This matters only if output from a program running on one computer will be read on a computer with different endianness -- but as there seems to be no measurable speed increase from using this method, you might as well use the more portable bit-shifting approach, just in case. | This is probably as optimized as you'll get. Bit-twiddling operations are some of the fastest available on the processor.
It may be faster to >> 16, >> 24 instead of >>= 8 >>= 8 - you cut down an assignment.
Also I don't think you need the & - since you're casting to a BYTE (which *should* be a 8-bit char) it'll get truncated down appropriately anyway. (Is it? correct me if I'm wrong)
All in all, though, these are really minor changes. Profile it to see if it actually makes a difference :P | Fastest Method to Split a 32 Bit number into Bytes in C++ | [
"",
"c++",
"byte",
""
] |
OMG - what is going on with Eclipse (3.3 Europa) - has anyone come accross this problem (bearing in mind I have been messing about with uninstalling different Tomat containers and installing others - but anyway thats another story)
When I change a line of code or remove a class within my project - when I come to debug - it actually goes to a line that is commented out and runs that line regardless!!!! e.g.
//System.out.println("you should not be able to read this!");
UPDATE: This can be solved by setting Project -> Build Automatically (see answer below).
---
REMAINING PROBLEM:
Eclipse is not keeping my hot deploy folder current with the latest changes to my project:
I found out to my horror that some old remenants of my project are 'hanging around' in the folder that I think Eclipse uses for hot deploys or something
**C:\myJavaCode.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\myWebApp**
basically it is not actually copying accross any changes made in the classes of my working dir!?!??
...anyway - in order to keep my project up to date - I have to modify this folder too - TOTALLY UNACCEPTABLE - as you can't develop in this way - it would take you eons! Anyway, if anyone can help explain to me what stupid thing I have done to get me in this mess and how I can get out of this mess - I would really appreciate it. | Have a look at:
> Windows>Preferences>Server>Launching...
and:
> Project>Build Automatically
maybe you accidentally disabled the auto-deploy features. | I had a similar problem, only without the added complexities of a web app. I'm just running a JUnit test and it's running the old code. I went into Configure Build Path, on the bottom of the Source tab, and looked at Default Output Folder, which said myproject/bin. The Package Explorer doesn't even show a bin folder, but when looking at the file system there's a bin folder there. I deleted the bin folder, refreshed the package explorer tree, and it worked. This behavior was in Helios and occurred with AND without Build Automatically selected...looks like a bug to me.
Dave | Eclipse keeps running my old web application | [
"",
"java",
"eclipse",
""
] |
Is there a lint-like tool for C#? I've got the compiler to flag warnings-as-errors, and I've got Stylecop, but these only catch the most egregious errors. Are there any other must-have tools that point out probably-dumb things I'm doing? | Tried [FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx)? It's integrated into VS as "Code Analysis"
In the newer versions of Visual Studio, it is called "Microsoft Code Analysis" and can be downloaded from the Visual Studio Marketplace: <https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.MicrosoftCodeAnalysis2017> | [SonarLint](http://www.sonarlint.org/visualstudio/index.html) (free, open source) is pretty sweet!
> SonarLint for Visual Studio is based on and benefits from the .NET Compiler Platform ("Roslyn") and its code analysis API to provide a fully-integrated user experience in Visual Studio 2015.
> SonarLint is free, open source, and available in the Visual Studio Gallery. | What linters are there for C#? | [
"",
"c#",
".net",
"code-analysis",
"lint",
""
] |
*Even though the solution is so obvious I should have never have posted this, I'm leaving it up as a reminder and a useful point of reference to others.*
I've got the following base class:
```
using System;
namespace LibraryWPF
{
public class Library
{
/// <summary>
/// Event fired when content is added to the libary
/// </summary>
public event EventHandler<ObjectInfoEventArgs> Library_ObjectAdded;
/// <summary>
/// Event fired when the scan of the library is finished
/// </summary>
public event EventHandler Library_Finished;
// Properties
/// <summary>
/// Whether to stop checking the library or not
/// </summary>
public bool Stop
{
get;
set;
}
/// <summary>
/// Where to look for content
/// </summary>
public string Root
{
get;
set;
}
/// <summary>
/// Empty instance of library's object for reflection
/// </summary>
public virtual object ObjectInfo
{
get
{
// Should this raise as exception to show if it's not been overridden?
return null;
}
}
/// <summary>
/// Sub class overrides this method to call it's actual find code
/// </summary>
public virtual void Find()
{
// Should this raise as exception to show if it's not been overridden?
}
/// <summary>
/// Build the library
/// </summary>
public void Build()
{
if (Root != null && Root.Length > 0)
{
Stop = false;
Find();
}
// Final update
if (Library_Finished != null)
{
Library_Finished(this, null);
}
}
/// <summary>
/// Sub class calls this method to fire the ObjectAdded event
/// </summary>
/// <param name="objectInfo">Object just added to library</param>
protected void OnObjectAdded(object objectInfo)
{
if (Library_ObjectAdded != null)
{
Library_ObjectAdded(this, new ObjectInfoEventArgs(objectInfo));
}
}
}
}
```
The sub-classes override `ObjectInfo` to return an instance of the type of object they're looking for use by reflection. They also override `Find` to do the actual searching.
This way my application code can use the base class methods so it doesn't have to know anything about the sub-classes at compile time. I tell it what sort of content to look for using DI.
So - my question is this:
Should I throw an exception in the base class versions of `ObjectInfo` and `Find` so that if the sub-classes aren't implemented properly I get a run-time error? Or should I code for `ObjectInfo` returning `null`? | If you require that a method be implemented by derived classes, why not make it abstract instead of virtual? This will force the derived class to implement the member. If they do not want to, or cannot return an ObjectInfo they can choose to return null themselves. | You should declare your base class and the methods to be implemented by derived classes as abstract. This avoids the probem entirely because the compiler will detect derived classes that don't override all abstarct methods. | Is it good practice to throw exceptions in virtual functions? | [
"",
"c#",
""
] |
I'm a complete novice, looking for instructions on implementing javascript. I am attempting to replace a YUI slider with buttons and a text field. I am trying to achieve buttons that, when held down, will continue to make the text field increase, preferably at a faster and faster rate. (<http://www.blackbird502.com/white.htm)I> have this in the java tag in the head:
```
function holdit(btn, action, start, speedup) {
var t;
var repeat = function () {
action();
t = setTimeout(repeat, start);
start = start / speedup;
}
btn.mousedown = function() {
repeat();
}
btn.mouseup = function () {
clearTimeout(t);
}
/* to use */
holdit(btn, function () { }, 1000, 2);
/* x..1000ms..x..500ms..x..250ms..x */
```
I have no clue how to implement the press and hold into the following in the body:
```
<form><input type=button value="UP" class="btn" onClick="javascript:this.form.amount.value++;"><br /><input type=text name=amount value=5 class="text"><br /> <input type=button value="DOWN" class="btn" onClick="javascript:this.form.amount.value--;" ></form>
```
Is it possible? Thanks. | This code should do everything you're looking for; it's based very loosely on tj111's example. I tried to make it as reusable as possible, and it doesn't need JavaScript mixed in with the HTML.
You do need to add IDs to the buttons (`btnUP` and `btnDOWN`) and text field (`amount`). You can change these IDs in the `window.onload` statement.
```
// This function creates a closure and puts a mousedown handler on the element specified in the "button" parameter.
function makeButtonIncrement(button, action, target, initialDelay, multiplier){
var holdTimer, changeValue, timerIsRunning = false, delay = initialDelay;
changeValue = function(){
if(action == "add" && target.value < 1000)
target.value++;
else if(action == "subtract" && target.value > 0)
target.value--;
holdTimer = setTimeout(changeValue, delay);
if(delay > 20) delay = delay * multiplier;
if(!timerIsRunning){
// When the function is first called, it puts an onmouseup handler on the whole document
// that stops the process when the mouse is released. This is important if the user moves
// the cursor off of the button.
document.onmouseup = function(){
clearTimeout(holdTimer);
document.onmouseup = null;
timerIsRunning = false;
delay = initialDelay;
}
timerIsRunning = true;
}
}
button.onmousedown = changeValue;
}
//should only be called after the window/DOM has been loaded
window.onload = function() {
makeButtonIncrement(document.getElementById('btnUP'), "add", document.getElementById('amount'), 500, 0.7);
makeButtonIncrement(document.getElementById('btnDOWN'), "subtract", document.getElementById('amount'), 500, 0.7);
}
``` | This is kind of quick and dirty, but it should give you a start. Basically you want to set up a few initial "constants" that you can play with to get the desired behavior. The initial time between increments is 1000 ms, and on each iteration if become 90% of that (1000, 990, 891, ... 100) and stops getting smaller at 100 ms. You can tweak this factor to get faster or slower acceleration. The rest I believe is pretty close to what I think you were going for. It seems like you were just missing the event assignments. In the `window.onload` you'll see that i assign the `onmouseup`, and `onmousedown` events to functions that just call the `increment()` or `decrement()` functions with your initial timeout, or the `ClearTimeout()` function to stop the counter.
EDIT: I changed this slightly to fix the bug. Now if you move your mouse pointer off the button and release it will stop the counter.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script>
// Fake Constants
var INITIAL_TIME = 1000;
var ACCELERATION = .9;
var MIN_TIME = 100;
// create global variables to hold DOM objects, and timer
var up = null,
down = null,
count = null,
timer = null;
// Increment the counter
function increment (time) {
// decrease timeout by our acceleration factor, unless it's at the minimum
time = (time * ACCELERATION > MIN_TIME) ? (time * ACCELERATION) : MIN_TIME;
count.value ++ ;
// set the timeout for the next round, and pass in the new smaller timeout
timer = setTimeout(
function () {
increment(time);
}, time);
}
// Same as increment only subtracts one instead of adding.
// -- could easily make one function and pass an pos/neg factor instead
function decrement (time) {
time = time * ACCELERATION > MIN_TIME ? (time * ACCELERATION) : MIN_TIME;
count.value --;
timer = setTimeout(
function () {
decrement(time);
}, time);
}
// Initialize the page after all the forms load
window.onload = function () {
// initialization function
// assign DOM objects to our vars for ease of use.
up = document.getElementById('up_btn');
down = document.getElementById('dwn_btn');
count = document.getElementById('count');
// create event handlers for mouse up and down
up.onmousedown = function () {
increment(INITIAL_TIME);
}
down.onmousedown = function () {
decrement(INITIAL_TIME);
}
document.onmouseup = function () {
clearTimeout(timer);
}
}
</script>
</head>
<body>
<!-- Insert your content here -->
<form name="the_form">
<input type="button" value="Up" id="up_btn" /><br />
<input type="button" value="Down" id="dwn_btn" /></br>
<br />
Count:
<input type="text" value="0" id="count" />
</form>
</body>
</html>
``` | How do I implement press and hold button javascript? | [
"",
"javascript",
"forms",
"button",
""
] |
I have a class that should read a message, extract its type from the envelope and then call a method that have to process the message; at each message type is associated an enum member.
There are 30+ message types.
One way to dispatch the message is to just use a switch, but it's really ugly and error-prone (have I already tract that case? have I tract that case two times?).
One another way is to define an interface with a single method process(data) and create one class for each message type that implements that interface, register those classes with a map and, in the code that should process the message, just call map.get(messageType).process(data); but it's really annoying to create 30+ classs.
One another way is to use reflection: define one function for each messagetype, with a precise signature and pattern name, like processMessagetype; then create a map from messagetype to Method (filled with a simple search upon getDeckaredMethods()) and then do something like:
map.get(messageType).invoke(this,data).
What method you should use? What's the overhead of using java's reflection? | Reflection has a big overhead if you're looking for good performance. If your routine (message dispatch) is going to be used over and over the polymorphism alternative is better. Also, IMO it's better if looking in a OO perspective, since as stated by [Brian](https://stackoverflow.com/questions/793568/overhead-of-searching-and-calling-a-method-with-reflection/793593#793593) on his answer, it's easier and cheaper for maintenance.
Your clas handling 30+ messages can easily grow to 100+ messages, then you will have a class with 100+ methods, add the private methods too and code reuse will be hard and your class has just became a mess.
The overhead of reflection over polymorphism and switch is something like this:
```
time spent on a switch case call: 1
time spent on a polymorphism call: 1.1
time spent on a reflection call: 1.9-2.0
```
I benchmarked these guys a while ago, and those were my results, I don't have the code now because these benchmarks were done on my previous company and I don't have access to that code anymore. | You could add the process method to the enum.
What exactly is wrong with a big switch (with each case just calling a method)?
The major cost of reflection is that it tends to make code suck. ;) | Overhead of searching and calling a method with reflection | [
"",
"java",
"reflection",
""
] |
I'm not even sure if this is possible, but is it feasible to secure, end-to-end runtime data on an uncontrolled client?
Specifically, is there any functionality in Java to take in encrypted data, process it and send it back out encrypted, all without exposing the data in plaintext to a curious 3rd party that has full access to the client?
Also, I know that code obfuscation is merely an annoyance to a dedicated individual with a decompiler, so I'm assuming for this scenario that the attack party has full source/operating knowledge.
I'm interested in answers either way. If there is no existing functionality, would it be feasible given Java's architecture? If Java can't do it, is there another language/platform that could? I'm fearing this may require special hardware. | To have a chance at doing what you are talking about, you need special hardware. You can't have a secure layer "on top" of an insecure layer. For example, if the attacker has full control over the hardware, he can always compromise the OS running on that host.
The special hardware is called a "Trusted Platform Module," or TPM. This supports remote attestation, which would allow you to verify that a client has not been tampered with. Some parts of the TPM are available on many computers (my Dell laptop, for example). In fact, I think all computers purchased by the US federal government are required to have a TPM. However, most consumers do not enable the TPM, and there's a lot of hostility toward TPM from privacy advocates. I'm also unsure how many machines with a TPM include the remote attestation capability.
Anyway, the bottom line is that you can't give someone a secret, and the key to the secret, and expect it to remain a secret. You have to retain control over the whole stack, top-to-bottom. Trusted Treacherous Computing allows you do do that, even if you don't legally own the hardware in question. | It is fundamentally not possible to be completely secure if the client is not locked down. At some point the bytes will exist in memory, and that memory can be read by hostile applications.
If your goal isn't to make it completely secure but merely inconvenient for the casually curious, then just be sure to not write the data to temporary files or anywhere else that would be trivial to examine. | Securing java runtime data on an untrusted client | [
"",
"java",
"security",
"encryption",
""
] |
I've had a hard time understanding the difference between composition and aggregation in UML. Can someone please offer me a good compare and contrast between them? I'd also love to learn to recognize the difference between them in code and/or to see a short software/code example.
Edit: Part of the reason why I ask is because of a reverse documentation activity that we're doing at work. We have written the code, but we need to go back and create class diagrams for the code. We'd just like to capture the associations properly. | The distinction between aggregation and composition depends on context.
Take the car example mentioned in another answer - yes, it is true that a car exhaust can stand "on its own" so may not be in composition with a car - but it depends on the application. If you build an application that actually has to deal with stand alone car exhausts (a car shop management application?), aggregation would be your choice. But if this is a simple racing game and the car exhaust only serves as part of a car - well, composition would be quite fine.
Chess board? Same problem. A chess piece doesn't exist without a chess board only in certain applications. In others (like that of a toy manufacturer), a chess piece can surely not be composed into a chess board.
Things get even worse when trying to map composition/aggregation to your favorite programming language. In some languages, the difference can be easier to notice ("by reference" vs. "by value", when things are simple) but in others may not exist at all.
And one last word of advice? Don't waste too much time on this issue. It isn't worth it. The distinction is hardly useful in practice (even if you have a completely clear "composition", you may still want to implement it as an aggregation due to technical reasons - for example, caching). | As a rule of thumb:

```
class Person {
private Heart heart;
private List<Hand> hands;
}
class City {
private List<Tree> trees;
private List<Car> cars
}
```
**In composition** (Person, Heart, Hand), "sub objects" (Heart, Hand) will be destroyed as soon as Person is destroyed.
**In aggregation** (City, Tree, Car) "sub objects" (Tree, Car) will NOT be destroyed when City is destroyed.
**The bottom line is, composition stresses on mutual existence, and in aggregation, this property is NOT required.** | Aggregation versus Composition | [
"",
"java",
"oop",
"uml",
""
] |
I am using hibernate as my ORM solution, with EHCache as the Second Level (Read-Write) cache.
My question is: Is it possible to access the Second Level cache directly?
I want to access this: <http://www.hibernate.org/hib_docs/v3/api/org/hibernate/cache/ReadWriteCache.html>
How can I access the same ReadWriteCache that is being used by Hibernate?
I have some direct/custom JDBC inserts that I am doing, and I want to add those objects to the 2nd level cache myself. | I would call "afterInsert" on the EntityPersister that maps to your entity since Read/Write is an asynchronous concurrency strategy. I pieced this together after looking through the Hibernate 3.3 source. I am not 100% that this will work, but it looks good to me.
```
EntityPersister persister = ((SessionFactoryImpl) session.getSessionFactory()).getEntityPersister("theNameOfYourEntity");
if (persister.hasCache() &&
!persister.isCacheInvalidationRequired() &&
session.getCacheMode().isPutEnabled()) {
CacheKey ck = new CacheKey(
theEntityToBeCached.getId(),
persister.getIdentifierType(),
persister.getRootEntityName(),
session.getEntityMode(),
session.getFactory()
);
persister.getCacheAccessStrategy().afterInsert(ck, theEntityToBeCached, null);
}
```
--
```
/**
* Called after an item has been inserted (after the transaction completes),
* instead of calling release().
* This method is used by "asynchronous" concurrency strategies.
*
* @param key The item key
* @param value The item
* @param version The item's version value
* @return Were the contents of the cache actual changed by this operation?
* @throws CacheException Propogated from underlying {@link org.hibernate.cache.Region}
*/
public boolean afterInsert(Object key, Object value, Object version) throws CacheException;
``` | I did this by creating my own cache provider. I just overrode EhCacheProvider and used my own variable for the manager so I could return it in a static. Once you get the CacheManager, you can call manager.getCache(class\_name) to get a Cache for that entity type. Then you build a CacheKey using the primary key, the type, and the class name:
```
CacheKey cacheKey = new CacheKey(key, type, class_name, EntityMode.POJO,
(SessionFactoryImplementor)session.getSessionFactory());
```
The Cache is essentially a map so you can check to see if your object is in the cache, or iterate through the entities.
There might be a way to access the CacheProvider when you build the SessionFactory initially which would avoid the need to implement your own. | Manipulating Hibernate 2nd Level Cache | [
"",
"java",
"hibernate",
"caching",
"jakarta-ee",
"ehcache",
""
] |
I'm self-learning C#, OOP, and WPF so the potential for stuff ups is staggering.
So given that, can someone please explain why after clicking the button in my tiny test example the Name property appears in the TextBox but the ListBox shows nothing?
## **XAML:**
```
<Window x:Class="BindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindingTest" Height="250" Width="300">
<Grid Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Button
Grid.Row="0"
Name="MakeIntListButton"
Click="MakeIntListButton_Click">Make and Display Integer List</Button>
<TextBox Grid.Row="1" Text ="{Binding Path=Name}"
/>
<ListBox
Grid.Row="2"
ItemsSource="{Binding Path=MyIntegers}"
/>
</Grid>
```
## **C#:**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BindingTest
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void MakeIntListButton_Click(object sender, RoutedEventArgs e)
{
AClass InstanceOfAClass = new AClass();
InstanceOfAClass.MyIntegers.Add(6);
InstanceOfAClass.MyIntegers.Add(7);
InstanceOfAClass.MyIntegers.Add(42);
InstanceOfAClass.Name = "Fred";
mainGrid.DataContext =InstanceOfAClass ;
}
}
public class AClass
{
public string Name {get;set;}
public List<int> MyIntegers = new List<int>();
}
}
``` | Part of me wonders whether it's something to do with the fact that "MyIntegers" is a public field rather than a property. Can you refactor you class to look like this and try it?
```
public class AClass
{
private List<int> _ints = new List<int>();
public string Name { get; set; }
public List<int> MyIntegers
{
get { return _ints; }
}
}
``` | Look into using the System.Collections.ObjectModel.ObservableCollection for list binding instead of a plain List. | How do I bind to a List<T> using DataContext? | [
"",
"c#",
".net",
"wpf",
"xaml",
""
] |
I am working on a form in C# that is used for displaying information, but I still need to allow some manipulation of the information. What I really want to do is remove the border from a combobox, this would allow me to display the information while also allowing the user to select other items in the set without having to display them all.
To be more specific I have a list of 4 or 5 email addresses, but I only want to display one at a time while allowing the user a way to easily select a different item. I have searched all over but can't find an easy way to modify the border of a combobox, and a border less combobox will fit my needs nicely.
I just started with C# so I'm still learning, maybe I am missing something. Seems like this should be a lot easier than it's turning out to be, hopefully somebody can help me out.
EDIT:
The form is using labels to display information, so having a combobox in the middle of it makes it look awful. Basically what I'm looking for is a Link that when clicked opens the default email program and fills in the address, but I want the drop-down button so an alternate address can be selected. I don't want to display a huge list of addresses if I don't have to, I just want to display one at a time. Like a combobox, but with no border.
I could probably just add a button that displays a list of the alternate addresses, but why reinvent the wheel if I can just remove the border from a combobox and have exactly what I'm looking for?
Thanks | Perhaps you don't need a ComboBox at all. Assuming you're using Windows Forms, You could use a standard TextBox and add your list of email addresses to its AutoCompleteCustomSource (and set AutoCompleteSource to "CustomSource").
Then if you set the TextBox's AutoCompleteMode to "Append" the user will never see the full list of email addresses - they'll just get the closes match populated in the TextBox as they type. With a bit of code-behind you might even be able to introduce the ability to cycle through the available items with the up and down arrow keys.
**Edit**
Now that you've updated your question, I'll suggest a completely different approach.
Add the "default" email address as a standard Label. Heck - add it as a LinkLabel and make it clickable so it behaves like a mailto: link on a web page. Next to that label, add a normal Button. Set its FlatStyle property to "System", Font name to "Marlett" and caption to "u", so it has a nice "dropdown button" look to it.
Now add a ContextMenuStrip to your form and add a menu item for each email address. You could do this in code pretty easily.
Now add this Click event handler for your button:
```
private void button1_Click(object sender, EventArgs e)
{
contextMenuStrip1.Show(button1, new Point(0, button1.Height));
}
```
So when the button is clicked, the menu pops up displaying the "alternate" email addresses. All you'll need to do is catch the Click event of the menu items to "use" the selected email address. | Why would you need the `ComboBox` to be borderless? Doesn't make much sense to me.
Make you can do is make a read-only `ComboBox`. You can populate the entries and the user will be allowed to select them but not type in any text.
Just set `DropDownStyle` to `ComboBoxStyle.DropDownList`.
```
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
```
---
### Update:
You can try "hiding" the border by setting `DrawMode` to `DrawMode.OwnerDrawFixed`.
```
this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
```
This won't hide it but makes it less visible. | Remove the border from a combobox | [
"",
"c#",
"controls",
""
] |
We have a big winforms C# application, that's basically a frontend for some databases (CRUD stuff) and I'm trying to implement some in memory cache for business objects.
Something like:
```
List<Customer> customerCache; // Loaded during app. startup
```
I've already created some code to keep the cache up-to-date with the database. This code run on a separate thread all the time, and is working really well.
My problem is that depending on the size of the cache, it's faster to do a 'select \* from customers where id = x' in the database than looping through the cache with a foreach (foreach Customer cmr in customerCache) to find that specific object...
Is there a way to search for specific objects in my cache really fast ? I was going to try some algorithm or changing the type of my collection, but I would appreciate listening to your suggestions.
Please note that we have several 'List xxxCache' and everything is fast (for small N, off course). But when the number of cached itens grow (> 3000 normally) its faster to read from the database.
What's the best way to loop through my cached items to find a specific one ? All business items inherit from a common ancestor and have an 'ID' property(integer, unique).
Sorry for my bad english, it's not my primary language.
Best regards,
Greetings from Brazil. | Use `Dictionary<int, Customer>` instead. It supports O(1) lookup based on a key. In this case, key would be Customer.Id.
You might also want to look into other pre-built database caching solutions for .Net. | We have a similar case for the web form application.
We use MS Enterprise Lib Cache block.
It is easy to implement and use.
The only thing you need to focus in Cache Key (string type)
cache.add(key, object)
cache.getdata(key) | Cache lookup performance | [
"",
"c#",
"performance",
"caching",
"lookup",
""
] |
I am trying to access the `Text` property of a textbox from a partial postback-done in an Update Panel. The problem is that this textbox I want to access **is not** in this Update Panel, and when I am trying to write to it (putting content in the `Text` property), this new content is not being displayed.
I think that this is because this textbox is not part of the Update Panel's, but I'm not sure about it. And also, I cannot put this Textbox in the same update panel as the one I'm triggering a partial postback.
Why isn't the text being displayed? | During a partial page rending only controls contained within an update panel will have thier html refreshed. The rest of the page will remain the same.
For your specific case you would need to wrap your text box in an update panel, then you hnave a decision to make. You can either mark its UpdateMode as Always or Conditional. If you mark it as always then all the controls contained within that update panel will get updated durning every partial rendering. If you mark it conditional then you will need to call the update panels Update() method to have it's html refreshed. | I don't think you can, unless you put the text box in a second update panel with the update mode set to Conditional. Then you invoke the update method or set the first update panel as an asyncpostbacktrigger to the new one. | Writing to a text box from an update panel | [
"",
"c#",
"asp.net",
"updatepanel",
""
] |
**Duplicate:** [How do I best catch up with the latest developments in java?](https://stackoverflow.com/questions/638192/how-do-i-best-catch-up-with-the-latest-developments-in-java)
I've been working on a Java codebase that was frozen in time around 2001. As a result I haven't bothered to learn any new Java syntax since then.
Today I saw this code and recognized it as a syntax that must have been introduced in the current decade.
```
private ArrayList<String> colors = new ArrayList<String>();
```
Which version of Java introduced this angle-bracket notation?
And what would be a good way to learn about other significant changes to the language since 2001? I have a pretty good grasp of everything before that date. | Of all recent Java release, Java 5 made the largest and most obvious changes to the language. [The summary](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html) lists all the new features. In brief:
* [autoboxing](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#boxing)
* [enum](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#enums), e.g., `enum Season { WINTER, SPRING, SUMMER, FALL }`
* [Generics](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#generics), e.g., `Collection<String> coll;` instead of `Collection coll;`
* [ehanced for loop](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#forloop), e.g., `for (String str : coll)`
* [varargs](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#varargs), e.g., `private void function(Object... arguments);`
* [static import](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#static_import)
* [Annotations](http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#annotations), e.g., `@Override` or `@Deprecated`
* `String.format` like a Java version of `printf()`
Java 4 introduced a few new features too, primarily [assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html).
If you prefer books, you can learn about Java 5 changes from the book [Java 5.0 Tiger: A Developer's Notebook](http://oreilly.com/catalog/9780596007386/). This isn't the most comprehensive book you'll find, but it's a nice and quick introduction to all of the new features of Java 5. | You're referring to generics, introduced in Java SE 1.5 (or Java 5). Enums got a bit more exciting in the Java 5 release as well as the Java autoboxing and unboxing, annotations and much much more.
<http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html>
<http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html>
Overview:
<http://java.sun.com/j2se/1.5.0/docs/guide/language/>
When you want to get up to speed on Java 6, check out <http://java.sun.com/javase/6/features.jsp> | What's the best way to get up to speed on changes in Java syntax since 2001? | [
"",
"java",
"syntax",
""
] |
I use the following code to save Chinese characters into a .txt file, but when I opened it with Wordpad, I couldn't read it.
```
StringBuffer Shanghai_StrBuf = new StringBuffer("\u4E0A\u6D77");
boolean Append = true;
FileOutputStream fos;
fos = new FileOutputStream(FileName, Append);
for (int i = 0;i < Shanghai_StrBuf.length(); i++) {
fos.write(Shanghai_StrBuf.charAt(i));
}
fos.close();
```
What can I do ? I know if I cut and paste Chinese characters into Wordpad, I can save it into a .txt file. How do I do that in Java ? | There are several factors at work here:
* Text files have no intrinsic metadata for describing their encoding (for all the talk of angle-bracket taxes, there are reasons XML is popular)
* The default encoding for Windows is still an 8bit (or doublebyte) "[ANSI](http://blogs.msdn.com/oldnewthing/archive/2004/05/31/144893.aspx)" character set with a limited range of values - text files written in this format are not portable
* To tell a Unicode file from an ANSI file, Windows apps rely on the presence of a [byte order mark](http://unicode.org/faq/utf_bom.html#bom4) at the start of the file ([not strictly true - Raymond Chen explains](http://blogs.msdn.com/oldnewthing/archive/2007/04/17/2158334.aspx)). In theory, the BOM is there to tell you the [endianess](http://en.wikipedia.org/wiki/Endianness) (byte order) of the data. For UTF-8, even though there is only one byte order, Windows apps rely on the marker bytes to automatically figure out that it is Unicode (though you'll note that Notepad has an encoding option on its open/save dialogs).
* It is wrong to say that Java is broken because it does not write a UTF-8 BOM automatically. On Unix systems, it would be an error to write a BOM to a script file, for example, and many Unix systems use UTF-8 as their default encoding. There are times when you don't want it on Windows, either, like when you're appending data to an existing file: `fos = new FileOutputStream(FileName,Append);`
Here is a method of reliably appending UTF-8 data to a file:
```
private static void writeUtf8ToFile(File file, boolean append, String data)
throws IOException {
boolean skipBOM = append && file.isFile() && (file.length() > 0);
Closer res = new Closer();
try {
OutputStream out = res.using(new FileOutputStream(file, append));
Writer writer = res.using(new OutputStreamWriter(out, Charset
.forName("UTF-8")));
if (!skipBOM) {
writer.write('\uFEFF');
}
writer.write(data);
} finally {
res.close();
}
}
```
Usage:
```
public static void main(String[] args) throws IOException {
String chinese = "\u4E0A\u6D77";
boolean append = true;
writeUtf8ToFile(new File("chinese.txt"), append, chinese);
}
```
Note: if the file already existed and you chose to append and existing data *wasn't* UTF-8 encoded, the only thing that code will create is a mess.
Here is the `Closer` type used in this code:
```
public class Closer implements Closeable {
private Closeable closeable;
public <T extends Closeable> T using(T t) {
closeable = t;
return t;
}
@Override public void close() throws IOException {
if (closeable != null) {
closeable.close();
}
}
}
```
This code makes a Windows-style best guess about how to read the file based on byte order marks:
```
private static final Charset[] UTF_ENCODINGS = { Charset.forName("UTF-8"),
Charset.forName("UTF-16LE"), Charset.forName("UTF-16BE") };
private static Charset getEncoding(InputStream in) throws IOException {
charsetLoop: for (Charset encodings : UTF_ENCODINGS) {
byte[] bom = "\uFEFF".getBytes(encodings);
in.mark(bom.length);
for (byte b : bom) {
if ((0xFF & b) != in.read()) {
in.reset();
continue charsetLoop;
}
}
return encodings;
}
return Charset.defaultCharset();
}
private static String readText(File file) throws IOException {
Closer res = new Closer();
try {
InputStream in = res.using(new FileInputStream(file));
InputStream bin = res.using(new BufferedInputStream(in));
Reader reader = res.using(new InputStreamReader(bin, getEncoding(bin)));
StringBuilder out = new StringBuilder();
for (int ch = reader.read(); ch != -1; ch = reader.read())
out.append((char) ch);
return out.toString();
} finally {
res.close();
}
}
```
Usage:
```
public static void main(String[] args) throws IOException {
System.out.println(readText(new File("chinese.txt")));
}
```
(System.out uses the default encoding, so whether it prints anything sensible depends on your platform and [configuration](http://illegalargumentexception.blogspot.com/2009/04/java-unicode-on-windows-command-line.html).) | If you can rely that the default character encoding is UTF-8 (or some other Unicode encoding), you may use the following:
```
Writer w = new FileWriter("test.txt");
w.append("上海");
w.close();
```
The safest way is to always explicitly specify the encoding:
```
Writer w = new OutputStreamWriter(new FileOutputStream("test.txt"), "UTF-8");
w.append("上海");
w.close();
```
P.S. You may use any Unicode characters in Java source code, even as method and variable names, if the -encoding parameter for javac is configured right. That makes the source code more readable than the escaped `\uXXXX` form. | How to save Chinese Characters to file with java? | [
"",
"java",
"file",
"character-encoding",
"cjk",
""
] |
I understand lambdas and the `Func` and `Action` delegates. But expressions
stump me.
In what circumstances would you use an `Expression<Func<T>>` rather than a plain old `Func<T>`? | When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).
Conceptually, `Expression<Func<T>>` is *completely different* from `Func<T>`. `Func<T>` denotes a `delegate` which is pretty much a pointer to a method and `Expression<Func<T>>` denotes a *tree data structure* for a lambda expression. This tree structure **describes what a lambda expression does** rather than doing the actual thing. It basically holds data about the composition of expressions, variables, method calls, ... (for example it holds information such as this lambda is some constant + some parameter). You can use this description to convert it to an actual method (with `Expression.Compile`) or do other stuff (like the LINQ to SQL example) with it. The act of treating lambdas as anonymous methods and expression trees is purely a compile time thing.
```
Func<int> myFunc = () => 10; // similar to: int myAnonMethod() { return 10; }
```
will effectively compile to an IL method that gets nothing and returns 10.
```
Expression<Func<int>> myExpression = () => 10;
```
will be converted to a data structure that describes an expression that gets no parameters and returns the value 10:
[ *larger image*](https://i.stack.imgur.com/gwU0E.jpg)
While they both look the same at compile time, what the compiler generates is **totally different**. | I'm adding an answer-for-noobs because these answers seemed over my head, until I realized how simple it is. Sometimes it's your expectation that it's complicated that makes you unable to 'wrap your head around it'.
I didn't need to understand the difference until I walked into a really annoying 'bug' trying to use LINQ-to-SQL generically:
```
public IEnumerable<T> Get(Func<T, bool> conditionLambda){
using(var db = new DbContext()){
return db.Set<T>.Where(conditionLambda);
}
}
```
This worked great until I started getting OutofMemoryExceptions on larger datasets. Setting breakpoints inside the lambda made me realize that it was iterating through each row in my table one-by-one looking for matches to my lambda condition. This stumped me for a while, because why the heck is it treating my data table as a giant IEnumerable instead of doing LINQ-to-SQL like it's supposed to? It was also doing the exact same thing in my LINQ-to-MongoDb counterpart.
The fix was simply to turn `Func<T, bool>` into `Expression<Func<T, bool>>`, so I googled why it needs an `Expression` instead of `Func`, ending up here.
**An expression simply turns a delegate into a data about itself.** So `a => a + 1` becomes something like "On the left side there's an `int a`. On the right side you add 1 to it." **That's it.** You can go home now. It's obviously more structured than that, but that's essentially all an expression tree really is--nothing to wrap your head around.
Understanding that, it becomes clear why LINQ-to-SQL needs an `Expression`, and a `Func` isn't adequate. `Func` doesn't carry with it a way to get into itself, to see the nitty-gritty of how to translate it into a SQL/MongoDb/other query. You can't see whether it's doing addition or multiplication or subtraction. All you can do is run it. `Expression`, on the other hand, allows you to look inside the delegate and see everything it wants to do. This empowers you to translate the delegate into whatever you want, like a SQL query. `Func` didn't work because my DbContext was blind to the contents of the lambda expression. Because of this, it couldn't turn the lambda expression into SQL; however, it did the next best thing and iterated that conditional through each row in my table.
Edit: expounding on my last sentence at John Peter's request:
IQueryable extends IEnumerable, so IEnumerable's methods like `Where()` obtain overloads that accept `Expression`. When you pass an `Expression` to that, you keep an IQueryable as a result, but when you pass a `Func`, you're falling back on the base IEnumerable and you'll get an IEnumerable as a result. In other words, without noticing you've turned your dataset into a list to be iterated as opposed to something to query. It's hard to notice a difference until you really look under the hood at the signatures. | Why would you use Expression<Func<T>> rather than Func<T>? | [
"",
"c#",
"delegates",
"lambda",
"expression-trees",
""
] |
There appears to be a Validate package in Pear that I'm interested in useing in production. Our site has about 20M uniques across 10 languages, so as part of due diligence, thought I'd asked around here.
Does anyone have any experience with this PEAR package?
Is it ready for production?
Here's the Validate package in question:
<http://pear.php.net/package/Validate>
Intro:
<http://pear.php.net/manual/en/package.validate.validate.php>
Bugs (only 78 ever filed...)
<http://pear.php.net/bugs/search.php?cmd=display&package_name[]=Validate&status=All> | Judging by the revision number and the revision title. (0.8.2 (Beta)) i would say no. Personally i would advice against using any Beta product in production, though there are many cases that it worked out fine (stackoverflow for example). Though you are always running a risk of something happening. | I'd strongly advise against integrating the PEAR code you use into your own code-base.
What happens then if a new version of one of the PEAR packages you use is released to fix security issues and there are multiple dependencies from that package onto others?
Do you download the new versions and check everything works ok and that you've not added a bug yourself by missing something?
The best thing to do, if you are paranoid of the system-wide PEAR install being compromised, is to make your own PEAR install. <http://pear.php.net/manual/en/installation.shared.php> would be where to start for doing this.
Then it's just a case of doing $pear upgrade [Package] rather than copying loads of files around. | Is the Validate PEAR package ready for production? | [
"",
"php",
"validation",
"pear",
""
] |
I maintain a cross platform application, based on PyQt that runs on linux mac and windows.
The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).
I would like to add an "auto update" functionality, based on patches to limit downloads size:
* check for new versions on an http server
* download the patches needed to update to the last version
* apply the patches list and restart the application
I have some questions:
* what is the preferred way to update a windows application since open files are locked and can't be overwritten ?
* how do I prepare and apply the patches ? perhaps using [bsdiff/pspatch](http://www.daemonology.net/bsdiff/) ?
**[update]**
I made a simple class to make patches with [bsdiff](http://www.daemonology.net/bsdiff/), which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.
The code is available in the 'update' package of [pyflu](http://pypi.python.org/pypi/pyflu), a small library of Python code. | I don't believe py2exe supports patched updates. However, if you do not bundle the entire package into a single EXE ([py2exe website example](http://www.py2exe.org/index.cgi/SingleFileExecutable) - bottom of page), **you can get away with smaller updates by just replacing certain files**, like the EXE file, for example. This can reduce the size of your updates significantly.
You can write a separate **updater app**, which can be downloaded/ran from inside your application. This app may be different for every update, as the files that need to be updated may change.
Once the application launches the updater, it will need to close itself so the files can be overwritten. Once the updater is complete, you can have it reopen the application before closing itself. | I don't know about patches, but on OS X the "standard" for this with cocoa apps is [Sparkle](http://sparkle.andymatuschak.org/). Basically it does "appcasting". It downloads the full app each time. It might be worth looking at it for inspiration.
I imagine on OS X you can probably just download the actual part of your app bundle that contains your specific code (not the libs etc that get packaged in) and that'd be fairly small and easy to replace in the bundle.
On Windows, you'd probably be able to do a similar trick by not bundling your app into one exe - thus letting you change the one file that has actually changed.
I'd imagine your actual Python code would be much less than 40Mb, so that's probably the way to go.
As for replacing the running app, well first you need to find it's location, so you could use `sys.executable` to get you a starting point, then you could probably fork a child process to, kill the parent process and have the child doing the actual replacement?
I'm currently playing around with a small wxPython app and wondering about exactly this problem. I'd love to hear about what you come up with.
Also how big is you app when compressed? If it compresses well then maybe you can still afford to send the whole thing. | Self updating py2exe/py2app application | [
"",
"python",
"deployment",
"patch",
"py2exe",
""
] |
I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second? | I tried using the nr parameter, without any luck.
I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML:
Here are my two submit buttons:
```
<input type="submit" name="Preview" value="Preview" />
<input type="submit" name="Create" value="Create New Page" />
```
... and here's the code that clicks the first one, goes back, and then clicks the second:
```
from mechanize import Browser
self.br = Browser()
self.br.open('http://foo.com/path/to/page.html')
self.br.select_form(name='my_form')
self.br['somefieldname'] = 'Foo'
submit_response = self.br.submit(name='Preview', label='Preview')
self.br.back()
self.br.select_form(name='my_form')
self.br['somefieldname'] = 'Bar'
submit_response = self.br.submit(name='Create', label='Create New Page')
```
There's a variant that also worked for me, where the "name" of the submit button is the same, such as:
```
<input type="submit" name="action" value="Preview" />
<input type="submit" name="action" value="Save" />
<input type="submit" name="action" value="Cancel" />
```
and
```
self.br.select_form(name='my_form')
submit_response = self.br.submit(name='action', label='Preview')
self.br.back()
submit_response = self.br.submit(name='action', label='Save')
```
IMPORTANT NOTE - I was *only* able to get any of this multiple-submit-button code to work **after** cleaning up some HTML in the rest of the page.
Specifically, I could not have `<br/>` - instead I had to have `<br />` ... and, making even less sense, I could not have anything between the two submit buttons.
It frustrated me to no end that the mechanize/ClientForm bug I hunted for over two hours boiled down to this:
```
<tr><td colspan="2"><br/><input type="submit" name="Preview" value="Preview" /> <input type="submit" name="Create" value="Create New Page" /></td></tr>
```
(all on one line) did not work, but
```
<tr><td colspan="2"><br />
<input type="submit" name="Preview" value="Preview" />
<input type="submit" name="Create" value="Create New Page" /></td></tr>
```
worked fine (on multiple lines, which also shouldn't have mattered).
I like mechanize because it was easy to install (just copy the files into my include directory) and because it's pretty simple to use, but unless I'm missing something major, I think that bugs like this are kind of awful - I can't think of a good reason at all why the first example there should fail and the second should work.
And, incidentally, I also found another mechanize bug where a `<textarea>` which is contained within a `<p>` is not recognized as a valid control, but once you take it out of the `<p>` container it's recognized just fine. And I checked, textarea **is** allowed to be included in other block-level elements like `<p>`. | I would suggest you to use Twill which uses mechanize (mostly monkeypatched).
So say you have form with some fields and two submit buttons with **names** "submit\_to\_preview" and "real\_submit". Following code should work.
BTW remember this is not threadsafe so you might want to use locks in case if you want to use the code in a threaded env.
```
import twill.commands
b = twill.get_browser()
url = "http://site/myform"
twill.commands.go(url)
twill.commands.fv("2", "name", "Me")
twill.commands.fv("2", "age", "32")
twill.commands.fv("2", "comment", "useful article")
twill.commands.browser.submit("real_submit")
```
Hope that helps. Cheers. | Python mechanize - two buttons of type 'submit' | [
"",
"python",
"mechanize",
""
] |
I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net "Snakelets") and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered [TurboGears](http://turbogears.org "TurboGears") and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.
But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between ***"doing it the right way"***, e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious:
1. I'm not learning anything in the process
2. If I ever need to do anything lower level it's going to be a pain
3. The overhead required for just a basic site which uses authentication is insane. (IMO)
So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such.
---
Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework.
Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away. | I suggest taking another look at TG2. I think people have failed to notice some of the strides that have been made since the last version. Aside from the growing WSGI stack of utilities available there are quite a few TG2-specific items to consider. Here are a couple of highlights:
[TurboGears Administration System](http://turbogears.org/2.0/docs/main/Extensions/index.html) - This CRUD interface to your database is fully customizable using a declarative config class. It is also integrated with Dojo to give you infinitely scrollable tables. Server side validation is also automated. The admin interface uses RESTful urls and HTTP verbs which means it would be easy to connect to programatically using industry standards.
[CrudRestController](http://turbogears.org/2.0/docs/main/Extensions/Crud/index.html)/[RestController](http://turbogears.org/2.0/docs/modules/tgcontroller.html?highlight=restcontroller#tg.controllers.RestController) - TurboGears provides a structured way to handle services in your controller. Providing you the ability to use standardized HTTP verbs simply by extending our RestController. Combine [Sprox](http://www.sprox.org) with CrudRestController, and you can put crud anywhere in your application with fully-customizable autogenerated forms.
TurboGears now supports mime-types as file extensions in the url, so you can have your controller render .json and .xml with the same interface it uses to render html (returning a dictionary from a controller)
If you click the links you will see that we have a new set of documentation built with sphinx which is more extensive than the docs of the past.
With the best [web server](http://pylonshq.com), [ORM](http://www.sqlalchemy.org), and [template system](http://genshi.edgewall.org/)(s) (pick your own) under the hood, it's easy to see why TG makes sense for people who want to get going quickly, and still have scalability as their site grows.
TurboGears is often seen as trying to hit a moving target, but we are consistent about releases, which means you won't have to worry about working out of the trunk to get the latest features you need. Coming to the future: more TurboGears extensions that will allow your application to grow functionality with the ease of paster commands. | > the religious debates between the Django and WSGI camps
It would seem as though you're a tad bit confused about what WSGI is and what Django is. Saying that Django and WSGI are competing is a bit like saying that C and SQL are competing: you're comparing apples and oranges.
Django is a framework, WSGI is a protocol (which is supported by Django) for how the server interacts with the framework. Most importantly, learning to use WSGI directly is a bit like learning assembly. It's a great learning experience, but it's not really something you should do for production code (nor was it intended to be).
At any rate, my advice is to figure it out for yourself. Most frameworks have a "make a wiki/blog/poll in an hour" type exercise. Spend a little time with each one and figure out which one you like best. After all, how can you decide between different frameworks if you're not willing to try them out? | Django vs other Python web frameworks? | [
"",
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears",
""
] |
I need to know how the a .net web service authenticates a request from a client that is using a certificate. I know that the client will have to attach their certificate to the service proxy before they make a request, but I dont know how to check that the correct computer is contacting us.
This needs to be implemented in a shared hosting environment using .Net framework 2.0. Please advise if this is possible or if web should use another authentication method such as Basic Authentication over SSL
Let me know if you need more information.
Thanks | The web service doesn't do the authentication - IIS does. Look on the "Security" tab of the site or application properties. At the bottom, there's an "Edit" button. The bottom of the dialog that appears allows you to enable client certificate mapping, and to specify how to map client certificates to Windows users.
The web service will simply see the clients as authenticated Windows users (which is what they are). | See [Using Web Services Enhancements (WSE) for X.509 Certificate Authentication and Digital Signature](http://www.eggheadcafe.com/articles/20021231.asp). I'd recommend WCF on .NET 3.5 if possible though. | how to authenicate clients using certificates in an ASP.NET web service | [
"",
"c#",
"asp.net",
"web-services",
"authentication",
""
] |
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`?
I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"? | You seek the all-powerful `*?`
From the docs, [Greedy versus Non-Greedy](http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy)
> the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?` [...] match as *little*
> text as possible. | ```
>>> x = "a (b) c (d) e"
>>> re.search(r"\(.*\)", x).group()
'(b) c (d)'
>>> re.search(r"\(.*?\)", x).group()
'(b)'
```
[According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax):
> The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE `<.*>` is matched against '`<H1>title</H1>`', it will match the entire string, and not just '`<H1>`'. Adding '`?`' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using `.*?` in the previous expression will match only '`<H1>`'. | Python non-greedy regexes | [
"",
"python",
"regex",
"regex-greedy",
""
] |
I have a RichBox(memo) that I'd like to add lines to.
Currently,I use this
```
RichBox1.text += "the line I'd like to add" + "\n";
```
Isn't there something like the method in Delphi below?
```
Memo.Lines.add('The line I''d like to add');
``` | [AppendText](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.appendtext(VS.71).aspx) is the closest it gets. Unfortunately you still have to append the newline character:
```
RichBox1.AppendText( "the line I'd like to add" + Environment.NewLine );
``` | You could use an extension method to add this handy `add` method to the RichTextBox class.
<http://msdn.microsoft.com/en-us/library/bb383977.aspx>
```
public static class Extension
{
public static void add(this System.Windows.Forms.RichTextBox richText, string line)
{
richText.Text += line + '\n';
}
}
``` | C#: How to add a line to a memo? | [
"",
"c#",
"winforms",
""
] |
Has anyone got an idea regarding the motivation behind the awkward design of the java.lang.System.out?
Awkwardness:
First, the *out* member is exposed (Encapsulation anyone?).
Second, it is **final** but can be changed via *setOut()* (contradicts final). | In Java 1.0.x `System.out` and friends were not `final`—it was possible to change them by assigning directly to them. However, this presented an issue when Sun decided to optionally restrict this behavior in Java 1.1 (for applets, at the time). To maintain at least some backwards compatibility, `out` was made final and written to with a native method, which was wrapped with the appropriate security checks. | I would bet it is exposed mainly for brevity. Compare:
```
System.out.prinln("blah");
```
with
```
System.getOut().println("blah");
```
The former is not many character shorter, but still it *is* shorter, and simpler conceptually. It is also very probably faster, perhaps especially back in the day when JIT was not too common in Java virtual machines; I bet the direct access is faster than a method call in those cases. So, it boils down to being a tradeoff.
**UPDATE:**
As for `final` and `setOut()`, the [documentation for the latter](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#setOut%28java.io.PrintStream%29) says that if there is a security manager, it will be queried to see if the caller is allowed to re-set the output stream. This might be the answer; if the `out` member had been directly assignable, there would not have been a way to protect it.
This is just my interpretation of the API and the thoughts that might be behind its design, I could be off. | Why the awkward Design of System.out? | [
"",
"java",
"api",
""
] |
If one adds many framework dependencies to a Java application, will this increase its memory footprint drastically, because it preloads all libraries at startup or is that a more lazy behaviour which would load only the needed classes when you actually need it (e.g. import statements or even later)?
Could adding many dependencies also have other negative side effects that a Java developer should be aware of? | Classes will only be loaded as required (referenced by other classes via `import` etc.)
The headache with multiple frameworks is that you have to manage their shared dependencies. e.g. Framework A requires Logging Framework X, but Framework B requires Logging Framework Y.
These problems aren't insurmountable, but you have to keep track of them. When you upgrade Framework A, you may well end up with a ripple effect, in which you have to update a corresponding dependency. That then requires another framework component update, and so on.
e.g. Framework A gets upgraded, and requires an update to Log4J. THat then forces you to update Framework B to a version compatible with your new Log4J, and so on.
If you have multiple framework requirements, this may in fact point to a requirement to subdivide your application accordingly (into different deployables/services etc.). | Conceptually you are probably also adding a large amount of overlapping functionality to your code base when you're adding a large number of frameworks. This overload can also get to be quite a headache, and you'll be having different people using different versions of the same features (from different frameworks) for no apparent reason. It can get messy. | Adding many frameworks to a Java application - will it have any negative side effects? | [
"",
"java",
"performance",
"frameworks",
""
] |
I'm in the process of reviewing a code base (~20K LOC) and trying to determine how to migrating it from 1.4.2 to 5. Obviously, it's not an overnight project and the suggestion which I have received is to write new code against Java 5 and migrate the old code in a piece-meal fashion. Also, I'm no expert in the new features in Java 5 (i.e. I know of them, but have never written any for production use).
My questions:
1. What features of Java 5 are typically used in production code? (i.e. generics, auto-boxing, etc.) Are there features to be avoided / not considered to be best-practices?
2. What are the best refactoring strategies which I can use migrate a code base of this size? (i.e. make changes to classes one at a time only when a class is edited, etc.) Objective - reduce risk on the code base. Limitation - resources to do refactoring.
Any advice is appreciated - thanks in advance.
**UPDATE - a year too late, but better late than never? =)**
Thank you for all of the comments - lots of great points of view. In the life of a software developer, there's always going to be the projects you strive to finish but never get around to because of something more "urgent".
With respect to the use of Java 5 (at that time), it was something which was required in the client's production environment, so that was why we did not use Java 6.
I found that the stronger typing for collections, enums and unboxing of primitives were the features I tend to apply the most, both to old and new code. The refactoring was fairly straight-forward, but code comprehension improved significantly and standards became easier to enforce. The ones I had the most trouble with was the generics; I think it's a concept which I still haven't had a chance to fully grasp and appreciate yet, so it was difficult for me to find previous cases where the application of generics was appropriate.
Thanks again to everyone who contributed to this thread and apologies for the late follow up. | Java 5 is almost completely backwards compatible with Java 4. Typically, the only change you **must** make when you migrate is to rename any usages of the new `enum` keyword in the Java 4 code.
The full list of potential compatibility problems is listed here:
<http://java.sun.com/j2se/1.5.0/compatibility.html>
The only other one that I've run into in practice is related to the change in the JAXP implementation. In our case, it simply meant removing xerces.jar from the classpath.
As far as refactoring goes, I think that migrating your collection classes to use the new strongly-typed generic versions and removing unnecessary casting is a good idea. But as another poster pointed out, changing to generic collections tends to work best if you work in vertical slices. Otherwise, you end up having to add casting to the code to make the generic types compatible with the non-generic types.
Another feature I like to use when I'm migrating code is the @Override annotation. It helps to catch inheritance problems when you're refactoring code.
<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html>
The new concurrency library is very useful if your code uses threading. For example, you may be able to replace home-grown thread pools with a `ThreadPoolExecutor`.
<http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#concurrency>
I would definitely take the approach of updating the code as you change it during normal maintenance. Other than the compatibility issues, I don't think there is a compelling reason to use the new Java 5 features unless you're already changing the code for other reasons. | There is one very real issue with the "viral" nature of generics; once you start introducing them at a given layer in an architecture you generally want to introduce it at the layer above & below as well. I have found that introducing generics is probably best done in full "verticals". But you do not have to do *all* the verticals at once. | Strategies for migrating medium-sized code base from Java 1.4.2 to Java 5 | [
"",
"java",
"refactoring",
"migration",
""
] |
I've been programming in C++ a while and I've used both methods:
```
class Stuff {
public:
Stuff( int nr ) : n( nr ) { }
private:
int n;
}
```
Or
```
class Stuff {
public:
Stuff( int nr ) {
n = nr;
}
private:
int n;
}
```
Note: This is not the same as [this](https://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration), similar but not the same.
What is considered best practice? | Initializer lists are preferred. See [FAQ 10.6](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6) | One big advantage to using initializers: If an exception is thrown anywhere within the initializer list, the destructors will be called for those members that had already been initialized -- and only for those members.
When you use the contructor body to initialize the object, it's up to you to handle exceptions properly and unwind the object as appropriate. This is usually much harder to get right. | Initializing in constructors, best practice? | [
"",
"c++",
""
] |
I have some image processing code that loops through 2 multi-dimensional byte arrays (of the same size). It takes a value from the source array, performs a calculation on it and then stores the result in another array.
```
int xSize = ResultImageData.GetLength(0);
int ySize = ResultImageData.GetLength(1);
for (int x = 0; x < xSize; x++)
{
for (int y = 0; y < ySize; y++)
{
ResultImageData[x, y] = (byte)((CurrentImageData[x, y] * AlphaValue) +
(AlphaImageData[x, y] * OneMinusAlphaValue));
}
}
```
The loop currently takes ~11ms, which I assume is mostly due to accessing the byte arrays values as the calculation is pretty simple (2 multiplications and 1 addition).
Is there anything I can do to speed this up? It is a time critical part of my program and this code gets called 80-100 times per second, so any speed gains, however small will make a difference. Also at the moment xSize = 768 and ySize = 576, but this will increase in the future.
**Update**: Thanks to [Guffa](https://stackoverflow.com/users/69083/guffa) (see answer below), the following code saves me 4-5ms per loop. Although it is *unsafe* code.
```
int size = ResultImageData.Length;
int counter = 0;
unsafe
{
fixed (byte* r = ResultImageData, c = CurrentImageData, a = AlphaImageData)
{
while (size > 0)
{
*(r + counter) = (byte)(*(c + counter) * AlphaValue +
*(a + counter) * OneMinusAlphaValue);
counter++;
size--;
}
}
}
``` | To get any real speadup for this code you would need to use pointers to access the arrays, that removes all the index calculations and bounds checking.
```
int size = ResultImageData.Length;
unsafe
{
fixed(byte* rp = ResultImageData, cp = CurrentImageData, ap = AlphaImageData)
{
byte* r = rp;
byte* c = cp;
byte* a = ap;
while (size > 0)
{
*r = (byte)(*c * AlphaValue + *a * OneMinusAlphaValue);
r++;
c++;
a++;
size--;
}
}
}
```
Edit:
Fixed variables can't be changed, so I added code to copy the pointers to new pointers that can be changed. | These are all independent calculations so if you have a multicore CPU you should be able to gain some benefit by parallelizing the calculation. Note that you'd need to keep the threads around and just hand them work to do since the overhead of thread creation would probably make this slower rather than faster if the threads are recreated each time.
The other thing that may work is farming the work off to the graphics processor. Look at [this question](https://stackoverflow.com/questions/375011/utilizing-the-gpu-with-c) for some ideas, for example, using [Accelerator](http://research.microsoft.com/en-us/projects/Accelerator/). | Can this code be optimised? | [
"",
"c#",
".net",
"optimization",
"image-processing",
""
] |
How do I load the following nested XML into a DataSet?
```
<items>
<item>
<id>i1</id>
<name>item1</name>
<subitems>
<name>subitem1</name>
<name>subitem2</name>
</subitems>
</item>
<item>
<id>i2</id>
<name>item2</name>
<subitems>
<name>subitem1</name>
<name>subitem2</name>
</subitems>
</item>
</items>
```
I can get as far as a the "item" table but how do I get the subitems?
```
MemoryStream itemsStream = new MemoryStream(Encoding.ASCII.GetBytes(itemsXML));
DataSet itemsSet = new DataSet();
itemsSet.ReadXml(itemsStream);
foreach (DataRow itemRow in itemsSet.Tables["item"].Rows) {
Console.WriteLine("column id=" + itemRow["id"] as string + " name=" + itemRow["name"] as string);
}
``` | This works for me, the only liberty I have taken is to Change the field name for the subitems.
Original XML for subitem
```
<subitems>
<name>subitem1</name>
<name>subitem2</name>
</subitems>
```
Modified XML for subitem
```
<subitems>
<name1>subitem1</name1>
<name2>subitem2</name2>
</subitems>
```
Here is the code.
```
DataSet myDS = new DataSet();
DataTable myTable = new DataTable("item");
myTable.Columns.Add("id", typeof(string));
myTable.Columns.Add("name", typeof(string));
myTable.Columns.Add("name1", typeof(string));
myTable.Columns.Add("name2", typeof(string));
myDS.Tables.Add(myTable);
string xmlData = "<items> <item> <id>i1</id> <name>item1</name> <subitems> <name1>subitem1</name1> <name2>subitem2</name2> </subitems> </item> <item> <id>i2</id> <name>item2</name> <subitems> <name1>subitem3</name1> <name2>subitem4</name2> </subitems></item></items>";
System.IO.MemoryStream itemsStream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(xmlData));
myDS.ReadXml(itemsStream, XmlReadMode.IgnoreSchema);
foreach (DataRow itemRow in myDS.Tables["item"].Rows)
{
MessageBox.Show("column id=" + itemRow["id"] + " name=" + itemRow["name"]);
MessageBox.Show(itemRow["name1"].ToString() + " - " + itemRow["name2"].ToString());
}
``` | Use dataset ReadXml. You have to follow article on link below backwards:
<http://msdn.microsoft.com/en-us/library/7sfkwf9s(v=VS.100).aspx>
For Instance:
```
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(nestedXml));
StringBuilder sb = new StringBuilder();
ds.WriteXml(new StringWriter(sb));
Response.Write(sb.ToString());
```
Of course you can read tables individually by using `ds.Tables[0]` and `ds.Tables[1]` | Load nested XML into dataset | [
"",
"c#",
"xml",
"dataset",
""
] |
Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file. | In theory yes, you can start spewing crud into \_\_builtin\_\_:
```
>>> import __builtin__
>>> __builtin__.rubbish= 3
>>> rubbish
3
```
But, don't do this; it's horrible evilness that will give your applications programming-cancer.
> classes and functions and i don't want to have to keep declaring
Put them in modules and ‘import’ them when you need to use them.
> I have certain variables i want to use throughout my whole project
If you must have unqualified values, just put them in a file called something like “mypackage/constants.py” then:
```
from mypackage.constants import *
```
If they really are ‘variables’ in that you change them during app execution, you need to start encapsulating them in objects. | Create empty superglobal.py module.
In your files do:
```
import superglobal
superglobal.whatever = loacalWhatever
other = superglobal.other
``` | Python Superglobal? | [
"",
"python",
"python-3.x",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.