Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Suppose I have the following structure:
```
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
```
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the `__init__.py` file so I don't have to import them in every one of the files?
Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons. | No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass `logging` around as a function argument, which would be a weird way to do things, to say the least).
But the modules are only imported once anyway (and then put into the `a`, `b`, and `c` namespaces), so don't worry about using too much memory or something like that.
You can of course put them into a separate module and import *that* into each `a`, `b`, and `c`, but this separate module would still have to be imported everytime. | You can do this using a common file such as `include.py`, but it goes against recommended practices because it involves a wildcard import. Consider the following files:
```
app/
__init__.py
foo/
a.py
b.py
c.py
include.py <- put the includes here.
__init__.py
```
Now, in `a.py`, etc., do:
```
from include import *
```
As stated above, it's not recommended because wildcard-imports are discouraged. | Importing files in Python from __init__.py | [
"",
"python",
"import",
"module",
""
] |
Time and again, I read that we are not supposed to use static variables in a session bean. Then, how am I supposed to get a logger for this bean and use it all over the bean methods ? | I think you are interpreting the "rule" a little too rigidly.
You shouldn't store any sort of state of a servlet/session/bean in a static variable, as that reference is shared amongst all instances of that type.
However, a logger (usually, or shouldn't) hold any state. It's perfectly fine IMO to use static references to a Logger instance, if you follow the usual practice of naming/categorizing your loggers based on the classname:
```
public class SomeTypeOfBean {
private static final Logger log = Logger.getLogger(SomeTypeOfBean.class);
//...
}
``` | Read only non-blocking static references (which is what a logger is) are generally fine, if there are no issues with having a few copies of them around (at the application server's discretion).
That being said, there is nothing that says that a logger must be in a static variable. It can be in an instance variable (and a transient one at that if your logger is not serializable).
One thing to realize with the EJB rules - it is most important to understand why they exist and what could trip up an app server (if you are indeed developing app server independent). Once you understand that, you know how to work with them (and they make sense given what an app server is expected to do with your class). If it is just a bunch of arbitrary rules written on a document, then you won't be able to figure out how to work with them, instead of getting trapped by them. | If we are not allowed to use static variables in session beans, how to define a logger? | [
"",
"java",
"session-variables",
""
] |
I am trying to get JAXB to work with a groovy class of mine, however, it appears it doesn't work but the java version does. Here is the code...
Here are the Scenarios:
If 2 and 3 are uncommented it works fine.
If 1 and 4 are uncommented I get:
```
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
2 counts of IllegalAnnotationExceptions
groovy.lang.MetaClass is an interface, and JAXB can't handle interfaces.
```
If 1 and 5 are uncommented I get:
```
javax.xml.bind.JAXBException: class org.oclc.presentations.simplejaxb.PlayerGroovy
nor any of its super class is known to this context.
```
Any ideas?
Java:
```
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Player {
}
```
Groovy:
```
import javax.xml.bind.annotation.XmlRootElement
@XmlRootElement
public class PlayerGroovy {
}
```
Test:
```
import org.junit.Test
import javax.xml.bind.JAXBContext
import javax.xml.bind.Marshaller
import org.junit.Assert
class PlayerTest {
@Test
public void testJaXB(){
//1 PlayerGroovy player = new PlayerGroovy()
//2 Player player = new Player()
StringWriter writer = new StringWriter();
//3 JAXBContext context = JAXBContext.newInstance(Player.class);
//4 JAXBContext context = JAXBContext.newInstance(PlayerGroovy.class);
//5 JAXBContext context = JAXBContext.newInstance(PlayerGroovy.getClass());
Marshaller m = context.createMarshaller();
m.marshal(player, writer);
println(writer)
Assert.assertTrue(true)
}
}
``` | Uncommenting 1 and 4 is the correct way to set JAXB up with Groovy. The reason it is not working is that each Groovy Class has a metaClass property on it. JAXB is trying to expose this as a JAXB property which obviously fails. Since you don't declare the metaClass property yourself, it is not possible to annotate it to have JAXB ignore it. Instead you and set the XmlAccessType to NONE. This disable's JAXB's auto-discovery of properties to expose as XML elements. After you do that, you need to explicitly declare any fields you want exposed.
Example:
```
@XmlAccessorType( XmlAccessType.NONE )
@XmlRootElement
public class PlayerGroovy {
@XmlAttribute
String value
}
``` | I was having the same problem while exposing a Grails GORM object. After researching the solution posted above, using `@XmlAccessorType( XmlAccessType.NONE )`, I quickly grew tired of marking everything as `@XmlAttribute`.
I'm having plenty of success using:
```
@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
public class PlayerGroovy {
String value
}
```
See: [XmlAccessType](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlAccessType.html)
Thanks to the original answer for getting me started in the right direction. | How do I get Groovy and JAXB to play nice together | [
"",
"java",
"groovy",
"jaxb",
""
] |
Using [this](http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/#Demo) article from sun. I am trying to create a transparent window.
I have one image inside a label on the frame.
I want the image to be visible but the frame invisible.
When i use
```
try {
Class awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
mSetWindowOpacity.invoke(null, window, Float.valueOf(0.75f));
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
```
It makes everthing transparent is possible to keep components not transparent. | You could try just setting the alpha channel for the background color of your frame, that shouldn't descend to components.
```
window.setBackground(new Color(1.0, 1.0, 1.0, 0.25));
```
should give you a white, transparent window. | You can still use the AWTUtilities class, but instead of setting the opacity with setWindowOpacity() setWindowOpaque(). This will turn off the background of the window, but anything you draw inside the window will still be drawn as before. As of the recent Java 6 updates this is now the correct way to do things. AWTUtilities will work on both Mac & MS Windows. These methods will be moved into java.awt.Window itself in Java 7. | AWTUtilities Transparent JFrame | [
"",
"java",
"swing",
"awtutilities",
""
] |
I'm trying to call a method from a DLL written in C, from my C# application. Here is how I've implemented the call:
--> C method signature: (from a third-part company)
```
Int16 SSEXPORT SS_Initialize(Uint16 ServerIds[], Uint16 ServerQty, const char PTR *Binding, const char PTR *LogPath, Uint16 LogDays, Int16 LogLevel,
Uint16 MaxThreads, Uint16 ThreadTTL, Int16 (CALLBACK *ProcessMessage)(Uint16, const char PTR *, Uint32, char PTR **, Uint32 PTR *, Int16 PTR *));
```
--> C types definition:
```
#ifndef _CSISERVERTYPES_
#define _CSISERVERTYPES_
#if defined(OS_NT)
#define CALLBACK __stdcall
#define SSEXPORT __stdcall
#define PTR
typedef char Int8;
typedef unsigned char Uint8;
typedef short Int16;
typedef unsigned short Uint16;
typedef long Int32;
typedef unsigned long Uint32;
typedef unsigned char Byte;
typedef unsigned short Word;
typedef unsigned long Dword;
typedef short Bool;
#endif
typedef Int16 (CALLBACK *PM_Function)
(Uint16,const char PTR *,Uint32,char PTR **,Uint32 PTR *,Int16 PTR *);
#define SS_OK 0
#define SS_NOT_INIT -1
#define SS_PROC_ERR -2
#define SS_ERR_TCP_SRV -3
#define SS_ERR_OUT_MEM -4
#ifndef NULL
#define NULL 0
#endif
#endif
```
--> C# DLL Method declaration:
```
[DllImport("CSITCPServer.dll", SetLastError = true)]
static extern Int16 SS_Initialize(
UInt16[] ServerIds,
UInt16 ServerQty,
ref string Binding,
ref string LogPath,
UInt16 LogDays,
Int16 LogLevel,
UInt16 MaxThreads,
UInt16 ThreadTTL,
ProcessMessageCallback callback);
```
Method call:
```
public static void Call_SS_Initialize()
{
Int16 ret;
UInt16[] serverIds = new UInt16[] { 2020, 2021 };
string binding = "";
string logPath = "";
try
{
ret = SS_Initialize(
serverIds,
Convert.ToUInt16(serverIds.ToList().Count),
ref binding,
ref logPath,
10,
0,
256,
300,
ProcessMessage);
Console.WriteLine("Call_SS_Initialize() -> Result of SS_Initialize: {0}", ret.ToString());
}
catch (Exception ex)
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
//throw;
}
}
```
And then I get the **Win32Exception: 1008 - An attempt was made to reference a token that does not exist**
I know that the problem must be in the CHAR to STRING conversion between unmanaged (C) and managed (C#) codes. If I modify the **Binding** or **LogPath** parameters to type **SByte**, it doesn't give any errors. But since the method expects for a text (string), I don't know how can I pass the text to the method since it expects a SByte variable...
I'm aware that I might have to use something like **MarshalAs**, but I've tried a few options and didn't had any success.
Can anybody tell me what am I doing wrong??
Thank you very much!!
---
Here is the callback definition:
```
public delegate Int16 ProcessMessageCallback(
UInt16 ServerId,
[MarshalAs(UnmanagedType.LPStr)] ref string RequestMsg,
UInt32 RequestSize,
[MarshalAs(UnmanagedType.LPStr)] ref string ResponseMsg,
ref UInt32 ResponseSize,
ref Int16 AppErrCode);
```
The thing is that the C DLL method is expecting a "REF" parameter. The call to **SS\_Initialize** attachs the execution to the **ProcessMessage** callback function. In this function I need to be able to get the modified parameters (ref) from SS\_Initialize ...
Could you please suggest how do you think the code should be structured?
Thank you!! | You do not need to use ref for Binding and LogPath; they are const char\* and will not change.
That ResponseMessage in the callback will return an array of strings, (char \*\*) not just a single string. The Response size probably will indicate the depth of the array. Try [MarshalAs(UnamangedType.LPArray, ArraySubType=UnmanagedType.LPStr)] string[] instead. | For marshalling strings you don't pass `ref string`, just `string`. Also, you should decorate each string with `[MarshalAs( UnmanagedType.LPStr)]` to indicate, that you are passing string that contains ascii chars and it's null terminated.
Edit: Could you also give your definition of this callback procedure, as you could made similar mistakes. | Call C DLL function from C# - convert char parameter to string | [
"",
"c#",
"c",
"string",
"dll",
"char",
""
] |
I am writing this code. Here dt is input into the function, as well as someint. The column Exp is a T-SQL date column, which comes as a DateTime through Linq.
```
return (from a in dataContext.TableOfA
where a.name == "Test" &&
a.Exp.Value.AddDays(Convert.ToDouble(Someint)) >= new DateTimeOffset(dt)
select a).First();
```
In C#, you can add a double as a day to a date time. Meaning you can add 1.5 days. In T-SQL you can only add 1 day, then 12 hours. You must add an int for each part. So when Linq translates AddDays to T-SQL, it converts my number of days to milliseconds, and adds those. This allows it to give all the precision the double gives C#.
Here's the rub. When this gets to SQL, I get the error:
> The datepart millisecond is not
> supported by date function dateadd for
> data type date
Basically you can't add milliseconds to a date. Well no kidding. But how do I get something that translates here? I want to add int days to a date. Is the only want to do this to add the negative of them to the other guy I am comparing against? What if I wanted to compare to columns while adding to one?
**Update 1**
> Keith wrote, A command like
> datepart(millisecond, 10000, myDate)
> has been supported in T-SQL since at
> least SQL Server 2000. This error
> suggests that whatever database you
> are using does not support the
> millisecond date part, which seems
> strange to me.
Please note I am using SQL Server 2008. It is not supported on the DATE data type. It is supported on datetime. | I just changed the column back to a DateTime. | If you are using the Entity Framework, use the System.Data.Objects.EntityFunctions as below:
```
c.CMT_TS > System.Data.Objects.EntityFunctions.AddDays(e.Call.CALL_TS, 1)
``` | How to add day to date in Linq to SQL | [
"",
"c#",
"datetime",
"linq-to-sql",
""
] |
It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it `Class` objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different `Class` argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, [e.g.](http://www.developer.com/java/other/article.php/3300881):
```
new className(optional argument list){classBody}
new interfaceName(){classBody}
```
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a `Class` object for an anonymous class? | Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
```
foo((new Object() { ... }).getClass());
```
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
### EDIT
Your question also says that you want to call `foo` "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class *definition*, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that `foo` will create using the `Class` object passed to it *will not* have them captured. | ## short answer
you cannot (using only JDK classes)
## long answer
give it a try:
```
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
@Override
public int value() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
```
let's creating two new class "parametric" classes:
```
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
```
however you cannot instantiate this classes:
```
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
```
it will fail at runtime since **there is only one instance for every anonymous class**.
However you can build *dynamic classes* at runtime using **bytecode manipulation libraries such [ASM](http://asm.ow2.org/)**. Another approach is using [dynamic proxies](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Proxy.html), but this approach as the drawback that you can proxy only interface methods (so you need a Java interface). | Uninstantiated Anonymous Classes in Java | [
"",
"java",
"anonymous-class",
""
] |
I need to write some code that performs an HTML highlight on specific keywords in a string.
If I have comma separated list of strings and I would like to do a search and replace on another string for each entry in the list. What is the most efficient way of doing it?
I'm currently doing it with a split, then a foreach and a Regex.Match. For example:
```
string wordsToCheck = "this", "the", "and";
String listArray[] = wordsToCheck.Split(',');
string contentToReplace = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
foreach (string word in listArray)
{
if (Regex.Match(contentToReplace, word + "\\s+", RegexOptions.IgnoreCase).Success)
{
return Regex.Replace(contentToReplace , word + "\\s+", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);
}
}
```
I'm not sure this is the most efficient way because the list of words to check for could get long and the code above could be part of a loop to search and replace a bunch of content. | Don't do that if the wordsToCheck can be modified by a user!
Your approach works perfectly without Regexes. Just do a normal String.Replace.
If the input is safe, you can also use one regex for all keywords, e.g.
```
return Regex.Replace(contentToReplace, "(this|the|and)", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);
```
where "this|the|and" is simply `wordsToCheck` where the commas are replaces with pipes "|".
BTW, you might want to take the list keywords directly as a regex instead of a comma separated list. This will give you more flexibility. | You could search for "(this|the|end)" and call Regex.Replace *once* with a match evaluator, a method, that takes the match and returns a replacement string.
You can build the match pattern by taking your string array and calling Regex.Escape on every element, then join it with String.Join using | as a separator. | Best way to do a string search and replace | [
"",
"c#",
"string",
""
] |
If I define a variable like `set @a = "1";`. How can I see that @a is a string? | You cannot determine the type of a variable in MySQL.
As an alternative, you can easily `CAST()` your variable in the type you desire:
```
@a = CAST(123 AS CHAR);
```
More information and examples about casting in the MySQL Manual:
> [11.9. Cast Functions and Operators](http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html) | You CAN determine the type of a variable in MySQL. Create a table by selecting your variable and then check the column type:
```
set @a:="1"; -- your variable
drop temporary table if exists foo;
create temporary table foo select @a; -- dirty magic
desc foo;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| @a | longtext | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
``` | Get the type of a variable in MySQL | [
"",
"sql",
"mysql",
""
] |
Guys, could you please recommend a tool for spotting a memory corruption on a production multithreaded server built with c++ and working under linux x86\_64? I'm currently facing the following problem : every several hours my server crashes with a segfault and the core dump shows that error happens in malloc/calloc which is definitely a sign of memory being corrupted somewhere.
Actually I have already tried some tools without much luck. Here is my experience so far:
* Valgrind is a great(I'd even say best) tool but it slows down the server too much making it unusable in production. I tried it on a stage server and it really helped me find some memory related issues but even after fixing them I still get crashes on the production server. I ran my stage server under Valgrind for several hours but still couldn't spot any serious errors.
* ElectricFence is said to be a real memory hog but I couldn't even get it working properly. It segfaults almost immediately on the stage server in random weird places where Valgrind didn't show any issues at all. Maybe ElectricFence doesn't support threading well?.. I have no idea.
* DUMA - same story as ElectricFence but even worse. While EF produced core dumps with readable backtraces DUMA shows me only "?????"(and yes server is built with -g flag for sure)
* dmalloc - I configured the server to use it instead of standard malloc routines however it hangs after several minutes. Attaching a gdb to the process reveals it's hung somewhere in dmalloc :(
I'm gradually getting crazy and simply don't know what to do next. I have the following tools to be tried: mtrace, mpatrol but maybe someone has a better idea?
I'd greatly appreciate any help on this issue.
**Update:** I managed to find the source of the bug. However I found it on the stage server not production one using helgrind/DRD/tsan - there was a datarace between several threads which resulted in memory corruption. The key was to use proper valgrind suppressions since these tools showed too many false positives. Still I don't really know how this can be discovered on the production server without any significant slowdowns... | Folks, I managed to find the source of the bug. However I found it on the stage server using helgrind/DRD/tsan - there was a datarace between several threads which resulted in memory corruption. The key was to use *proper* valgrind suppressions since these tools showed too many false positives. Still I don't really know how this can be discovered on the production server without any significant slowdowns... | Yes, C/C++ memory corruption problems are tough.
I also used several times valgrind, sometimes it revealed the problem and sometimes not.
While examining valgrind output don't tend to ignore its result too fast. Sometimes after a considerable time spent, you'll see that valgrind gave you the clue on the first place, but you ignored it.
Another advise is to compare the code changes from previously known stable release. It's not a problem if you use some sort of source versioning system (e.g. svn). Examine all memory related functions (e.g. memcpy, memset, sprintf, new, delete/delete[]). | Tracing memory corruption on a production linux server | [
"",
"c++",
"linux",
"memory",
"production",
"corruption",
""
] |
this code does not work? When i try to click on the radiobutton, nothing happens. It is supposed that it is going to be disabled but nothing is disabled and enabled. Here is the code.
```
<script type="text/javascript">
function ann()
{
document.getElementById('butta').disabled = true;
document.getElementById('strup').disabled = true;
document.getElementById('name').disabled = false;
}
function own()
{
document.getElementById('butta').disabled = false;
document.getElementById('strup').disabled = false;
document.getElementById('name').disabled = true;
}
</script>
<input type="radio" name="checktype" id="ann" onclick="ann()" value="1"> Anime<br>
<input type="radio" name="checktype" id="own" onclick="own()" value="2"> My picture<br>
``` | **[It Works fine](http://jsbin.com/ijexa)**
add **/edit** to the URL to inspect the code and play around.
I closed the input and break elements in the example. Although the code works without these, I would consider it good practice to close them.
EDIT:
**[Updated example](http://jsbin.com/uxupa)**
This is to demonstrate that the code does work when you have a `<select id="name">`, `<input type="file" id="strup" />` and `<input type="button" id="butta" />` in the page. Works fine in Firefox 3 and IE 7.
There must be a problem elsewhere in the code | Your ids for the radio buttons are wrong. | OnClick does not work | [
"",
"javascript",
""
] |
I use the "bool" type for variables as I was used to in C++, and I try to put the values of functions or properties I expect to be boolean into my variable. However I often encounter cases where the result type is "bool?" and not "bool" and the implicit casting fails.
What is the difference between the two and when is each used? Also, should I use "bool?" as the type for my variable? Is this the best practice? | The `?` symbol after a type is only a shortcut to the [Nullable type](http://msdn.microsoft.com/en-us/library/1t3y8s4s%28VS.80%29.aspx), `bool?` is equivalent to `Nullable<bool>`.
`bool` is a [value type](http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx), this means that it cannot be `null`, so the Nullable type basically allows you to wrap value types, and being able to assign `null` to them.
`bool?` can contain three different values: `true`, `false` and `null`.
Also, there are no short-circuiting operators (&& ||) defined for `bool?`
Only the logical AND, inclusive OR, operators are defined and they behave like this:
```
x y x & y x | y
true true true true
true false false true
true null null true
false true false true
false false false false
false null false null
null true null true
null false false null
null null null null
```
The Nullable type is basically a generic struct, that has the following public properties:
```
public struct Nullable<T> where T: struct
{
public bool HasValue { get; }
public T Value { get; }
}
```
The `HasValue` property indicates whether the current object has a value, and the `Value` property will get the current value of the object, or if HasValue is false, it will throw an InvalidOperationException.
Now you must be wondering something, Nullable is a struct, a value type that cannot be null, so why the following statement is valid?
```
int? a = null;
```
That example will compile into this:
```
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
```
A call to [initobj](http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj%28VS.85%29.aspx), which initializes each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.
That's it, what's happening here is the default [struct initialization](http://msdn.microsoft.com/en-us/library/aa288208%28VS.71%29.aspx).
```
int? a = null;
```
Is equivalent to:
```
Nullable<int> a = new Nullable<int>();
``` | `bool?` is nullable while `bool` is not.
```
bool? first;
bool second;
```
In the above code, `first` will be `null` while `second` will be `false`.
One typical use is if you want to know whether there has been an assignment made to the variable. Since `bool` is a *value type* (just as `int`, `long`, `double`, `DateTime` and some other types), it will always be initialized to a default value (`false` in the case of a `bool`, `0` in the case of an `int`). This means that you can not easily know whether it's `false` because some code assigned `false` to it, or if it is `false` because it has not yet been assigned. In that case `bool?` comes in handy. | What's the difference between "bool" and "bool?"? | [
"",
"c#",
"boolean",
"nullable",
""
] |
I'm a bit stumped by the Facebook implementation of Javascript. I want to set up a listener on a checkbox so that when checked, it changes the class of an element I can get by ID.
I've been using the test console and have tried various permutations. Javascript is NOT my first language, nor my second, third... COuld anyone help me by translating my pseudocode?
```
<input class="one" type="checkbox" onclick="setcolor(this.checkedornot)">
function setcolor(checkedornot){
if checkedornot == true {set p.one to p.one.GREEN}
if checkedornot == false {set p.one to p.one.RED}
}
```
Obviously this is not javascript, but that is how I can best explain the functionality I need. In my short tests, FBJS doesn't even seem to register onClick events. Thanks! | FBJS has its own getters and setters. Getting "checked" and setting/removing classes are different. And, you would have to remove the `red` class if you are adding the `green` class and visa versa. Or, if you just want to overwrite all the classes of the element, you can use the `setClassName(class)` method instead, I'm going to use the `add`/`remove` class methods in my answer since it is less destructive.
[FBJS Docs: Manipulating Objects](http://wiki.developers.facebook.com/index.php/FBJS#Manipulating_Objects)
For the `onclick` event, I think you're supposed to use the `addEventListener` if `onclick` doesn't work. [Events in FBJS](http://wiki.developers.facebook.com/index.php/FBJS#Events)
Instead of `this.checked`, FBJS uses `getChecked`. So when you add the event listener (for `click`), add a `this.getChecked()` for the `arg`.
```
setColor(this.getChecked());
```
And for the function:
```
function setColor (isChecked) {
var p = document.getElementById(ID-OF-P);
if (isChecked) {
p.removeClassName("red");
p.addClassName("green");
} else {
p.removeClassName("green");
p.addClassName("red");
}
}
```
I am a JS newb too though. I **think** this is right. | For the onclick event you need to use...
```
this.checked
```
Then your function will look like this:
```
var setColor = function(isChecked) {
var myElement = document.getElementById("one");
if (isChecked) {
myElement.className = "myGreenClass";
} else {
myElement.className = "myRedClass";
}
};
``` | Using FBJS to change CSS | [
"",
"javascript",
"css",
"facebook",
"fbjs",
""
] |
From: `https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript`
```
The same origin policy prevents a document or script loaded from one
origin from getting or setting properties of a document from another origin.
This policy dates all the way back to Netscape Navigator 2.0.
```
So why is not the same origin policy enforced?, when a have a script tag like this:
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
```
I'm sure I'm missing 'something', I've read
<http://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy>
a bunch of times but can not figure out... | HTML can load from wherever it likes, it's another **script** running on the page that can't fetch documents from another origin. | `<script>` tags are an exception to this rule. A page is allowed to "invite" a script from another server, and that's considered OK.
(The whole economy of the internet - on-page advertising - is based on this being allowed! Although it does represent a security risk, it's not going to change any time soon.) | Is google AJAX Libraries API bypassing same origin policy? | [
"",
"javascript",
"ajax",
"same-origin-policy",
""
] |
I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:
* Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.
* Ease-of-use. This is python. The storage should feel like python.
* Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine.
* Ease of installation. My sysadmin should be able to get this running on our cluster.
I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.
Some potential options that I've started looking at (see [this](https://stackoverflow.com/questions/195626/how-to-avoid-computation-every-time-a-python-module-is-reloaded) post):
* [pyTables](http://www.pytables.org/)
* [ZopeDB](http://www.zope.org/)
* [shove](http://pypi.python.org/pypi/shove)
* [shelve](http://docs.python.org/library/shelve.html)
* [redis](http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/)
* [durus](http://www.mems-exchange.org/software/durus/)
Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best? | A RDBMS.
Nothing is more realiable than using tables on a well known RDBMS. [Postgresql](http://www.postgresql.org/) comes to mind.
That automatically gives you some choices for the future like clustering. Also you automatically have a lot of tools to administer your database, and you can use it from other software written in virtually any language.
It is really fast.
In the "feel like python" point, I might add that you can use an ORM. A strong name is [sqlalchemy](http://www.sqlalchemy.org/). Maybe with the [elixir](http://elixir.ematia.de) "*extension*".
Using sqlalchemy you can leave your user/sysadmin choose which database backend he wants to use. Maybe they already have [MySql](http://www.mysql.com/) installed - no problem.
RDBMSs are still the best choice for data storage. | Might want to give [mongodb](http://www.mongodb.org/) a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used [in production](http://www.mongodb.org/display/DOCS/Production+Deployments) at some big names. | Comparing persistent storage solutions in python | [
"",
"python",
"orm",
"persistence",
""
] |
I'm using Visual C++ 2008 SP1. I have an app that is compiled in debug mode, but links against a library in release mode.
I'm getting a crash at the start-up of the application. To make the problem smaller, I created a simple solution with 2 projects:
* lib\_release (generates a .lib, in release mode)
* exec\_using\_lib\_release (genereates a .exe, in debug mode)
The 'lib\_release' project is simple enough to have a simple class:
```
//Foo.h
#include <vector>
class Foo {
std::vector<int> v;
public:
void doSomething();
};
//Foo.cpp
#include "Foo.h"
void Foo::doSomething() {}
```
The 'exec\_using\_lib\_release' project is simple like this:
```
//main.cpp
#include "Foo.h"
int main() {
Foo foo;
foo.doSomething();
return 0;
}
```
And it crashes, it's the same problem reported by [How do you build a debug .exe (MSVCRTD.lib) against a release built lib (MSVCRT.lib)?](https://stackoverflow.com/questions/746298/how-do-you-build-a-debug-exe-msvcrtd-lib-against-a-release-built-lib-msvcrt-l), but his answer didn't work for me.
I get the same linker warnings, I tried the same steps, but none worked. Is there something I'm missing?
**EDIT:**
On the lib\_release (that creates a library in release mode), I'm using *Multi Threaded (/MT)*, and at the exec\_using\_lib\_release, I'm using *Multi Threaded Debug (/MTd)*. I think this is the expected way of doing it, since I want the .lib to be created without debug info. I read the document at [MSDN Runtime library](http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx "MSDN - Runtime library") and those are the settings of linking against the CRT in a static way.
I don't have 'Common Language Runtime Support' either. | You don't *have* to use the same runtimes for release and debug modules (but it helps), as long as you follow very specific rules: never mix and ,match accessing the memory allocated using each runtime.
To put this more simply, if you have a routine in a dll that allocates some memory and returns it to the caller, the caller must never free it - you must create a function in the original dll that frees the memory. That way you're safe from runtime mismatches.
If you consider that the Windows dlls are built release only (unless you have the debug version of Windows), yet you use them from your debug applications, you'll see how this matters.
Your problem now is that you're using a static library, there is no dll boundary anymore, and the calls in the lib are compiled using the static version of the C runtime. If your exe uses the dynamic dll version of the runtime, you'll find that the linker is using that one instead of the one your static lib used... and you'll get crashes.
So, you could rebuild your lib as a dll; or you could make sure they both use the same CRT library; or you could make sure they both use the same type of CRT - ie the dll version or the static version, whilst keeping debug/release differences.
At least, I think this is your problem - what are the 'code generation, runtime library' settings? | For the mix of release and debug problems that earlier people have mentioned, those issues would not show up until the wrong runtime library tried to de-allocate. I think what you are running into is that VS 2008 has iterator debugging enabled by default, so your lib and your exe are referring to different implementations of std::vector. You will want to add \_HAS\_ITERATOR\_DEBUGGING=0 to your preprocessor settings. Then you will start hitting the problem of different heaps for the different runtimes. In the past we have had different rules and policies to avoid this, but now we just rely on a consistent build environment - don't mix and match. | Linking against library in release and .exe in debug crashes in Visual studio | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"linker",
""
] |
When i store a delegate (that points to a page method) in session state, retrive it after a postback and execute it the target of the delegate is the old page object and not the current one, is there anyway to change the target of the delegate so that it executes the method on the current page object ?
I have thought about using a static page method but then i don't have access to the controls on the page which defeats the object of what i am trying to do, which is update a text box. | Make your delegate take the new page as its first parameter, and when you call it pass `this`. | I'm a little nervous about this. Both Jon Skeet's and Mehrdad's suggestions will work (of course), but page instances are supposed to be disposed after a request completes. This delegate could be preventing that from happening, leading to the .Net equivalent of a memory leak.
Perhaps you could use reflection and put a `System.Reflection.MethodBase` or `System.Reflection.MethodInfo` object in the session to invoke later instead. | c# Delegates across postback | [
"",
"c#",
"asp.net",
"delegates",
"postback",
"session-state",
""
] |
What I want to achieve is to get a website screenshot from any website in python.
Env: Linux | On the Mac, there's [webkit2png](http://www.paulhammond.org/webkit2png/) and on Linux+KDE, you can use [khtml2png](http://khtml2png.sourceforge.net/). I've tried the former and it works quite well, and heard of the latter being put to use.
I recently came across [QtWebKit](http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/) which claims to be cross platform (Qt rolled WebKit into their library, I guess). But I've never tried it, so I can't tell you much more.
The QtWebKit links shows how to access from Python. You should be able to at least use subprocess to do the same with the others. | Here is a simple solution using webkit:
<http://webscraping.com/blog/Webpage-screenshots-with-webkit/>
```
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class Screenshot(QWebView):
def __init__(self):
self.app = QApplication(sys.argv)
QWebView.__init__(self)
self._loaded = False
self.loadFinished.connect(self._loadFinished)
def capture(self, url, output_file):
self.load(QUrl(url))
self.wait_load()
# set to webpage size
frame = self.page().mainFrame()
self.page().setViewportSize(frame.contentsSize())
# render image
image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
frame.render(painter)
painter.end()
print 'saving', output_file
image.save(output_file)
def wait_load(self, delay=0):
# process app events until page loaded
while not self._loaded:
self.app.processEvents()
time.sleep(delay)
self._loaded = False
def _loadFinished(self, result):
self._loaded = True
s = Screenshot()
s.capture('http://webscraping.com', 'website.png')
s.capture('http://webscraping.com/blog', 'blog.png')
``` | How can I take a screenshot/image of a website using Python? | [
"",
"python",
"screenshot",
"html",
"backend",
""
] |
i've stuck at a little design problem.
following situation
*Library Interface*
Contains interface for every model class (getters and setters only)
*Libray Businnes Logic*
Contains implementations of interface library and DAL.
Uses interface & transporter library
*Library Transporter*:
Contains classes for messaging 3rd party web services. Also there i want to add the references or web references of 3rd party libraries if needed.
Uses interface library.
So far soo good. There is no circular dependency now. As soon as a webservice needs to be called the business logic library uses the "transporter" library to call the extern method. This works pretty well.
But now i need to create a webservice where 3rd parties should be able to create business objects at our side. I want to create a "Transform library" where bussines objects are transformed to message objects for the the external webservies and vice versa. And there I think is the problem with my current architecture. If i want to create this library, I get a circular dependency.
The reasons are
* Transporter references Transform
* Transform Library references BL
* BL references Transporter
I hope that I could explain my situation well.
Thanks for every idea to solve this. | [Dependency injection](http://martinfowler.com/articles/injection.html) to the rescue:
1. Create a `ITransporter` interface
which models the service provided by
"Transporter". Put it in the interfaces library. Make `Transporter` implement `ITransporter`.
2. In your business library, program
against the `ITransporter` interface
instead of directly using
`Transporter`. Now the business
library doesn't need a dependency on
the transporter library anymore.
3. In your application/web service
where you glue everything together,
create an instance of `Transporter`
and inject it where you need an
`ITransporter` object in your business
code. | You may way to rethink your design. Does it make sense to group ALL of your third party web services into one DLL, then move what might considered essential functionality (the transformations) into another library? I think it would make more sense to create individual assemblies for each web service (or group of services, if it makes sense to group them) that has the appropriate functionality in them.
You also have some faulty logic in assuming that "transporter functionality is not need[ed] in every project". If this is the case, why does the Business Logic assembly depend on it? | Software design problem: circular dependency | [
"",
"c#",
""
] |
Is it good practice to initialize a global variable in PHP? The snippet of code seems to work fine, but is it better to initialize (in a larger project, say for performance sake) the variable outside of a function, like in the second scratch of code?
```
if(isset($_POST["Return"]))Validate();
function Validate(){
(!empty($_POST["From"])&&!empty($_POST["Body"]))?Send_Email():Fuss();
};
function Send_Email(){
global $Alert;
$Alert="Lorem Ipsum";
mail("","",$_POST["Body"],"From:".$_POST["From"]);
};
function Fuss(){
global $Alert;
$Alert="Dolor Sit"
};
function Alert(){
global $Alert;
if(!is_null($Alert))echo $Alert;
};
```
Notice the variable $Alert above is not initialized.
```
$Alert;
if(isset($_POST["Return"]))Validate();
function Validate(){
(!empty($_POST["From"])&&!empty($_POST["Body"]))?Send_Email():Fuss();
};
function Send_Email(){
global $Alert;
$Alert="Lorem Ipsum";
mail("","",$_POST["Body"],"From:".$_POST["From"]);
};
function Fuss(){
global $Alert;
$Alert="Dolor Sit"
};
function Alert(){
global $Alert;
if(!is_null($Alert))echo $Alert;
};
```
Now notice it is.
I appreciate any answers! Thanks in advance, Jay | I don't think this is doable so I'm scrapping it. Global variables are being dropped in PHP6 and a Constant, by definition can't have it's value changed. Thanks to everyone, I appreciate each answer and all who contributed. | In the second example you are still not declaring the variable, the line
```
$alert;
```
does not assign `$alert` a value so it remains undeclared.
If you declare the variable first, you can access it more easily without generating notices:
```
$alert = '';
if ($alert) {
//do something with alert
}
``` | Initialize Global Variables in PHP | [
"",
"php",
"variables",
"global",
"initialization",
""
] |
How can I get the table creation date of a MS SQL table using a SQL query?
I could not see any table physically but I can query that particular table. | For 2005 up, you can use
```
SELECT
[name]
,create_date
,modify_date
FROM
sys.tables
```
I think for 2000, you need to have enabled auditing. | For SQL Server 2005 upwards:
```
SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables
```
For SQL Server 2000 upwards:
```
SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so
WHERE it.[TABLE_NAME] = so.[name]
``` | SQL Server table creation date query | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
I am attempting to pass objects into an Attributes constructor as follows:
```
[PropertyValidation(new NullOrEmptyValidatorScheme())]
public string Name { get; private set; }
```
With this attribute constructor:
```
public PropertyValidationAttribute(IValidatorScheme validator) {
this._ValidatorScheme = validator;
}
```
The code won't compile. How can I pass an object into an attribute as above?
EDIT: Yes NullOrEmptyValidatorScheme implements IValidatorScheme.
The error: error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type. | The values into attributes are limited to simple types; for example, basic constants (including strings) and `typeof`... you can't use `new` or other more complex code. In short; you can't do this. You can give it the **type** though:
```
[PropertyValidation(typeof(NullOrEmptyValidatorScheme)]
```
i.e. the `PropertyValidation` ctor takes a `Type`, and use `Activator.CreateInstance` inside the code to create the object. Note that you should ideally just store the string internally (`AssemblyQualifiedName`).
From ECMA 334v4:
> §24.1.3 Attribute parameter types
>
> The types of positional and named
> parameters for an attribute class are
> limited to the *attribute parameter
> types*, which are:
>
> * One of the following types: `bool`, `byte`, `char`,
> `double`, `float`, `int`, `long`, `short`, `string`.
> * The type `object`.
> * The type `System.Type`.
> * An enum type, provided it has public accessibility and the
> types in which it is nested (if any)
> also have public accessibility.
> * Single-dimensional arrays of the above
> types.
and
> §24.2 Attribute specification
>
> ...
>
> An expression `E` is an
> attribute-argument-expression if all
> of the following statements are true:
>
> * The type of `E` is an attribute
> parameter type (§24.1.3).
> * At compile-time, the value of E can be
> resolved to one of the following:
> + A constant value.
> + A typeof-expression (§14.5.11) specifying a non-generic
> type, a closed constructed type
> (§25.5.2), or an unbound generic type
> (§25.5).
> + A one-dimensional array of
> attribute-argument-expressions. | As previous posters noted, the types use in attribute arguments are quite severely restricted (understandably, because their values need to be serialized directly into the assembly metadata blob).
That said, you can probably create a solution that utilizes *typeofs*, as those **can** be used.
For instance :
```
[PropertyValidation(typeof(NullOrEmptyValidatorScheme))]
public string Name { get; private set; }
```
This syntax is perfectly legal. The code that reads your attributes you have to get the validator type, create a new instance of the validator (it can even maintain a cache of validators keyed on valicator types, if appropriate - this is a fairly common technique), and then invoke it. | How to pass objects into an attribute constructor | [
"",
"c#",
"attributes",
""
] |
I have a checkbox that I want to perform some Ajax action on the click event, however the checkbox is also inside a container with its own click behaviour that I don't want to run when the checkbox is clicked. This sample illustrates what I want to do:
```
$(document).ready(function() {
$('#container').addClass('hidden');
$('#header').click(function() {
if ($('#container').hasClass('hidden')) {
$('#container').removeClass('hidden');
} else {
$('#container').addClass('hidden');
}
});
$('#header input[type=checkbox]').click(function(event) {
// Do something
});
});
```
```
#container.hidden #body {
display: none;
}
```
```
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="container">
<div id="header">
<h1>Title</h1>
<input type="checkbox" name="test" />
</div>
<div id="body">
<p>Some content</p>
</div>
</div>
```
However, I can't figure out how to stop the event bubbling without causing the default click behaviour (checkbox becoming checked/unchecked) to not run.
Both of the following stop the event bubbling but also don't change the checkbox state:
```
event.preventDefault();
return false;
``` | replace
```
event.preventDefault();
return false;
```
with
```
event.stopPropagation();
```
***event.stopPropagation()***
> Stops the bubbling of an event to
> parent elements, preventing any parent
> handlers from being notified of the
> event.
***event.preventDefault()***
> Prevents the browser from executing
> the default action. Use the method
> isDefaultPrevented to know whether
> this method was ever called (on that
> event object). | Use the stopPropagation method:
```
event.stopPropagation();
``` | How to stop event bubbling on checkbox click | [
"",
"javascript",
"jquery",
"checkbox",
"events",
""
] |
I need to find the most recently modified file in a directory.
I know I can loop through every file in a folder and compare `File.GetLastWriteTime`, but is there a better way to do this without looping?. | how about something like this...
```
var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
// or...
var myFile = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();
``` | Expanding on the first one above, if you want to search for a certain pattern you may use the following code:
```
using System.IO;
using System.Linq;
...
string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();
``` | How to find the most recent file in a directory using .NET, and without looping? | [
"",
"c#",
".net",
"file",
"loops",
"last-modified",
""
] |
I can't get the last insert id like I usually do and I'm not sure why.
In my view:
```
comment = Comments( ...)
comment.save()
comment.id #returns None
```
In my Model:
```
class Comments(models.Model):
id = models.IntegerField(primary_key=True)
```
Has anyone run into this problem before? Usually after I call the save() method, I have access to the id via comment.id, but this time it's not working. | Are you setting the value of the `id` field in the `comment = Comments( ...)` line? If not, why are you defining the field instead of just letting Django take care of the primary key with an AutoField?
If you specify in IntegerField as a primary key as you're doing in the example Django won't automatically assign it a value. | Simply do
```
c = Comment.object.latest()
```
That should return you the last inserted comment
```
c.pk
12 #last comment saved.
``` | Django - last insert id | [
"",
"python",
"django",
""
] |
Is there a really simple compression technique for strings up to about 255 characters in length (yes, I'm compressing [URLs](http://en.wikipedia.org/wiki/Uniform_Resource_Locator))?
I am not concerned with the strength of compression - I am looking for something that performs very well and is quick to implement. I would like something simpler than [SharpZipLib](http://www.icsharpcode.net/opensource/sharpziplib/): something that can be implemented with a couple of short methods. | I think the key question here is "*Why do you want to compress URLs?*"
**Trying to shorten long urls for the address bar?**
You're better storing the original URL somewhere (database, text file ...) alongside a hashcode of the non-domain part (MD5 is fine). You can then have a simple page (or some HTTPModule if you're feeling flashy) to read the MD5 and lookup the real URL. This is how TinyURL and others work.
For example:
```
http://mydomain.com/folder1/folder2/page1.aspx
```
Could be shorted to:
```
http://mydomain.com/2d4f1c8a
```
*Using a compression library for this will not work*. The string will be compressed into a shorter binary representation, but converting this back to a string which needs to be valid as part of a URL (e.g. Base64) will negate any benefit you gained from the compression.
**Storing lots of URLs in memory or on disk?**
Use the built in compressing library within System.IO.Compression or the ZLib library which is simple and incredibly good. Since you will be storing binary data the compressed output will be fine as-is. You'll need to uncompress it to use it as a URL. | As suggested in [the accepted answer](https://stackoverflow.com/questions/1192732/really-simple-short-string-compression-c/1192853#1192853), Using data compression does not work to shorten URL paths that are already fairly short.
[DotNetZip](http://dotnetzip.codeplex.com) has a DeflateStream class that exposes a static (Shared in VB) [CompressString](http://cheeso.members.winisp.net/DotNetZipHelp/html/b1d910c8-a036-dc5d-321e-c2d63e724130.htm) method. It's a one-line way to compress a string using DEFLATE ([RFC 1951](http://www.ietf.org/rfc/rfc1950.txt)). The DEFLATE implementation is fully compatible with [System.IO.Compression.DeflateStream](http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx), but DotNetZip compresses better. Here's how you might use it:
```
string[] orig = {
"folder1/folder2/page1.aspx",
"folderBB/folderAA/page2.aspx",
};
public void Run()
{
foreach (string s in orig)
{
System.Console.WriteLine("original : {0}", s);
byte[] compressed = DeflateStream.CompressString(s);
System.Console.WriteLine("compressed : {0}", ByteArrayToHexString(compressed));
string uncompressed = DeflateStream.UncompressString(compressed);
System.Console.WriteLine("uncompressed: {0}\n", uncompressed);
}
}
```
Using that code, here are my test results:
```
original : folder1/folder2/page1.aspx
compressed : 4bcbcf49492d32d44f03d346fa0589e9a9867a89c5051500
uncompressed: folder1/folder2/page1.aspx
original : folderBB/folderAA/page2.aspx
compressed : 4bcbcf49492d7272d24f03331c1df50b12d3538df4128b0b2a00
uncompressed: folderBB/folderAA/page2.aspx
```
So you can see the "compressed" byte array, when represented in hex, is longer than the original, about 2x as long. The reason is that a hex byte is actually 2 ASCII chars.
You could compensate somewhat for that by using base-62, instead of base-16 (hex) to represent the number. In that case a-z and A-Z are also digits, giving you 0-9 (10) + a-z (+26) + A-Z (+26) = 62 total digits. That would shorten the output significantly. I haven't tried that. yet.
---
**EDIT**
Ok I tested the Base-62 encoder. It shortens the hex string by about half. I figured it would cut it to 25% (62/16 =~ 4) But I think I am losing something with the discretization. In my tests, the resulting base-62 encoded string is about the same length as the original URL. So, no, using compression and then base-62 encoding is still not a good approach. you really want a hash value. | Really simple short string compression | [
"",
"c#",
"string",
"compression",
"short",
""
] |
I have program that the number of classes loaded there is constantly rising.
How could this actually be ? Or do i misunderstand something in java about classloading?
Here is a snippet from jConsole overnight :
[alt text http://img200.imageshack.us/img200/200/classesp.jpg](http://img200.imageshack.us/img200/200/classesp.jpg)
Could someone please tell me what could be the possible reason for such a constant classloading growth ? Or is this normal ?
Thanks | What sort of features does your application have that are out-of-the-ordinary as regards class loading? For example:
* are you constantly loading classes from remote sources (e.g. `RMI`)?
* are you using your own `ClassLoader`?
* are you using the Java `Proxy` mechanism to create classes on the fly? | You can use other profilers to know exactly what java objects are in memory (and verify that there is no memory leak) :
* List TPTP (Eclipse plugin)
* List Netbeans profiler (very good profiler)
* List JProbe profiler (not free) | Number of classes loaded in java | [
"",
"java",
"classloader",
""
] |
I'm doing a platform independent PyQt application. I intend to use write a setup.py files using setuptools. So far I've managed to detech platform, e.g. load specific options for setup() depending on platform in order to use py2exe on Windows... etc...
However, with my application I'm distributing some themes, HTML and images, I need to load these images in the application at runtime. So far they are stored in the themes/ directory of the application.
I've been reading documentation on setuptools and distutils, and figured out that if I gave setup() the data\_files options with all the files in the themes/ directory to be installed in "share/MyApp/themes/" it would be installed with a /usr/ prefix, or whatever sys.prefix is on the platform.
I assume that I would find the data files using os.path.join(sys.prefix, "share", "MyApp", "themes") nomatter what platform I'm on, right?
However, I want to be able to access the data files during development too, where they reside in the themes/ directory relative to application source. How do I do this?
Is there some smart way to figure out whether the application has been installed? Or a utility that maps to the data files regardless of where they are, at the moment?
I would really hate to add all sorts of ugly hacks to see if there are themes relative to the source, or in sys.prefix/share... etc... How do I find there data files during development? and after install on arbitrary platform ? | I've used a utility method called data\_file:
```
def data_file(fname):
"""Return the path to a data file of ours."""
return os.path.join(os.path.split(__file__)[0], fname)
```
I put this in the **init**.py file in my project, and then call it from anywhere in my package to get a file relative to the package.
Setuptools offers a similar function, but this doesn't need setuptools. | You could try [`pkg_resources`](http://setuptools.readthedocs.io/en/latest/pkg_resources.html#resourcemanager-api):
```
my_data = pkg_resources.resource_string(__name__, fname)
``` | Accessing data files before and after distutils/setuptools | [
"",
"python",
"setuptools",
"distutils",
""
] |
Does anyone know of a way to detect if a remote app has failed/crashed? I'm meaning when it becomes unusable - you'd usually see "Not Responding" in the title bar, in this case - but the key is that the app is still running; therefore just finding the process no longer running is not enough.
WMI does not support use of System.Diagnostics.Process.Responding on a remote machine.. and their seems to be no other WMI properties I can query in Win32\_Process for this kind of information. | In determining 'liveness' of a program it is important to measure that aspect the defines it being alive in a useful manner.
Several simple 'proxy' approaches are superficially appealing due to their simplicity but fundamentally do not measure the important aspect.
Perhaps the most common are the "Is the process alive" and "separate heartbeat broadcast thread" probably because it is so simple to do:
```
bool keepSending = true; // set this to false to shut down the thread
var hb = new Thread(() =>
{
while (true)
SendHeartbeatMessage();
}).Start();
```
Both of these however have a serious flaw, if the real working thread(s) in your app lock up (say going into an infinite loop or a deadlock) then you will continue to merrily send out OK messages. For the process based monitoring you will continue to see the process 'alive' despite it no longer performing it's real task.
You can improve the thread one in many ways (significantly increasing the complexity and chance threading issues) by layering on tests for progress on the main thread but this takes the wrong solution and tries to push it towards the right one.
What is best is to make the task(s) performed by the program part of the liveness check. Perhaps to heartbeat directly from the main thread after every sub task done (with a threshold to ensure that it does not happen too often) or to simply look at the output (if it exists) and ensure that the inputs are resulting in outputs.
It is better still to validate this both internally (within the program) and externally (especially if there are external consumers/users of the program). If you have a web server: attempt to use it, if your app is some event loop based system: trigger events to which it must respond (and verify the output is correct). Whatever is done consider always that you wish to verify that *useful* and correct behaviour is occurring rather than just any activity at all.
The more you verify of not only the existence of the program, but it's *actions* the more useful your check will be. You will check more of the system the further you put yourself from the internal state, if you run your monitor process on the box you may only check local loopback, running off the box validates much more of the network stack including often forgotten aspects like DNS.
Inevitably this makes the checking harder to do, because you are inherently thinking about a specific task rather than a general solution, the dividends from this should yield sufficient benefits for this approach to be seriously considered in many cases. | You can use polling mechanism and periodically ask the status of the remote application. | C# Detect Remote Application Failure | [
"",
"c#",
"wmi",
""
] |
This is mainly a performance questions. I have a master list of all users existing in a String array AllUids. I also have a list of all end dated users existing in a String array EndUids.
I am working in Java and my goal is to remove any users that exist in the end dated array from the master list AllUids. I know PHP has a function called array\_diff.
I was curious if Java has anything that will compare two arrays and remove elements that are similar in both. My objective is performance here which is why I asked about a built in function. I do not want to add any special packages.
I thought about writing a recursive function but it just seems like it will be inefficient. There are thousands of users in both lists. In order to exist in the end dated list, you must exist in the AllUids list, that is until removed.
Example:
```
String[] AllUids = {"Joe", "Tom", "Dan", "Bill", "Hector", "Ron"};
String[] EndUids = {"Dan", "Hector", "Ron"};
```
Functionality I am looking for:
```
String[] ActiveUids = AllUids.RemoveSimilar(EndUids);
```
ActiveUids would look like this:
```
{"Joe", "Tom", "Bill"}
```
Thank you all,
Obviously I can come up with loops and such but I am not confident that it will be efficient. This is something that will run on production machines everyday. | [Commons Collections](http://commons.apache.org/collections/) has a class called [CollectionUtils](http://commons.apache.org/collections/api-2.1.1/org/apache/commons/collections/CollectionUtils.html) and a static method called removeAll which takes an initial list and a list of thing to remove from that list:
```
Collection removeAll(Collection collection,
Collection remove)
```
That should do what you want provided you use lists of users rather than arrays. You can convert your array into a list very easily with Arrays.asList() so...
```
Collection ActiveUids = CollectionUtils.removeAll(Arrays.asList(AllUids),
Arrays.asList(EndUids))
```
**EDIT: I also did a bit of digging with this into Commons Collections and found the following solution with ListUtils in Commons Collections as well:**
```
List diff = ListUtils.subtract(Arrays.asList(AllUids), Arrays.asList(EndUids));
```
Pretty neat... | You can't "remove" elements from arrays. You can set them to null, but arrays are of fixed size.
You *could* use `java.util.Set` and `removeAll` to take one set away from another, but I'd prefer to use the [Google Collections Library](http://code.google.com/p/google-collections/):
```
Set<String> allUids = Sets.newHashSet("Joe", "Tom", "Dan",
"Bill", "Hector", "Ron");
Set<String> endUids = Sets.newHashSet("Dan", "Hector", "Ron");
Set<String> activeUids = Sets.difference(allUids, endUids);
```
That has a more functional feel to it. | Java: Comparing two string arrays and removing elements that exist in both arrays | [
"",
"java",
"arrays",
"string",
""
] |
If I have a list of dictionaries, say:
```
[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
```
and I would like to remove the dictionary with `id` of 2 (or name `'john'`), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped). | ```
thelist[:] = [d for d in thelist if d.get('id') != 2]
```
**Edit**: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a value of 2 for key 'id'), I wish to offer reassurance on this point.
On an old Linux box, measuring this code:
```
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); thelist[:] = [d for d in thelist if d.get('id') != 2]"
10000 loops, best of 3: 82.3 usec per loop
```
of which about 57 microseconds for the random.shuffle (needed to ensure that the element to remove is not ALWAYS at the same spot;-) and 0.65 microseconds for the initial copy (whoever worries about performance impact of shallow copies of Python lists is most obviously out to lunch;-), needed to avoid altering the original list in the loop (so each leg of the loop does have something to delete;-).
When it is known that there is exactly one item to remove, it's possible to locate and remove it even more expeditiously:
```
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); where=(i for i,d in enumerate(thelist) if d.get('id')==2).next(); del thelist[where]"
10000 loops, best of 3: 72.8 usec per loop
```
(use the `next` builtin rather than the `.next` method if you're on Python 2.6 or better, of course) -- but this code breaks down if the number of dicts that satisfy the removal condition is not exactly one. Generalizing this, we have:
```
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"
10000 loops, best of 3: 23.7 usec per loop
```
where the shuffling can be removed because there are already three equispaced dicts to remove, as we know. And the listcomp, unchanged, fares well:
```
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"
10000 loops, best of 3: 23.8 usec per loop
```
totally neck and neck, with even just 3 elements of 99 to be removed. With longer lists and more repetitions, this holds even more of course:
```
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]"
1000 loops, best of 3: 1.11 msec per loop
$ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]"
1000 loops, best of 3: 998 usec per loop
```
All in all, it's obviously not worth deploying the subtlety of making and reversing the list of indices to remove, vs the perfectly simple and obvious list comprehension, to possibly gain 100 nanoseconds in one small case -- and lose 113 microseconds in a larger one;-). Avoiding or criticizing simple, straightforward, and perfectly performance-adequate solutions (like list comprehensions for this general class of "remove some items from a list" problems) is a particularly nasty example of Knuth's and Hoare's well-known thesis that "premature optimization is the root of all evil in programming"!-) | Here's a way to do it with a list comprehension (assuming you name your list 'foo'):
```
[x for x in foo if not (2 == x.get('id'))]
```
Substitute `'john' == x.get('name')` or whatever as appropriate.
`filter` also works:
`foo.filter(lambda x: x.get('id')!=2, foo)`
And if you want a generator you can use itertools:
`itertools.ifilter(lambda x: x.get('id')!=2, foo)`
However, as of Python 3, `filter` will return an iterator anyway, so the list comprehension is really the best choice, as Alex suggested. | Remove dictionary from list | [
"",
"python",
"list",
"dictionary",
""
] |
Suppose I have the following XML document, how to get the element value for a:name (in my sample, the value is Saturday 100)? My confusion is how to deal with the name space. Thanks.
I am using C# and VSTS 2008.
```
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<PollResponse xmlns="http://tempuri.org/">
<PollResult xmlns:a="http://schemas.datacontract.org/2004/07/FOO.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:name>Saturday 100</a:name>
</PollResult>
</PollResponse>
</s:Body>
</s:Envelope>
``` | It's easier if you use the LINQ to XML classes. Otherwise namespaces really are annoying.
```
XNamespace ns = "http://schemas.datacontract.org/2004/07/FOO.WCF";
var doc = XDocument.Load("C:\\test.xml");
Console.Write(doc.Descendants(ns + "name").First().Value);
```
Edit. Using 2.0
```
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
Console.Write(doc.SelectSingleNode("//a:name", ns).InnerText);
``` | Use System.Xml.XmlTextReader class,
```
System.Xml.XmlTextReader xr = new XmlTextReader(@"file.xml");
while (xr.Read())
{
if (xr.LocalName == "name" && xr.Prefix == "a")
{
xr.Read();
Console.WriteLine(xr.Value);
}
}
``` | issue to get specific XML element value using C# | [
"",
"c#",
".net",
"xml",
"visual-studio-2008",
""
] |
Here a code to demonstrate an annoying problem:
```
class A {
public:
A():
m_b(1),
m_a(2)
{}
private:
int m_a;
int m_b;
};
```
This is an output on *Console* view:
```
make all
Building file: ../test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"test.d" -MT"test.d" -o"test.o" "../test.cpp"
../test.cpp: In constructor 'A::A()':
../test.cpp:9: warning: 'A::m_b' will be initialized after
../test.cpp:8: warning: 'int A::m_a'
../test.cpp:3: warning: when initialized here
Finished building: ../test.cpp
```
The problem is that in *Problems* view I'll see 3 separate warnings (lines in output containing warning word), while indeed there're 4 lines in output describing a one problem.
Is there're something I'm missing?
Additional question. Maybe it's in Eclipse spirit, but is there a way to make *Console* view clickable as most IDE does (e.g. Visual Studio, emacs ...)
Thanks
Dima | According to the last comment on [this](https://bugs.eclipse.org/bugs/show_bug.cgi?id=50124) bug report you should be able to click on the console view to jump to code in CDT 7.0.
It might be worth checking out the milestone builds to see if the grouping of error messages is better. If not raising a bug to attempt to group related messages would be a good idea. | There are multiple lines in the warning because each line refers to a different line of code. The problem being warned about is what's *happening* to the `m_b` that's declared on line 9, it's *because* of the fact that `m_a` on line 8 is declared before `m_b` is, but it's *caused* by what's happening in your initializer list, which starts on line 3.
With gcc it's possible for warnings that aren't related to each other to appear one after the other (i.e., a bunch of unrelated stuff all wrong in `main`), so Eclipse can't tell from the output whether those are separate warnings or all related to the same issue. | Eclipse C++ compilation warning problem | [
"",
"c++",
"eclipse",
"compilation",
"eclipse-cdt",
""
] |
Is there a way to execute python code in a browser, other than using Jython and an applet?
The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.
I am aware that [python can be executed remotely](http://pyro.sourceforge.net/) outside a browser, but my requirement is to be done inside a browser.
For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question. | The [Pyjamas](http://pyjs.org/) project has a compiler called pyjs which turns Python code into Javascript. | nosklo's answer is wrong: pyxpcomext for firefox adds language="python" support to script tags. yes it's a whopping 10mb plugin, but that's life. i think it's best if you refer to <http://wiki.python.org/moin/WebBrowserProgramming> because that is where all known documented links between python and web browser technology are recorded: you can take your pick, there. | Execute python code inside browser without Jython | [
"",
"python",
"browser",
"remote-execution",
""
] |
Is it possible to use gprof to line-profile a single function in C++?
Something like:
```
gprof -l -F function_name ...
```
, which does not seem to work. | That can be done easily with [valgrind](http://valgrind.org/). It is a wonderful tool if you have the chance to use it in your development environment. It even have and graphical interface [kcachegrind](http://kcachegrind.sourceforge.net/html/Home.html). | Try using options with **[symspec]** to filter the results. gprof 2.18.0 says that **-F** and **-f** are deprecated and to use symspec instead.
Also, **-l** may not work with binaries compiled with newer versions of gcc. Try **gcov** instead. | Profile single function in gprof | [
"",
"c++",
"gprof",
""
] |
I'd like to get the largest 100 elements out from a list of at least 100000000 numbers.
I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time.
Is there any existing easy, pythonic way of doing this?
What I want is following function instead of a pure sort. Actually I don't want waste time to sort the elements I don't care.
For example, this is the function I'd like to have:
```
getSortedElements(100, lambda x,y:cmp(x,y))
```
Note this requirement is only for performance perspective. | The heapq module in the standard library offers the nlargest() function to do this:
```
top100 = heapq.nlargest(100, iterable [,key])
```
It won't sort the entire list, so you won't waste time on the elements you don't need. | [Selection algorithms](http://en.wikipedia.org/wiki/Selection_algorithm) should help here.
A very easy solution is to find the 100th biggest element, then run through the list picking off elements that are bigger than this element. That will give you the 100 biggest elements. This is linear in the length of the list; this is best possible.
There are more sophisticated algorithms. A [heap](http://tinyurl.com/6qo3yu), for example, is very amenable to this problem. The heap based algorithm is `n log k` where `n` is the length of the list and `k` is the number of largest elements that you want to select.
There's a discussion of this [problem](http://en.wikipedia.org/wiki/Selection_algorithm#Selecting_k_smallest_or_largest_elements) on the Wikipedia page for selection algorithms.
Edit: Another poster has pointed out that Python has a built in solution to this problem. Obviously that is far easier than rolling your own, but I'll keep this post up in case you would like to learn about how such algorithms work. | How to get the biggest numbers out from huge amount of numbers? | [
"",
"python",
"sorting",
"max",
"minimum",
""
] |
I have a script that takes a key from $\_GET['key'] , looks up the location in a database and uses the readfile together with some headers to present a download for the use. This works in Firefox but not IE8, haven't been able to test it on another IE. I get the following error in IE: "Internet Explorer cannot download download.php from www.example.com". As if it is trying to download the PHP script.
```
$the_query = "SELECT * FROM `files` WHERE `user_id`=" . $_SESSION['user_id'] . " AND `key`='" . $key . "'";
$result = mysql_query($the_query);
$row = mysql_fetch_array($result);
$file = '/var/www/vhosts/www.example.com/httpsdocs/uploads/' . $row['id'] . '/' . $row['file'];
header("Content-type: application/octet-stream");
header("Content-length: ".filesize($file));
header('Content-Description: File Transfer');
header("Cache-control: private");
header('Content-Disposition: attachment; filename=' . rawurlencode(basename($file)));
readfile($file);
``` | To solve the error : "Internet Explorer cannot download download.php from www.example.com",
Add these headers to your script:
`header("Pragma: ");`
`header("Cache-Control: ");`
The code will remove the Cache-Control from headers which makes the download problem.
The above code should be added at the top of the file.
It works fine for us. | Managed to get this working by using the first example from php.net
<https://www.php.net/manual/en/function.readfile.php>
```
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
``` | PHP script to download file not working in IE | [
"",
"php",
"http-headers",
""
] |
I have a default configuration of xampp (LAMP) on a windows system, I have been googleing and reading stackflow for an hour but I can not find where php session data is saved, I would like to locate a session file and look at it.
Some sites say windows usually stores it here C:\windows\tmp\ but I was unable to find it there or anywhere else.
1. Do you know where sessions are saved
by default?f
2. Do you know what kind name and file?
extension they might would have? | [session\_save\_path()](https://www.php.net/manual/en/function.session-save-path.php) - they have no extension, they are long string UID named files. | To find the "for sure" location, do the following:
1. Boot up a cmd prompt
* Run `php --ini` and find the loaded configuration file
* Open the config file and search for 'session.save\_path'
That's the path your session files should be saved to.
This assumes that `session.save_handler` is set to 'files', of course, and isn't overridden anywhere in your code.
By default, it's probably "C:\WINDOWS\Temp". The filenames are generally prefixed with `sess_`, and do not have an extension.
Edit: Other posters are correct in using `session_save_path()` to find the path as well. That's probably a more foolproof method, in case there's differences between your CLI configuration and your web configuration. I'll hand out some +1's. :D | Can you help me locate PHP session files? | [
"",
"php",
"session",
""
] |
I have three classes (class A, class B, and class C).
Class A calls an instance of B and runs start().
Class B extends Thread, so when start() is called, anything in the run() method is executed.
In the run() thread, there is an instance of class C.
Is there anyway to allow a method in Class C to call a method in Class A, without instantiating a new instance of Class A?
Since I can't extend class A to class B (because "Thread" is already extended), I don't know how I'd go about doing this.
Sorry for being vague, but my project features far too much code and is way too complicated to provide a direct code example.
Thanks! | So you have
```
class A {
void run()
{
new B().start();
}
}
class B extends Thread {
public void run(){
C c = new C();
c.do something with A .. }
}
```
You can pass the caller, which might get ugly, as you have to pass A all the way down to C through B:
```
class A {
void run()
{
new B(this).start();
}
}
class B extends Thread {
public void run(A a){
C c = new C();
c.do something(a)..
}
}
```
or simplify, especially if B and C have no other reason for being:
```
class A {
public void run()
{
this.do something() ...
}
}
``` | The best way might be for class B's start to be overloaded to take a parameter (A, or better yet, an interface implemented by A). Then B can either store that for retrieval by C (if it's an inner class) or pass it to C's constructor...
EDIT:
Although as the commenter mentioned overriding the constructor would work, it doesn't fit the parameters of the question which was phrased in such a way that B already existed, so my suggestion is to overload the start() like this:
```
b.start(A aParam) {
a=aParam;
start();
}
```
This version is NOT thread safe however. B's constructor works if B is actually instantiated every time, or if C is instantiated when b starts, then it could be passed to C's constructor as it's instantiated.
By the way, extending thread is not generally as good as implementing runnable for quite a few reasons. | Java extension/abstraction/implementation question | [
"",
"java",
"class",
"implementation",
"abstraction",
""
] |
I have a log file that continually logs short lines. I need to develop a service that reacts (or polls, or listens to) to new lines added to that file, a sort of unix' tail program, so that my service is always up to date reguarding the file.
I don't think that opening a read stream and keeping it opened is a good idea. Maybe I should use the FileSystemWatcher class.
Long story short, I need to parse in real time every new line added to this file.
Any idea help or indication is really appreciated.
**EDIT**
As I've been not very clear. I do not need any program, I am *writing* a program. For reading (then processing) every new line added to the file. I mean that what I'm looking for is a methodology (or: how to implement this?) for continually *tailing* a file that keeps on been written.
I have to develop a Windows service that "listens" to this file and does operations on every new line.
So, if in a given moment the file is:
```
12.31.07 - jdoe [log on] 347
12.32.08 - ssmith [log on] 479
12.32.08 - mpeterson [log off] 532
12.32.09 - apacino [log on] 123
```
in the very moment that the line
```
12.32.11 - pchorr [log on] 127
```
is added to the log file by the logging program (that I have not access to), I need my Windows service to "react" to the line addiction, intercept the new line (`12.32.11 - pchorr [log on] 127`) and process it. And so on.
Now, I don't know how to do this. I should poll the file every n seconds, store the last read line in memory and process only the newly added lines. The problem with this is that is very slow, plus I'd be reading a very large file every time.
Or maybe I could use `FileSystemWatcher`, but I haven't found any example of using it for similar purposes.
So, what would you suggest to get the work done? Thanks. | I would recommend using `FileSystemWatcher` to be notified of changes to the file or files you're concerned about. From there, I would cache information such as the size of the file between events and add some logic to only respond to full lines, etc. You can use the `Seek()` method of the `FileStream` class to jump to a particular point in the file and read only from there. Given these features, it shouldn't be too hard to hand-roll this functionality if that's what you need. | Simple solution would be use , sample code provided in <http://www.codeproject.com/Articles/7568/Tail-NET> article. It is just one function copy/paste into your code. | C#: tail like program for text file | [
"",
"c#",
"logging",
"filesystems",
"stream",
""
] |
I am having real trouble tracking down a bug and it would help be a lot to know which method called a certain method. Is there an easy way to get a call hierarchy from java? Java is a small part of the app so I cannot compile and run the whole app in eclipse/net beans so I don't have access to an IDE debugger's call hierarchy. | ```
Thread.currentThread().getStackTrace();
```
or
```
Exception ex = new Exception();
ex.printStackTrace();
```
It's fairly slow, but fine for debugging purposes. [API docs here](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#getStackTrace()). | > Java is a small part of the app so I cannot compile and run the whole app in eclipse/net beans so I don't have access to an IDE debugger's call hierarchy.
You dont need to run the app at all. If you make a project in Eclipse, you can use its built-in Call Hierarchy tool to find all of the possible places that call a method.
There is a trade off: The Call Hierarchy tool will give you ALL of the places from where a method is called. This is a good if you want/need to know all the possibilities. Neslson's suggestion of `Thread.currentThread().getStackTrace()` will give you the places from where a method is invoked during the process of you program for this invocation. The nuance is that you might not run through every code path during this invocation. If you are seeing specific behavior and want to know how you got there, use the `getStackTrace()` option. | Getting a call hierarchy in java | [
"",
"java",
"call",
"hierarchy",
""
] |
I see people use "window.onload" all the time, but why? Isn't the "window" part completely superfluous? | If you don't, then the onload method will be attributed to the current object, whatever that is (if any). So sometimes it may work, but writing window.onload is the most explicit, specific and safe way to do it. | [link text](https://developer.mozilla.org/en/DOM/window.onload)
"The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading."
need to start working with the full DOM | JavaScript "window.onload" – is "window" really necessary? | [
"",
"javascript",
"events",
"function",
"window",
""
] |
I'm using python's `ftplib` to write a small FTP client, but some of the functions in the package don't return string output, but print to `stdout`. I want to redirect `stdout` to an object which I'll be able to read the output from.
I know `stdout` can be redirected into any regular file with:
```
stdout = open("file", "a")
```
But I prefer a method that doesn't uses the local drive.
I'm looking for something like the `BufferedReader` in Java that can be used to wrap a buffer into a stream. | ```
from cStringIO import StringIO # Python3 use: from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
sys.stdout = old_stdout
# examine mystdout.getvalue()
``` | There is a [`contextlib.redirect_stdout()` function](http://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout) in Python 3.4+:
```
import io
from contextlib import redirect_stdout
with io.StringIO() as buf, redirect_stdout(buf):
print('redirected')
output = buf.getvalue()
```
Here's a [code example that shows how to implement it on older Python versions](https://stackoverflow.com/a/22434262). | Can I redirect the stdout into some sort of string buffer? | [
"",
"python",
"stream",
"stdout",
"redirect",
""
] |
What's the best way to detect the language of a string? | If the context of your code have internet access, you can try to use the Google API for language detection.
<http://code.google.com/apis/ajaxlanguage/documentation/>
```
var text = "¿Dónde está el baño?";
google.language.detect(text, function(result) {
if (!result.error) {
var language = 'unknown';
for (l in google.language.Languages) {
if (google.language.Languages[l] == result.language) {
language = l;
break;
}
}
var container = document.getElementById("detection");
container.innerHTML = text + " is: " + language + "";
}
});
```
And, since you are using c#, take a look at [this article](http://www.esotericdelights.com/post/2008/11/Calling-Google-Ajax-Language-API-for-Translation-and-Language-Detection-from-C.aspx) on how to call the API from c#.
UPDATE:
That c# link is gone, here's a cached copy of the core of it:
```
string s = TextBoxTranslateEnglishToHebrew.Text;
string key = "YOUR GOOGLE AJAX API KEY";
GoogleLangaugeDetector detector =
new GoogleLangaugeDetector(s, VERSION.ONE_POINT_ZERO, key);
GoogleTranslator gTranslator = new GoogleTranslator(s, VERSION.ONE_POINT_ZERO,
detector.LanguageDetected.Equals("iw") ? LANGUAGE.HEBREW : LANGUAGE.ENGLISH,
detector.LanguageDetected.Equals("iw") ? LANGUAGE.ENGLISH : LANGUAGE.HEBREW,
key);
TextBoxTranslation.Text = gTranslator.Translation;
```
---
Basically, you need to create a URI and send it to Google that looks like:
> <http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20worled&langpair=en%7ciw&key=your_google_api_key_goes_here>
This tells the API that you want to translate "hello world" from English to Hebrew, to which Google's JSON response would look like:
```
{"responseData": {"translatedText":"שלום העולם"}, "responseDetails": null, "responseStatus": 200}
```
I chose to make a base class that represents a typical Google JSON response:
```
[Serializable]
public class JSONResponse
{
public string responseDetails = null;
public string responseStatus = null;
}
```
Then, a Translation object that inherits from this class:
```
[Serializable]
public class Translation: JSONResponse
{
public TranslationResponseData responseData =
new TranslationResponseData();
}
```
This Translation class has a TranslationResponseData object that looks like this:
```
[Serializable]
public class TranslationResponseData
{
public string translatedText;
}
```
Finally, we can make the GoogleTranslator class:
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
namespace GoogleTranslationAPI
{
public class GoogleTranslator
{
private string _q = "";
private string _v = "";
private string _key = "";
private string _langPair = "";
private string _requestUrl = "";
private string _translation = "";
public GoogleTranslator(string queryTerm, VERSION version, LANGUAGE languageFrom,
LANGUAGE languageTo, string key)
{
_q = HttpUtility.UrlPathEncode(queryTerm);
_v = HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(version));
_langPair =
HttpUtility.UrlEncode(EnumStringUtil.GetStringValue(languageFrom) +
"|" + EnumStringUtil.GetStringValue(languageTo));
_key = HttpUtility.UrlEncode(key);
string encodedRequestUrlFragment =
string.Format("?v={0}&q={1}&langpair={2}&key={3}",
_v, _q, _langPair, _key);
_requestUrl = EnumStringUtil.GetStringValue(BASEURL.TRANSLATE) + encodedRequestUrlFragment;
GetTranslation();
}
public string Translation
{
get { return _translation; }
private set { _translation = value; }
}
private void GetTranslation()
{
try
{
WebRequest request = WebRequest.Create(_requestUrl);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadLine();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Translation));
Translation translation = ser.ReadObject(ms) as Translation;
_translation = translation.responseData.translatedText;
}
}
catch (Exception) { }
}
}
}
``` | *Fast answer:* [**NTextCat**](https://github.com/ivanakcheurov/ntextcat) ([NuGet](http://www.nuget.org/packages/NTextCat/), [Online Demo](http://ivanakcheurov.github.io/ntextcat/))
*Long answer:*
Currently the best way seems to use classifiers **trained** to classify piece of text into one (or more) of languages from predefined set.
There is a Perl tool called [TextCat](http://odur.let.rug.nl/~vannoord/TextCat/). It has language models for 74 most popular languages. There is a huge number of ports of this tool into different programming languages.
There were no ports in .Net. So I have written one: [**NTextCat** on GitHub](https://github.com/ivanakcheurov/ntextcat).
It is **pure .NET Framework** DLL + command line interface to it. By default, it uses a profile of 14 languages.
Any feedback is very appreciated!
New ideas and feature requests are welcomed too :)
Alternative is to use numerous online services (e.g. one from Google mentioned, detectlanguage.com, langid.net, etc.). | How to detect the language of a string? | [
"",
"c#",
"language-detection",
""
] |
The default background color of a selected row in DataGrid is so dark that I can't read it. Is there anyway of overriding it?
Tried this
```
<dg:DataGrid.RowStyle>
<Style TargetType="{x:Type dg:DataGridRow}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Background" Value="Gainsboro" />
</Trigger>
</Style.Triggers>
</Style>
</dg:DataGrid.RowStyle>
```
But still nothing... | Got it. Add the following within the DataGrid.Resources section:
```
<DataGrid.Resources>
<Style TargetType="{x:Type dg:DataGridCell}">
<Style.Triggers>
<Trigger Property="dg:DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="#CCDAFF" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
``` | The above solution left blue border around each cell in my case.
This is the solution that worked for me. It is very simple, just add this to your `DataGrid`. You can change it from a `SolidColorBrush` to any other brush such as linear gradient.
```
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#FF0000"/>
</DataGrid.Resources>
``` | How can I set the color of a selected row in DataGrid | [
"",
"c#",
"wpf",
"xaml",
"datagrid",
""
] |
In Windows, if I open a command prompt, start python, and inspect something using its \_\_doc\_\_ property, it doesn't display correctly. Instead of the lines being separated, I see one continuous string with the newline character every once and a while.
Is there a way to make it appear correctly?
Here's an example of what I see:
>>> hashlib.\_\_doc\_\_
'hashlib module - A common interface to many hash functions.\n\nnew(name, string=\'\') - returns a n
ew hash object implementing the\n given hash function; initializing the hash\n
using the given string data.\n\nNamed constructor functions are also availabl
e, these are much faster\nthan using new():\n\nmd5(), sha1(), sha224(), sha256(), sha384(), and sha5
12()\n\nMore algorithms may be available on your platform but the above are\nguaranteed to exist.\n\
nNOTE: If you want the adler32 or crc32 hash functions they are available in\nthe zlib module.\n\nCh | try
```
>>> print hashlib.__doc__
```
or (v3)
```
>>> print(hashlib.__doc__)
``` | Rather than pulling `__doc__` yourself, try this:
```
>>> help(hashlib)
```
It will give you a nicely formatted summary of the module, including (but not limited to) the docstring. | Make python __doc__ property display correctly in a Windows CMD window? | [
"",
"python",
""
] |
This question is based on [this answer](https://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl/1198220#1198220).
**What does the following sentence mean?**
> Finally, don't use mixed case
> identifiers. Do everything lowercase,
> so you don't have to quote them.
**Does it mean that I should change the commands such as CREATE TABLE, USER\_ID and NOT NULL to lowercase?** - It cannot because it would be against common naming conventions. | No, I think the gentleman referred to using all lowercase identifiers, e.g. table, column etc. names. This should have no impact on the commands like CREATE TABLE etc. that you use.
Marc | In `PostgreSQL`, an unquoted identifier is converted into lowercase:
```
CREATE TABLE "MYTABLE" (id INT NOT NULL);
CREATE TABLE "mytable" (id INT NOT NULL);
INSERT
INTO "MYTABLE"
VALUES (1);
INSERT
INTO "mytable"
VALUES (2);
SELECT *
FROM mytable;
---
2
SELECT *
FROM MYTABLE;
---
2
```
Both queries will return `2`, since they are issued against `"mytable"`, not `"MYTABLE"`.
To return `1` (i. e. issue a query against `"MYTABLE"`, not `"mytable"`), you need to quote it:
```
SELECT *
FROM "MYTABLE";
---
1
```
`CREATE TABLE` etc. are not identifiers, they are reserved words.
You can use them in any case you like. | To understand a sentence about the case in SQL/DDL -queries | [
"",
"sql",
"database",
"ddl",
""
] |
All over our project, we have this kind of enums. They works just fine, but we are not sure about them.
Specially with the getDocumentType(String) method.
Is there a way to avoid the iteration over all the Enums field ?
```
public enum DocumentType {
UNKNOWN("Unknown"),
ANY("Any"),
ASSET(Asset.class.getSimpleName()),
MEDIA(Media.class.getSimpleName()),
MEDIA35MM(Media.class.getSimpleName() + " 35mm");
private String label;
private DocumentType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static DocumentType getDocumentType(String label){
for(DocumentType documentType : DocumentType.values()){
if(documentType.getLabel().equals(label)){
return documentType;
}
}
return UNKNOWN;
}
}
```
Edit :
Check the newacct response. She's fine too. | You're going to have to do that iteration somewhere, due to the restrictions in writing enums. In an ideal world, you would populate a static Map from within DocumentType's constructor, but that's not allowed.
The best I can suggest is performing the iteration once in a static initializer, and storing the enums in a lookup table:
```
public enum DocumentType {
.... existing enum stuff here
private static final Map<String, DocumentType> typesByLabel = new HashMap<String, DocumentType>();
static {
for(DocumentType documentType : DocumentType.values()){
typesByLabel.put(documentType.label, documentType);
}
}
public static DocumentType getDocumentType(String label){
if (typesByLabel.containsKey(label)) {
return typesByLabel.get(label);
} else {
return UNKNOWN;
}
}
}
```
At least you won't be doing the iteration every time, although I doubt you'll see any meaningful performance improvement. | If the strings are known at compile-time, and if they are valid identifiers, you can just use them as the names of the enums directly:
```
public enum DocumentType { Unknown, Any, Asset, Media, Media35mm }
```
and then get it by `.valueOf()`. For example:
```
String label = "Asset";
DocumentType doctype;
try {
doctype = DocumentType.valueOf(label);
} catch (IllegalArgumentException e) {
doctype = DocumentType.Unknown;
}
``` | is my Enumeration correct? | [
"",
"java",
"enums",
"correctness",
""
] |
How do you create or replace a role (that might or might not exist) in Oracle? For example, the following does not work:
```
CREATE OR REPLACE ROLE role_name;
GRANT SELECT ON SCM1_VIEW_OBJECT_VW TO role_name;
```
Any way to do this without PL/SQL? | **Solution**
A combination of the given answers and a pragma control accomplishes this task for Oracle 10g.
```
CREATE OR REPLACE PROCEDURE create_role( role_name IN VARCHAR2 ) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
EXECUTE IMMEDIATE 'CREATE ROLE '||role_name;
EXCEPTION
WHEN OTHERS THEN
-- ORA-01921: If The role name exists, ignore the error.
IF SQLCODE <> -01921 THEN
RAISE;
END IF;
END create_role;
```
**Test**
This sequence works:
```
DROP ROLE role_name;
CREATE ROLE role_name;
CALL create_role( 'role_name' );
CALL create_role( 'role_name' );
```
The final create role statement fails, as expected:
```
DROP ROLE role_name;
CALL create_role( 'role_name' );
CREATE ROLE role_name;
``` | Best practice is to attempt the creation of the role, then handle the appropriate exception gracefully if it occurs; this means you don't need to run potentially expensive data dictionary queries:
```
begin
execute immediate 'create role role_name';
exception
when others then
--"ORA-01921: role name 'x' conflicts with another user or role name"
if sqlcode = -01921 then
null;
else
raise;
end if;
end;
```
And yes, you need PL/SQL to do this - it's the best tool for this job, anyway. | Create or replace role? | [
"",
"sql",
"oracle",
"plsql",
"roles",
""
] |
About to start working on a social networking site, but I'd like to incorporate OpenID logins.
The JanRain plugin is packed in Debian, but seems flakey, and my brief interactions with it so far have not gone well. There's a bunch of others out there, but which ones are people using in production? | The [OpenID Wiki](http://wiki.openid.net/Libraries) has a great list of libraries available for PHP. Always begin your searches in the official documentation.
I have personally used and recommend [EasyOpenId](http://www.codymays.net/content/2007/02/20/the-future-and-openid/) (requires [PHP OpenID](http://www.openidenabled.com/php-openid/)). | See [PHP library for openID](https://stackoverflow.com/questions/388749/php-library-for-openid) for a list of other PHP OpenID libraries.
I personally use the [PEAR OpenID](http://pear.php.net/package/OpenID) library. | PHP library for OpenID | [
"",
"php",
"plugins",
"openid",
"debian",
""
] |
```
import java.util.Collection;
public class Test
{
public static void main(String[] args)
{
Collection c = null;
Test s = null;
s = (Test) c;
}
}
```
In the code sample above, I am casting a collection object to a Test object. (ignoring the null pointer). Test has *no* relationship to Collection whatsoever, yet this program will pass all compile-time checks.
I'm wondering why this is. My assumption is that interfaces are ignored because they are too complicated. They have no common super-type and each class can implement several interfaces, so the class/interface hierarchy would be too complicated to search efficiently?
Other than that reason I am stumped though. Does anyone know?! | "Non-final" is a keyword here. You may have another class
```
public class Test2 extends Test implements Collection
```
whose instance will end up being assigned to `s` making a cast perfectly legal. | Because a subclass of `Test` can potentially be a subtype of `Collection` as well! The language specification is designed to be a bit flexible to permit casts that can be verified at run-time. | Why can we cast a Java interface to *any* non-final class? | [
"",
"java",
"interface",
"downcast",
""
] |
Lately I've been getting very excited about the support for lambdas in VC2010. I'm slowly starting to grasp the full potential this feature has in transforming C++ into something alot better.
But then I realized that this potential greatly depends on main stream support of lambdas in day to day libraries like boost and QT.
Does anyone know if there are plans to extend these libraries with the new features of C++0x?
lambdas practically replace the need for boost::lambda and everything in boost that interacts with it.
QT could add support for lambdas in all of their container and maybe even as an alternative way of defining `SLOT`s | Lambdas already fit very well into existing libraries - anywhere that a function accepts a function object of a type given by a template parameter.
This is one of the great things about them - they're a classic example of a language feature that codifies existing practice in a nifty syntax.
Obviously the boost lambda library becomes redundant, but that means it doesn't require any new features to be added to it. | I don't see how usage of lambda depends on support by libraries. Lambdas eliminate the need to create many classes just to wrap different small algorithms and neatly fit together with other language/library features (`std::function` comes to mind). Wherever you used to pass either a function object or a function pointer, lambdas can be used, too.
So they mainly add another alternative for making use of existing code and libraries. The only way I can see for libraries to better support lambda is use more functional-style approaches. | Library plans for C++0x? | [
"",
"c++",
"qt",
"boost",
"c++11",
""
] |
I am trying out some cascade options with nhibernate mapping and have a unit test where I'd like to use a tool to inspect the state of the database. I was hoping I could use linqpad to do this, but the connection seems hung while in the debugger. I'd seen a demo not to long ago where SSMS was being used to inspect the db during a debug, so I'm wondering if I should be able to somehow use linqpad or if I need a different tool (I haven't installed SSMS on my laptop and would prefer something more light weight).
Unrelated to linqpad, my motivation for doing this is I am not sure if the db state I'm validating in a unit test is from the db or from nhibernate's cache? If Session.Flush() is called before the the assert, does that mean a fetch in an assert is guaranteed to be coming from the db?
Cheers,
Berryl | To the second part of your question - Yes, calling session.flush() before any kind of fetch will push everything out to the DB. You could also do:
```
Transaction t = session.beginTransaction();
//some hibernate interaction test code
t.commit()
//you can rest assured that any code coming from the hibernate now will
//be exactly what is in the db.
```
hope that helps. | SQL Profiler (Tools > SQL Server Profile from SSMS) or [NHProf](http://nhprof.com/) will help you monitor commands sent to the database. | database inspection while debugging | [
"",
"c#",
"unit-testing",
"nhibernate",
"ssms",
"linqpad",
""
] |
I'm trying to decode HTML entries from here [NYTimes.com](http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?_r=1&hp) and I cannot figure out what I am doing wrong.
Take for example:
```
"U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’"
```
I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart\_str without any success. | **Try this:**
```
import re
def _callback(matches):
id = matches.group(1)
try:
return unichr(int(id))
except:
return id
def decode_unicode_references(data):
return re.sub("&#(\d+)(;|(?=\s))", _callback, data)
data = "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’"
print decode_unicode_references(data)
``` | ```
>>> from HTMLParser import HTMLParser
>>> print HTMLParser().unescape('U.S. Adviser’s Blunt Memo on Iraq: '
... 'Time ‘to Go Home’')
U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’
```
The function is undocumented in Python 2. [It is fixed in Python 3.4+](http://bugs.python.org/issue2927): it is exposed as [`html.unescape()` there](https://docs.python.org/3/library/html.html#html.unescape). | Decoding HTML entities with Python | [
"",
"python",
"unicode",
"character-encoding",
"content-type",
"beautifulsoup",
""
] |
I am trying to do full-text searching in PostgreSQL 8.3. It worked splendidly, so I added in synonym matching (e.g. `'bob' == 'robert'`) using a synonym dictionary. That works great too.
However, I've noticed that it apparently only allows a word to have **one** synonym. That is, `al` cannot be `albert` or `allen`.
Is this correct? Is there any way to have multiple dictionary matches in a PostgreSQL synonym dictionary?
For reference, here is my sample dictionary file:
```
bob robert
bobby robert
al alan
al albert
al allen
```
And the SQL that creates the full text search config:
```
CREATE TEXT SEARCH DICTIONARY nickname (TEMPLATE = synonym, SYNONYMS = nickname);
CREATE TEXT SEARCH CONFIGURATION dxp_name (COPY = simple);
ALTER TEXT SEARCH CONFIGURATION dxp_name ALTER MAPPING FOR asciiword WITH nickname, simple;
``` | That's a limitation in how the synonyms work. What you can do is turn it around as in:
```
bob robert
bobby robert
alan al
albert al
allen al
```
It should give the same end result, which is that a search for either one of those will match the same thing. | A dictionary must define a functional relationship between words and lexemes otherwise it won't know which word to return when you lexize. In your example, `al` maps to three different values thus defining a multi-valued function and the lexize function doesn't know what to return. As Magnus shows, you can lexize from the proper names `alan, albert, allen` to the nickname `al`.
Remember however, that the point of an FTS dictionary is not to perform transformations per se but to allow efficient indexing on semantically relevant words. This means that the lexeme need not resemble the original entry in any linguistic sense. Although you're right that a many-to-many relationship is impossible to define, do you really need to? For example, to resolve your `vin` example:
```
vin vin
vincent vin
vincenzo vin
vinnie vin
```
but you could also do this:
```
vin grob
vincent grob
vincenzo grob
vinnie grob
```
and get the same effect (although why you'd want to is another story).
Thus if you were to parse a document with say 11 versions of the name Vincent then the `to_tsvector` function would return `vin:11` in the former case and `grob:11` in the latter. | Multiple synonym dictionary matches in full-text searching | [
"",
"sql",
"postgresql",
"full-text-search",
""
] |
Is it not possible to append to an `ObjectOutputStream`?
I am trying to append to a list of objects. Following snippet is a function that is called whenever a job is finished.
```
FileOutputStream fos = new FileOutputStream
(preferences.getAppDataLocation() + "history" , true);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject( new Stuff(stuff) );
out.close();
```
But when I try to read it I only get the first in the file.
Then I get `java.io.StreamCorruptedException`.
To read I am using
```
FileInputStream fis = new FileInputStream
( preferences.getAppDataLocation() + "history");
ObjectInputStream in = new ObjectInputStream(fis);
try{
while(true)
history.add((Stuff) in.readObject());
}catch( Exception e ) {
System.out.println( e.toString() );
}
```
I do not know how many objects will be present so I am reading while there are no exceptions. From what Google says this is not possible. I was wondering if anyone knows a way? | Here's the trick: subclass `ObjectOutputStream` and override the `writeStreamHeader` method:
```
public class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}
}
```
To use it, just check whether the history file exists or not and instantiate either this appendable stream (in case the file exists = we append = we don't want a header) or the original stream (in case the file does not exist = we need a header).
**Edit**
I wasn't happy with the first naming of the class. This one's better: it describes the 'what it's for' rather then the 'how it's done'
**Edit**
Changed the name once more, to clarify, that this stream is only for appending to an existing file. It can't be used to create a *new* file with object data.
**Edit**
Added a call to `reset()` after [this question](https://stackoverflow.com/questions/12279245/classcastexception-when-appending-object-outputstream/12438141#12438141) showed that the original version that just overrode `writeStreamHeader` to be a no-op could under some conditions create a stream that couldn't be read. | As the [API](http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html#ObjectOutputStream(java.io.OutputStream)) says, the `ObjectOutputStream` constructor writes the serialization stream header to the underlying stream. And this header is expected to be only once, in the beginning of the file. So calling
```
new ObjectOutputStream(fos);
```
multiple times on the `FileOutputStream` that refers to the same file will write the header multiple times and corrupt the file. | Appending to an ObjectOutputStream | [
"",
"java",
"serialization",
"append",
"objectoutputstream",
"objectinputstream",
""
] |
Very new to jQuery, if dupe question sorry at this point not even sure I am using correct verbiage.
I need to add a li item to a ul based on a click event of a ListBox (user selects text and a new li is added with the selected text). And I need to add a icon, label and input on the li item. The icon needs to be a 'remove' icon.
How can I wire up the function to remove the newly added li item via jQuery?
Here is what I have tried;
```
$(function() {
function addSelectedWordCriteria() {
var selectedWord = $("#wsWords").val();
$("#wsCriteriaList").append("<li><a href='#' class='wsCriteriaRemove'><span class='ui-icon ui-icon-circle-close'/></a><em class='wsFilteredWord'>" + selectedWord + "</em><input type='textbox' maxlength='200' class='wsFilteredWords'/></li>");
$("#wsCriteriaList a:last").bind("click", "removeSelectedWordCriteria");
};
function removeSelectedWordCriteria() {
$("#wsCriteriaList").selected().remove();
}
})
<%= Html.ListBox("wsWords", ViewData["Words"] as IEnumerable<SelectListItem>) %>
<ul id="wsCriteriaList">
</ul>
```
Thanks for any suggestions. | To your immediate question, since the click event gives you a reference to the element that sent the event, you could use it quickly determine what should be removed:
```
function removeSelectedWordCriteria() {
$(this).parent().remove();
}
```
Other things I may change about this code:
1. As ScottE pointed out, this could be a great place to use the new live function. Outside of your addSelectedWordCriteria method, you should be able to put in:
```
$("#wsCriteriaList a").live("click", "removeSelectedWordCriteria");
```
And that will register all of your a tags with the same event even as they get added.
2. Speaking of a tags, I'm not sure if you really need yours. All you really want is to be able to click the span that contains the remove image. Since you're not actually using a link, personally, I would take out the anchor tag all together and put the click event directly on the span tag. You could then give it a class for the above live function.
Let me know if you have additional questions. | You're not using the bind method properly - you have your method call enclosed in quotes.
<http://docs.jquery.com/Events/bind#typedatafn> | jQuery adding <li> Item and click Events | [
"",
"c#",
"asp.net",
"jquery",
""
] |
I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
```
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);
```
Any better way of coding? | If you don't want to repeat this a lot, just create a helper function, like this:
```
public static class DataReaderExtensions
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
```
Which you can call like this:
```
value = reader.GetStringOrNull(n);
``` | The code you posted is fine. You could also do something like that :
```
value = r[n] as string;
```
If the value in the database is null, `r[n]` will return DBNull.Value, and the cast to `string` will return `null`. | SqlDataReader.GetString and sqlnullvalueexception | [
"",
"c#",
".net",
""
] |
At the moment I am using one list to store one part of my data, and it's working perfectly in this format:
```
Item
----------------
Joe Bloggs
George Forman
Peter Pan
```
Now, I would like to add another line to this list, for it to work like so:
```
NAME EMAIL
------------------------------------------------------
Joe Bloggs joe@bloggs.com
George Forman george@formangrills.co
Peter Pan me@neverland.com
```
I've tried using this code to create a list within a list, and this code is used in another method in a foreach loop:
```
// Where List is instantiated
List<List<string>> list2d = new List<List<string>>
...
// Where DataGrid instance is given the list
dg.DataSource = list2d;
dg.DataBind();
...
// In another method, where all people add their names and emails, then are added
// to the two-dimensional list
foreach (People p in ppl.results) {
list.Add(results.name);
list.Add(results.email);
list2d.Add(list);
}
```
When I run this, I get this result:
```
Capacity Count
----------------
16 16
16 16
16 16
... ...
```
Where am I going wrong here. How can I get the output I desire with the code I am using right now? | Why don't you use a `List<People>` instead of a `List<List<string>>` ? | Highly recommend something more like this:
```
public class Person {
public string Name {get; set;}
public string Email {get; set;}
}
var people = new List<Person>();
```
Easier to read, easy to code. | Multidimensional Lists in C# | [
"",
"c#",
"list",
""
] |
I have an XML-File, which has the following structure:
```
<mediawiki ...>
<siteinfo>...</siteinfo>
<page>
<title>The Title</title>
<id>42</id>
...
</page>
... more page items ...
</mediawiki>
```
I red a bit about XPath-Query and wrote the following code:
```
_xmlArticlesDocument = new XmlDocument();
_xmlArticlesDocument.Load(xmlArticlesFileName);
```
Now I want to get a grip on a page Element with a given id-Subelement. So I wrote:
```
XmlNode node = _xmlArticlesDocument.DocumentElement.SelectSingleNode
("//mediawiki/page[id=" + id.ToString() + "]");
```
but node is always null. I have tried several querys, including "page/id", "page", "/page", "//page" to get *anything*, but node is always null. I have checked via quick inspection the \_xmlArticlesDocument variable and it contains the correct XML-file with the expected structure.
It seems to me, that I have missed something very basic, but have no idea what. Maybe someone here has an idea?
Thanks in advance,
Frank | The query looks right on the basis of what you shown us so far. However I suspect behin the "..." on the mediawiki element there is a xmlns="...." attribute right?
That'll be what is tripping you up I suspect. You will need code like this:-
```
XmlNamespaceManager nsmgr = new XmlNamespaceManager(_xmlArticlesDocument.NameTable);
nsmgr.AddNamespace("a", "the-namespace-in-them-xmlns-attribute");
XmlNode page = _xmlArticlesDocument.SelectSingleNode(String.Format("//a:page[id={0}]", id), nsmgr);
``` | Have you tried:
```
_xmlArticlesDocument.DocumentElement.SelectSingleNode
("page[id='" + id.ToString() + "']"); // Note the single quotes
```
Also, if any of the XML nodes are in a namespace that is not the default one (i.e. `<mediawiki xmlns="whatever">`) then you are also going to need an [`XmlNamespaceManager`](http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.aspx). | C# and XPath - how to query | [
"",
"c#",
"xpath",
""
] |
I'm using Hibernate backed JPA as my persistence layer. I have a multi-threaded process that aggregates data from a Soap call and then stores a row in a database. The process usually ends up inserting about 700 rows and takes about 1 - 3 hours, with the Soap calls being the main bottleneck.
**During this entire process the table I am inserting into locks up and will not return select statements in a timely manner.**
Here is the SQL server error:
> Error Message: Lock request time out period exceeded.
How do I avoid locking my database table during this lengthy process? | Do you insert all 700 rows with the *same* transaction?
Where is your transaction boundary? If you could maybe lower your transaction bounday, i.e. only transaction the actual insert operation so the lock is brielfy held.
If you need to have the whole process to be atomic it might be an idea to write it into a temp table and then do a bulk insert (fast) to insert it into the main table. | You probably need to change your isolation level.
Here is some information:
<http://www.interview-questions-tips-forum.net/index.php/Your-Questions-on-Java/JDBC-Transaction/Transaction-Isolation-Levels>
It talks about the different isolation levels, and what they can help guard against. The general way to do this is to start with the strictist, and then go lower if you need better response times, while keeping in mind the requirements of data integrity/false reads.
**edit**
Spring Transaction levels are used to abstract JDBC (or whatever) transaction isolation levels at the transaction manager. They are defined in the [TransactionDefinition](http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/transaction/TransactionDefinition.html) class, and are static members.
```
TransactionDefinition.ISOLATION_DEFAULT
Default isolation
TransactionDefinition.ISOLATION_READ_UNCOMMITTED
Lowest level of isolation; allows transactions to see uncommitted modifications from other transactions
TransactionDefinition.ISOLATION_READ_COMITTED
Cannot read uncommitted data
TransactionDefinition.ISOLATION_REPEATABLE_READ
Ensures repeatable reads
TransactionDefinition.ISOLATION_SERIALIZABLE
Most reliable; all transactions are executed atomically, and are treated as though they occurred serially.
```
There are also transaction propagation levels. You may be using a transaction for pure reads, which might be overkill - reads do not require transactions, writes should ALWAYS have a transaction around them. The propagation levels are definite in TransactionDefinition as well. These are used, usually in a spring wiring file, to define the serialization and propagation for a particular call. If you have an example of your wiring up, I might be able to give some more hints/information. | How do I prevent JPA inserts from locking a database table? | [
"",
"java",
"database",
"hibernate",
"jpa",
"persistence",
""
] |
How can I refactor this so that **numberOfItems** doesn't have to be declared as a variable?
```
//method: gets the text in a string in front of a marker, if marker is not there, then return empty string
//example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "letter043.doc"
//example: GetTextAfterMarker("letter043.doc","/") returns ""
//example: GetTextAfterMarker("letter043.doc",".") returns "doc"
public static string GetTextAfterMarker(string line, string marker)
{
int numberOfItems = line.Split(new string[] { marker }, StringSplitOptions.None).Count();
string result = line.Split(new string[] { marker }, StringSplitOptions.None)[numberOfItems-1];
return line.Equals(result) ? string.Empty : result;
}
``` | If you're using 3.5 this is trivial with Linq:
```
public static string GetTextAfterMarker2(string line, string marker)
{
string result = line.Split(new string[] { marker }, StringSplitOptions.None).Last();
return line.Equals(result) ? string.Empty : result;
}
``` | ```
var index = line.LastIndexOf (marker) ;
return index < 0 ? string.Empty : line.Substring (index + marker.Length) ;
``` | How can I refactor this C# code using Split()? | [
"",
"c#",
"string",
"refactoring",
""
] |
I'm using linq to retrieve a row from a table in the database.
Now I only update 1 column.
Then I update it back into the database.
this goes well, except for the times any of the other fields is changed by another process/thread/user
In that case I get an exception (optimistic concurrency), telling me to look out, values have been changed since I last got the object with linq.
Since I'm only interested in this 1 column, can I tell linq to just update this column and ignore the others? (and warn me this one column has indeed been changed)
R | You can detect and resolve your concurrency issues by catching a [ChangeConflictException](http://msdn.microsoft.com/en-us/library/system.data.linq.changeconflictexception.aspx):
```
using (var db = new MyDataContext())
{
var row = db.MyTable.Single(x => x.Id == tableId); // Getting the row
row.Column = columnNewValue; // Assign the new value
try
{
db.SubmitChanges();
}
catch (ChangeConflictException)
{
db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
db.SubmitChanges();
}
}
```
With [RefreshMode](http://msdn.microsoft.com/en-us/library/system.data.linq.refreshmode.aspx).[KeepChanges](http://msdn.microsoft.com/en-us/library/system.data.linq.refreshmode.keepchanges.aspx) all the changes made to your client objects will persist, and the changes from other users/processes/threads, on other columns will be merged.
In your case, only your column will be changed.
Recommended articles:
* [Optimistic Concurrency Overview](http://msdn.microsoft.com/en-us/library/bb399373.aspx)
* [LINQ To SQL Samples - Optimistic Concurrency](http://msdn.microsoft.com/en-us/vbasic/bb737933.aspx)
* [Resolve Concurrency Conflicts by Merging with Database Values (LINQ to SQL)](http://msdn.microsoft.com/en-us/library/bb386918.aspx) | There is a good article in MSDN:
[Simultaneous Changes](http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic19)
The following example (a little further in the article) may be of special interest:
```
public partial class Northwind : DataContext
{
...
public void UpdateProduct(Product original, Product current) {
// Execute the stored procedure for UnitsInStock update
if (original.UnitsInStock != current.UnitsInStock) {
int rowCount = this.ExecuteCommand(
"exec UpdateProductStock " +
"@id={0}, @originalUnits={1}, @decrement={2}",
original.ProductID,
original.UnitsInStock,
(original.UnitsInStock - current.UnitsInStock)
);
if (rowCount < 1)
throw new Exception("Error updating");
}
...
}
}
```
with your stored procedure being:
```
create proc UpdateProductStock
@id int,
@originalUnits int,
@decrement int
as
UPDATE Product
SET originalUnits=@originalUnits,
decrement=@decrement
WHERE id=@id
```
In my experience, the best way to go is making your own stored procedure. Linq doesn't offer an easy way to do simultaneous changes, unless you set "UpdateCheck" properties from (almost) all your columns to "Never". | only update 1 column with linq | [
"",
"sql",
"linq",
"concurrency",
""
] |
This is my original xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<table>
<row>
<id>12</id>
<name>Mickey Mouse</name>
</row>
</table>
```
This is the output after going through encryption/decryption process
```
<?xml version="1.0" encoding="UTF-8"?>
<table>
<row>
<id>12</id>
<name>Mickey Mouse</name>
</row>
</
```
As you can see, few characters are missing.
here is my code.
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Decrypter
{
/**
* @param args
* @throws IOException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
// TODO Auto-generated method stub
File iFile = new File("normal.xml");
FileInputStream fis = new FileInputStream(iFile);
File oFile = new File("normal.xml.encrypted");
FileOutputStream fos = new FileOutputStream(oFile);
String algorithm = "DESede";
byte[] keyBytes = new byte[] { 0x34, 0x11, 0x12, 0x06, 0x34, 0x11,
0x12, 0x06, 0x34, 0x11, 0x12, 0x06, 0x34, 0x11, 0x12, 0x06,
0x34, 0x11, 0x12, 0x06, 0x34, 0x11, 0x12, 0x06 };
SecretKeySpec key = new SecretKeySpec(keyBytes, algorithm);
// generates encrypted output from normal.xml.
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
while ((b = fis.read()) != -1)
{
cos.write(b);
}
fos.close();
fos = null;
fis.close();
fis = null;
System.out.println("done");
// decrypt encrypted xml to normal xml.
File ieFile = new File("normal.xml.encrypted");
FileInputStream fies = new FileInputStream(ieFile);
Cipher ieCipher = Cipher.getInstance(algorithm);
ieCipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream cis = new CipherInputStream(fies, ieCipher);
File oeFile = new File("normal.xml.encrypted.xml");
FileOutputStream foes = new FileOutputStream(oeFile);
int c;
while ((c = cis.read()) != -1)
{
foes.write(c);
}
foes.close();
cis.close();
fies.close();
System.out.println("done done");
}
}
```
Please help. Thanks. | Found the problem. Do
```
cos.close();
```
before the line:
```
fos.close();
```
At least, that fixed it on my box. | After writing the encrypted output, call
```
cos.close();
```
instead of
```
fos.close();
```
Closing the cos object also closes the underlying fos object. | few characters missing after decryption | [
"",
"java",
"encryption",
""
] |
I'm designing a database application which stores simple contact information (First/Last Name etc.) and I also have to store phone numbers. Besides phone numbers I have to store what they are for (mobile, business etc.) and possibly an additional comment for each.
My first approach was to normalize and keep the phone numbers in a separate table, so that I have my 'Contacts' and my 'PhoneNumbers' table. The PhoneNumbers table would be like this:
```
Id int PK
ContactId int FK<->Contacts.Id
PhoneNumber nvarchar(22)
Description nvarchar(100)
```
However, it would make things a lot easier AND save a SQL Join on retrieval if I just stored this information as part of each contact's record (assuming that I limit the total # of phone numbers that can be stored, to say 4 numbers total).
However, I end up with an "ugly" structure like this:
```
PhoneNumber1 nvarchar(22)
Description1 nvarchar(100)
PhoneNumber2 nvarchar(22)
Description2 nvarchar(100)
```
etc. etc.
It looks amateurish to me but here are the advantages I see:
1) In ASP.NET MVC I can simply attach the input textboxes to my LINQ object's properties and I'm done with wiring up record adds and updates.
2) No SQL Join necessary to retrieve the information.
Unfortunately I am not very knowledgeable on issues such as table width problems (I read that this can cause problems if it grows too big/too many columns and that performance issues come up?) and then also it would mean that when I **search** for a phone number I'd have to look at 4 fields instead of 1 if I kept it in a separate table.
My application has about 80% search/data retrieval activity so search performance is an important factor.
I appreciate your help in finding the right way to do this. Separate table or keep it all in one? Thank you! | It won't likely cause problems to have the data denormalized like that, but I wouldn't suggest it. Even though it may be more complex to query, it's better to have well formed data that you can manipulate in a multitude of ways. I would suggest a database schema like this:
```
Contacts:
ID (Primary Key)
Name
Job Title
Phone Number Categories:
ID (Primary key)
Name
Phone Numbers:
ID (Primary Key)
Category_ID (Foreign Key -> Phone Number Categories.ID)
Contact_ID (Foreign Key -> Contacts.ID)
Phone Number
```
This allows you a lot of flexibility in the number of phone numbers allowed, and gives you the ability to categorize them. | This might be fine now, but what happens when someone wants a fifth phone number? Do you keep on adding more and more fields?
Another thing to consider is how would you run a query to say 'Give me all people and their mobile phone numbers', or 'Give me everyone with no phone number'? With a separate table, this is easy, but with one table the mobile number could be in any one of four fields so it becomes much more complicated.
If you take the normalised approach, and in future you wanted to add additional data about the phone number, you can simply add another column to the phone numbers table, not add 4 columns to the contacts table.
Going back to the first point about adding more phone numbers in future - if you do add more numbers, you will have to amend probably every query/bit of logic/form that works on data to do with phone numbers. | Normalize or Denormalize: Store Contact Details (Phone Numbers) in separate Table? Search Performance? | [
"",
"sql",
"asp.net-mvc",
"linq",
"database-design",
""
] |
can anyone suggest the best way to serialize data (a class actually) to a DB?
I am using SQL server 2008 but i presume i need to serialize the class to a string / or other data type before storing in the database?
I presume that this field needs to be text or binary??
Does SQL server 2008 (or .net 3.5) support serializing directly tothe database ??
Any help really appreciated | You can xml serialize the class into an xml field. We use this all the time for exception logging in an ETL.
Using the XmlSerializer you may want a helper method somewhere which serializes the class to a string...
```
public static string SerializeToXml<T>(T value)
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, value);
return writer.ToString();
}
```
Then just put the string into the db like any other. | The **best** way to store data in a database is in columns (per property), so that it is queryable and indexable. ORM tools will help with this.
However, it *is* also possible to serialize a class as a CLOB/BLOB (`varchar(max)`/`varbinary(max)` etc).
It this is what you want, avoid anything implementation-specific or version-intolerant; so in particular, don't use `BinaryFormatter`. Anything contract-based should work; `XmlSerializer`, `DataContractSerializer`, etc. Or for fast binary, protobuf-net might be worth a look.
But I stress; columns would be better. | Serialize C# class directly to SQL server? | [
"",
"c#",
".net",
"sql-server",
"serialization",
""
] |
Is there any way to access server side asp.net variable in javascript? I want to do something like
```
function setBookmark(val)
{
document.getElementById('<%# hBookmark.ClientID %>').value=val;
}
```
Is it possible in anyway?
**\*Note\***: hBookmark is a server side html hiddent control, I want to use client ID as IDs are changed as the server controls are rendered. | ```
// Use <%=, not <%#
document.getElementById('<%= hBookmark.ClientID %>').value = val;
``` | It's possible to use scriptlets like this...
```
document.getElementById('<%= hBookmark.ClientID %>').value = val;
```
But note that the Javascript can not reside in an external file; it must be in the markup for this to work. | Server variable in javascript | [
"",
"asp.net",
"javascript",
""
] |
```
Class A
{
public:
NullIt()
{
this = NULL;
}
Foo()
{
NullIt();
}
}
A * a = new A;
a->Foo();
assert(a); //should assert here
```
Is there a way to achieve this effect, memory leaks aside? | No. The object knows nothing about the external references to it (in this case, "a"), so it can't change them.
If you want the caller to forget your object, then you can do this:
```
class MyClass
{
void Release(MyClass **ppObject)
{
assert(*pObject == this); // Ensure the pointer passed in points at us
*ppObject = NULL; // Clear the caller's pointer
}
}
MyClass *pA = new A;
pA->Release(&pA);
assert(pA); // This assert will fire, as pA is now NULL
```
When you call Release, you pass in the pointer you hold to the object, and it NULLs it out so that after the call, your pointer is NULL.
(Release() can also "delete this;" so that it destroys itself at the same time) | Exactly what effect are you trying to acheive?
Even if you could assign a new pointer (or `NULL`) to '`this`' (which you can't), it wouldn't affect the pointer '`a`'. | Can an object instance null out the "this" pointer to itself safely? | [
"",
"c++",
""
] |
I have a program where I need to make 100,000 to 1,000,000 random-access reads to a List-like object in as little time as possible (as in milliseconds) for a cellular automata-like program. I think the update algorithm I'm using is already optimized (keeps track of active cells efficiently, etc). The Lists do need to change size, but that performance is not as important. So I am wondering if the performance from using Arrays instead of ArrayLists is enough to make a difference when dealing with that many reads in such short spans of time. Currently, I'm using ArrayLists.
Edit:
I forgot to mention: I'm just storing integers, so another factor is using the Integer wrapper class (in the case of ArrayLists) versus ints (in the case of arrays). Does anyone know if using ArrayList will actually require 3 pointer look ups (one for the ArrayList, one for the underlying array, and one for the Integer->int) where as the array would only require 1 (array address+offset to the specific int)? Would HotSpot optimize the extra look ups away? How significant are those extra look ups?
Edit2:
Also, I forgot to mention I need to do random access writes as well (writes, not insertions). | Now that you've mentioned that your arrays are actually arrays of primitive types, consider using the collection-of-primitive-type classes in the [Trove](http://trove4j.sourceforge.net/) library.
@viking reports significant (ten-fold!) speedup using Trove in his application - see comments. The flip-side is that Trove collection types are not type compatible with Java's standard collection APIs. So Trove (or similar libraries) won't be the answer in all cases. | Try both, but measure.
Most likely you could hack something together to make the inner loop use arrays without changing all that much code. My suspicion is that HotSpot will already inline the method calls and you will see no performance gain.
Also, try Java 6 update 14 and use -XX:+DoEscapeAnalysis | Java Performance - ArrayLists versus Arrays for lots of fast reads | [
"",
"java",
"performance",
"arrays",
"arraylist",
""
] |
I would like to use reflection to investigate the private fields of an object as well as get the values in those fields but I am having difficult finding the syntax for it.
For example, an object has 6 private fields, my assumption is that I could fetch their FieldInfo with something like
```
myObject.GetType().GetFields(BindingFlags.NonPublic)
```
but no dice - the call returns an array of 0.
Whats the correct syntax to access fields? | ```
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
``` | You've overridden the default flags, so you need to add `Instance` back in...
```
myObject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
``` | How to get instances in all private fields of an object? | [
"",
"c#",
".net",
"reflection",
""
] |
for extracting special folder icons I'm using
```
ExtractIconEx(Environment.SystemDirectory + "\\shell32.dll",ncIconIndex, handlesIconLarge, handlesIconSmall, 1);
```
Here im passing explicitly nIconIndex for special folders like MyDocs,MyPictures ..etc
and its working fine in XP ,however in Vista its not retrieving the correct icons ..there it retrieves yellow folder icons..it should not be the case.
Cn anybody help me on this.. | Vista added a new API called SHGetStockIconInfo but it does not support my documents AFAIK. But that does not matter since the method you SHOULD be using works on both XP and Vista (Your current solution will not work when the user has selected a custom icon, you are just looking in hardcoded system dlls, this could change at any point)
So, what you should do is, get the path or PIDL to the shell folder you are interested in (SHGetFolderPath and friends) and pass that path/PIDL to SHGetFileInfo. SHGetFileInfo can give you a icon handle, or the index into the system image list.
I'm not sure what the .NET equivalent for those functions are, but you should be able to figure that out, or use PInvoke | Check out the [IconLib library at codeproject](http://www.codeproject.com/KB/cs/IconLib.aspx). | Icon Extraction in VIsta | [
"",
"c#",
"windows-vista",
"icons",
""
] |
I am having some trouble hosting a WCF service inside a Windows Service.
I can start my WCF service in VS2008 and by navigating to the base address in my app.config
```
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="WCF.IndexerBehavior"
name="WCF.Indexer">
<endpoint address="" binding="wsHttpBinding" contract="WCF.IIndexer">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/WCFService/Action/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCF.IndexerBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
```
I can see it works fine, I get the page saying I created a service and code samples on how to use it are shown.
Now my next step was to create a Windows Service to host my WCF shown above.
I just used te windows service template, it gave me a Program.cs and Service1.cs which I renamed to WindowsServiceHost.cs. In it I have:
```
private ServiceHost host;
public WindowsServiceHost()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
var serviceType = typeof(Indexer.WCF.Indexer);
host = new ServiceHost(serviceType);
host.Open();
}
catch (Exception ex)
{
}
}
protected override void OnStop()
{
if (host != null)
{
host.Close();
}
}
```
Everything compiles fine, I can run InstallUtil (I defined an installer).
The service used to start and stop immediately but disabling Windows Defender got rid of this.
Now the service starts (As a network service) and stays up (I think), but when I navigate to the base address, I get the not found page.
Another weird thing is when I try to stop the service (which is still displayed as running) I get:
Error 1061: The service cannot accept control messages at this time
I've tried everything but am at a loss. | Not 100% sure what the reason really is - just to confirm, we self-host WCF services in Windows services all the time and it generally works perfectly fine.
Two points you could try - just to get a feeling for the behavior and a potential clue for the problem:
1) I notice you open the ServiceHost with just the type of the service - that works, but you might still want to add a base address even to the call of the `new ServiceHost()` - like this:
```
host = new ServiceHost(serviceType,
new Uri("http://localhost:8181/WCFService/Action/");
```
Can you navigate to that address and get the service page??
2) The other thing I noticed is that your service seems to be called `Indexer.WCF.Indexer` as specified in the typeof() before opening the host, but in the config file, the `name=` on the `<service>` tag is only "WCF.Indexer".
Could you possibly try to change that tag to read:
```
<service behaviorConfiguration="WCF.IndexerBehavior"
name="Indexer.WCF.Indexer">
```
Does that help? Are you now able to see the service page when navigating to it in the browser?
Marc | Self-hosting HTTP in a Windows service may require registering the endpoint with HttpCfg.exe. Take a look [here](http://msdn.microsoft.com/en-us/library/ms733768.aspx "here"). | Hosting a WCF service inside a Windows Service | [
"",
"c#",
".net",
"wcf",
""
] |
I want to return an Interface and inside a switch statement I would like to set it. Is this a bad design?
```
private IResultEntity GetEntity(char? someType)
{
IResultEntity entity = null;
switch (someType)
{
case 'L': //life
entity = new LifeEntity();
break;
case 'P': //property
entity = new PropertyEntity();
break;
case 'D': //disability
entity = new DisabilityEntity();
break;
case 'C': //credit card
entity = new CreditCardEntity();
break;
}
return entity;
}
``` | I don't usually mind switch statements in a factory, provided I can group and control all of the derived classes that I want my factory to create in advance.
Sometimes,maybe a user-created plugin might want to add it's own classes to that switch list, and then a swich statement is not enough.
I found this good [source for some more info](https://web.archive.org/web/20140414013728/http://tranxcoder.wordpress.com/2008/07/11/a-generic-factory-in-c) on creating some more powerfull/versatile factory classes
A good middle-ground approach I usually take is to keep a static Dictionary< string,Type > for each factory class.
People can just "register" their own implementations using some sort of
```
Factories.TypeRegistration.StaticDictionary.Add("somekey",typeof(MyDerivedClass))
```
(or better yet, use a Registration method and hide the StaticDictionary)
then the Factory has an easy task of creating an instance by performing a lookup in the table:
```
Activator.CreateInstance(Factories.TypeRegistration.StaticDictionary["somekey"]);
``` | I dont know, which possibilities you have in c#, but it is still better to have one switch in a factory method than having switches all over the place. In a factory method, a switch is tolerable -- but better have it well documented. | Is a switch statement applicable in a factory method? c# | [
"",
"c#",
"design-patterns",
"interface",
"factory-method",
""
] |
We allocate memory in C using malloc and in C++ using new. I know that memory allocated must
be freed or given back to OS using free in C and delete in C++.
If I forgot to use free/delete after allocating memory, it means there will be memory leak.
Now, my question is, is this memory leak only during the time period of execution of program; or is it permanent leak/loss or is it gained again once I restart the system ? What is the internal process actually ? What does memory leak/loss mean exactly?
I would be very grateful if someone could explain this in detail or provide me with some nice references.
UPDATE 1
After reading some answers, I learnt that memory is given back to OS/system after program terminates, if that is so, why everyone needs to care so much about memory leak, and why preventing memory leak is very important ?
UPDATE 2
So, memory leak should be prevented so that the system doesn't crash due to lack of sufficient memory for allocation purposes ??
UPDATE 3
So, after reading all answers, I realized that memory leak is quiet important issues to prevent system crashes. But, for a beginner like me, how can I be sure if my program is completely free from memory leak. I try to do free,delete if I am using malloc,new but sometimes, it gets messy. Is there any tool or method which I can use to know if my program is doing any memory leak ?
UPDATE 4
After reading answers, I have now understood the importance of memory leak free code, less use of new/delete, more use of STL, learnt new stuffs like RAII,valgrind and good programming practices.
Thanks to all :) | It's *per-process*. Once your process exits, the allocated memory is returned to the OS for use by other processes (new or existing).
To answer your edited question, there's only a finite amount of memory in your machine. So if you have a memory leak, then the major problem is that the memory isn't available for *other* processes to use. A secondary, but not negligible, effect is that your process image grows, you'll swap to disc and performance will be hit. Finally your program will exhaust all the memory in the system and fail, since it's unable to allocate any memory for itself.
It's arguable that for a small process with a short lifetime, memory leaks are tolerable, since the leaked memory will be small in quantity and short-lived.
Take a look at [this resource](http://www.memorymanagement.org/), for possibly more info than you'll ever need. What we're discussing here is *dynamic* or *heap* allocation. | A memory leak simply means that *your application* fails to release memory it has allocated. Once your program ends, it is up to the OS what happens. Every modern OS will reclaim all memory used by the application, so once your process terminates, it'll get cleaned up.
But C/C++ do not *guarantee* that the OS does that. It is possible on some platforms that the memory stays lost until you reboot.
So the problem with memory leaks is twofold:
* one a few platforms the system might have to reboot to reclaim the memory. On most platforms this is a non-isssue, although leaking some other resource types may still cause problems.
* As long as your program is running, it will allocate memory it never frees, which means it'll use more and more memory. If your program is intended to run for a long time, it may end up using all the available memory on the machine, and subsequently crash.
Many short-running programs actually ignore memory leaks *because* they know it'll get cleaned up by the OS soon enough. Microsoft's C++ compiler does this, as far as I know. They know that once the compiler is invoked, it runs for a couple of minutes at the most. (and they know it runs on Windows, where the OS *does* reclaim memory once the process terminates) So it's ok that it leaks some memory here and there.
As for how to avoid memory leaks, don't create them.
You risk leaking memory every time you use new/delete, so *don't*.
When you need an array of data do this:
```
std::vector<char> vec(200);
```
instead of this:
```
char* arr = new char[200];
```
The former is just as efficient, but you don't have to explicitly call delete to free it `std::vector` uses RAII to manage its resources internally. And you should do the same -- either by using ready-made RAII classes like `vector`, `shared_ptr`, or almost any other class in the standard library or in Boost, or by writing your own.
As a general rule of thumb, your code should not contain any new/delete calls, *except* in the constructor/destructor for the class responsible for managing that allocation.
If an object allocates the memory it needs in the constructor, and releases it in the destructor (and handles copying/assignment correctly), then you can simply create a local instance of the class on the stack whenever you need it, and it will not, can not, leak memory.
The key to not leaking memory in C++ is to not call new/delete. | Memory leak in C,C++; forgot to do free,delete | [
"",
"c++",
"c",
""
] |
I am wrapping the patterns & practices Enterprise Library Logging Application Block for an application written in .NET.
I want to be able to subclass a logger (i.e to provide domain specific logging).
What is the best way to do this?
For e.g, I have a static Logger class at the moment, but this does not allow me to specialize it for domain specific logging.
For example,
`Log(MyDomainObj obj, string msg)` | Check out [NLog](http://www.nlog-project.org/). They use this sort of pattern:
```
private static Logger myDomainLogger = LogManager.GetCurrentClassLogger();
```
You can then specialize the output based on the class that `myDomainLogger` belongs to.
More detail:
```
class MyDomain
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private void SomeFunc()
{
_logger.Trace("this is a test");
}
}
```
Then in your output you can have it output "MyDomain.SomeFunc" as part of the "this is a test" message. | Also, checkout [log4net](http://logging.apache.org/log4net/index.html). I never found the EL's logging to be as flexible as log4net. I chose log4net since I was already familiar with using log4j.
```
protected readonly log4net.ILog LOG = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
```
Doing it this way, I can get logs like this:
> 2009-07-15 09:48:51,674 [4420] DEBUG
> SampleNamespace.SampleClass [(null)] -
> Sample message you want to output | Singleton logger, static logger, factory logger... how to log? | [
"",
"c#",
"logging",
""
] |
Here's an example:
If I have these classes
```
class Author(models.Model):
name = models.CharField(max_length=45)
class Book(models.Model):
name = models.CharField(max_length=45)
authors = models.ManyToManyField(Author)
```
In the database I have one Author with the name "George" and another one with the name "Georfe". The last one is a mistake. So what I want is in every Book that have "Georfe" as one of his Author replace it by the Author "George".
In SQL is really easy to do. If id of "George" = 3 and id of "Georfe" = 7 and the relation table name is "author\_book":
```
UPDATE author_book SET id=3 WHERE id=7;
```
Is it possible to do that with the Django ORM?
I found a way to do it: I loop trough all the related Books of the mistyped author and do:
```
book.authors.add(Author.objects.get(id=3))
book.authors.remove(Author.objects.get(id=7))
```
But I don't find this solution really elegant and efficient. Is there a solution without the loop? | **Note:** This code will *delete* the bad 'georfe' author, as well as updating the books to point to the correct author. If you don't want to do that, then use `.remove()` as @jcdyer's answer mentions.
Can you do something like this?
```
george_author = Author.objects.get(name="George")
for book in Book.objects.filter(authors__name="Georfe"):
book.authors.add(george_author.id)
book.authors.filter(name="Georfe").delete()
```
I suspect that this would be easier if you had an explicit table joining the two models (with the "through" keyword arg) -- in that case, you would have access to the relationship table directly, and could just do a `.update(id=george_author.id)` on it. | With the auto-generated through table, you can do a two-step insert and delete, which is nice for readability.
```
george = Author.objects.get(name='George')
georfe = Author.objects.get(name='Georfe')
book.authors.add(george)
book.authors.remove(georfe)
assert george in book.authors
```
If you have an explicitly defined through table (authors = models.ManyToManyField(Author, through=BookAuthors) then you can change the relationship explicitly on BookAuthor. A little known fact is that this Model already exists, it is generated by django automatically. Usually you should only create an explicit through model if you have extra data you wish to store (for instance the chapters a particular author wrote, in a multi-author book).
```
# This line is only needed without a custom through model.
BookAuthor = Book.authors.through
book_author = BookAuthor.objects.get(author=georfe, book=great_american_novel)
book_author.author = george
book_author.save()
assert george in book.authors
``` | How to update manytomany field in Django? | [
"",
"python",
"django",
""
] |
On Linux I am used to using `mkpasswd` to generate random passwords to use, on OS X however I don't have this command. Instead of sshing in to my vps every time, I wanted to re implement it using Java. What I have done is pick at random 4 lower case letters, 2 upper case letters, 2 symbols (/ . , etc) and 2 numbers. Then I create a vector and shuffle that too.
Do you think this is good enough randomization? | yes, it is. If you are using [java.util.Random](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html):
> An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)
>
> The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.
**EDIT**
in response to a comment:
```
/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
*/
public Random() {
this(++seedUniquifier + System.nanoTime());
}
private static volatile long seedUniquifier = 8682522807148012L;
``` | If you use [java.security.SecureRandom](http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html) instead of java.util.Random then it's probably secure. SecureRandom provides a "cryptographically strong pseudo-random number generator (PRNG)". I.e. it ensures that the seed cannot easily be guessed and that the numbers generated have high entropy. | Reimplementing mkpasswd | [
"",
"java",
"linux",
""
] |
I have some basic code to determine errors in my MVC application. Currently in my project I have a controller called `Error` with action methods `HTTPError404()`, `HTTPError500()`, and `General()`. They all accept a string parameter `error`. Using or modifying the code below.
What is the best/proper way to pass the data to the Error controller for processing? I would like to have a solution as robust as possible.
```
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
switch (httpException.GetHttpCode())
{
case 404:
// page not found
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// server error
routeData.Values.Add("action", "HttpError500");
break;
default:
routeData.Values.Add("action", "General");
break;
}
routeData.Values.Add("error", exception);
// clear error on server
Server.ClearError();
// at this point how to properly pass route data to error controller?
}
}
``` | Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:
```
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
string action;
switch (httpException.GetHttpCode()) {
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}
```
Then your controller will receive whatever you want:
```
// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
return View("SomeView", message);
}
```
There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems. | To answer the initial question "how to properly pass routedata to error controller?":
```
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
```
Then in your ErrorController class, implement a function like this:
```
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Error(Exception exception)
{
return View("Error", exception);
}
```
This pushes the exception into the View. The view page should be declared as follows:
```
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Exception>" %>
```
And the code to display the error:
```
<% if(Model != null) { %> <p><b>Detailed error:</b><br /> <span class="error"><%= Helpers.General.GetErrorMessage((Exception)Model, false) %></span></p> <% } %>
```
Here is the function that gathers the all exception messages from the exception tree:
```
public static string GetErrorMessage(Exception ex, bool includeStackTrace)
{
StringBuilder msg = new StringBuilder();
BuildErrorMessage(ex, ref msg);
if (includeStackTrace)
{
msg.Append("\n");
msg.Append(ex.StackTrace);
}
return msg.ToString();
}
private static void BuildErrorMessage(Exception ex, ref StringBuilder msg)
{
if (ex != null)
{
msg.Append(ex.Message);
msg.Append("\n");
if (ex.InnerException != null)
{
BuildErrorMessage(ex.InnerException, ref msg);
}
}
}
``` | ASP.NET MVC Custom Error Handling Application_Error Global.asax? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"error-handling",
"user-experience",
""
] |
I have used .Net 3.5 and VS 2008 for more than a month. Like most .Net developers, I have evolved from years experience in .Net 1.0 & 2.0 and VS 2005. Just recently, I discovered the simplicity and power of LINQ and Lambda Expressions, as in my recent questions such as [Find an item in list by LINQ](https://stackoverflow.com/questions/1175645/find-an-item-in-list-by-linq), [Convert or map a class instance to a list of another one by using Lambda or LINQ](https://stackoverflow.com/questions/1176038/convert-or-map-a-class-instance-to-a-list-of-another-one-by-using-lambda-or-linq), and [Convert or map a list of class to another list of class by using Lambda or LINQ](https://stackoverflow.com/questions/1178891/convert-or-map-a-list-of-class-to-another-list-of-class-by-using-lambda-or-linq).
I admit that Lambda and LINQ are much simpler and easy to read and they seem very powerful. Behind the scenes, the .Net compiler must generate lots of code to achieve those functions. Therefore I am little bit hesitant to switch to the new syntax since I already know the "old" way to achieve the same results.
My question is the about the efficiency and performance of Lambda and LINQ. Maybe Lambda expressions are mostly in-line functions, in that case I guess Lambda should be okay. How about LINQ?
Let's limit the discussion to LINQ-to-Objects LINQ-to-SQL (LINQ-to-SQL). Any comments, comparison and experiences? | There's no one single answer that will suffice here.
LINQ has many uses, and many implementations, and thus many implications to the efficiency of your code.
As with every piece of technology at our fingertips, LINQ can and will be abused and misused alike, and the ability to distinguish between that, and proper usage, is only dependent on one thing: knowledge.
So the best advice I can give you is to go and read up on how LINQ is really implemented.
Things you should check into are:
* LINQ and how it uses the methods and extension methods on existing collection types
+ [How LINQ Works](http://aabs.wordpress.com/2006/12/15/how-linq-works-%E2%80%93-creating-queries/)
+ [How LINQ works internally (Stack Overflow)](https://stackoverflow.com/questions/671235/how-linq-works-internally)
+ [How does coding with LINQ work? What happens behind the scenes?](https://stackoverflow.com/questions/835569/how-does-coding-with-linq-work-what-happens-behind-the-scenes)
* How LINQ-to-objects and LINQ-to-SQL differs
+ [What is the difference between LINQ query expressions and extension methods (Stack Overflow)](https://stackoverflow.com/questions/796246/what-is-the-difference-between-linq-query-expressions-and-extension-methods)
* Alternatives to the new LINQ syntax, for instance, the usage of the .Where(...) extension method for collections
And as always, when looking at efficiency questions, the only safe approach is just to measure. Create a piece of code using LINQ that does a single, know, thing, and create an alternative, then measure both, and try to improve. Guessing and assuming will only lead to bad results. | Technically the fastest way is to control all the minutia yourself. [Here are some performance tests](http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html). Notice that the foreach keyword and the ForEach LINQ construct are identically far far slower than just using for and writing procedural code.
However, the compiler can and will be improved and you can always profile your code and optimize any problematic areas. It is generally recommended to use the more expressive features that make code easier to read unless you really need the extra nanoseconds. | What is the Efficiency and Performance of LINQ and Lambda Expression in .Net? | [
"",
"c#",
".net",
"linq",
".net-3.5",
"lambda",
""
] |
Lets just say you have a simple operation that runs on a background thread. You want to provide a way to cancel this operation so you create a boolean flag that you set to true from the click event handler of a cancel button.
```
private bool _cancelled;
private void CancelButton_Click(Object sender ClickEventArgs e)
{
_cancelled = true;
}
```
Now you're setting the cancel flag from the GUI thread, but you're reading it from the background thread. Do you need to lock before accessing the bool?
Would you need to do this (and obviously lock in the button click event handler too):
```
while(operationNotComplete)
{
// Do complex operation
lock(_lockObject)
{
if(_cancelled)
{
break;
}
}
}
```
Or is it acceptable to do this (with no lock):
```
while(!_cancelled & operationNotComplete)
{
// Do complex operation
}
```
Or what about marking the \_cancelled variable as volatile. Is that necessary?
[I know there is the BackgroundWorker class with it's inbuilt CancelAsync() method, but I'm interested in the semantics and use of locking and threaded variable access here, not the specific implementation, the code is just an example.]
There seems to be two theories.
1) Because it is a simple inbuilt type (and access to inbuilt types is atomic in .net) and because we are only writing to it in one place and only reading on the background thread there is no need to lock or mark as volatile.
2) You should mark it as volatile because if you don't the compiler may optimise out the read in the while loop because it thinks nothing it capable of modifying the value.
Which is the correct technique? (And why?)
[Edit: There seem to be two clearly defined and opposing schools of thought on this. I am looking for a definitive answer on this so please if possible post your reasons and cite your sources along with your answer.] | Firstly, threading is tricky ;-p
Yes, despite all the rumours to the contrary, it **is** required to *either* use `lock` *or* `volatile` (but not both) when accessing a `bool` from multiple threads.
For simple types and access such as an exit flag (`bool`), then `volatile` is sufficient - this ensures that threads don't cache the value in their registers (meaning: one of the threads never sees updates).
For larger values (where atomicity is an issue), or where you want to synchronize a *sequence* of operations (a typical example being "if not exists and add" dictionary access), a `lock` is more versatile. This acts as a memory-barrier, so still gives you the thread safety, but provides other features such as pulse/wait. Note that you shouldn't use a `lock` on a value-type or a `string`; nor `Type` or `this`; the best option is to have your own locking object as a field (`readonly object syncLock = new object();`) and lock on this.
For an example of how badly it breaks (i.e. looping forever) if you don't synchronize - [see here](https://stackoverflow.com/questions/458173/can-a-c-thread-really-cache-a-value-and-ignore-changes-to-that-value-on-other-th/458193#458193).
To span multiple programs, an OS primitive like a `Mutex` or `*ResetEvent` may also be useful, but this is overkill for a single exe. | `_cancelled` must be `volatile`. (if you don't choose to lock)
If one thread changes the value of `_cancelled`, other threads might not see the updated result.
Also, I think the read/write operations of `_cancelled` are *atomic*:
> Section 12.6.6 of the CLI spec states:
> "A conforming CLI shall guarantee that
> read and write access to properly
> aligned memory locations no larger
> than the native word size is atomic
> when all the write accesses to a
> location are the same size." | Do I need to lock or mark as volatile when accessing a simple boolean flag in C#? | [
"",
"c#",
".net",
"multithreading",
"locking",
"thread-safety",
""
] |
From program a.exe located in c:/dir I need to open text file c:/dir/text.txt. I don't know where a.exe could be located, but text.txt will always be in the same path. How to get the name of the currently executing assembly from within to program itself so that i can access the text file?
**EDIT**:
what if a.exe is a Windows service? It doesn't have Application as it is not a Windows Applicaion. | I usually access the directory that contains my application's .exe with:
```
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
``` | ```
string exePath = Application.ExecutablePath;
string startupPath = Application.StartupPath;
```
EDIT -
Without using application object:
```
string path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
```
See here for more info:
<http://msdn.microsoft.com/en-us/library/aa457089.aspx> | What is the best way to get the executing exe's path in .NET? | [
"",
"c#",
".net",
"filesystems",
""
] |
I need to serialize a report design. This is the scenario:
The app has base reports, let's say "Sales Report" with a set of pre-defined columns and design, like the corp. logo in the header. The users needs to have the ability to change that layout adding, for example, a footer with the office address, or page numbers. For doing that they need to edit the report, enter the designer and add/change what they need. This changed report layout needs to be serialized to be stored in the database for that user, so the next time, the user opens that report, using that design.
Makes sense? | Here's a simplified version of how I do this:
```
XtraReport customReport;
customReport = new MyXtraReport();
byte[] layout = LoadCustomLayoutFromDB();
if (layout != null) {
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(layout)) {
customReport.LoadLayout(memoryStream);
}
}
using (XRDesignFormEx designer = new XRDesignFormEx()) {
MySaveCommandHandler customCommands = new MySaveCommandHandler(designer.DesignPanel);
designer.DesignPanel.AddCommandHandler(customCommands);
designer.OpenReport(customReport);
designer.ShowDialog(this);
if (customCommands.ChangesSaved)
SaveCustomLayoutToDB(customCommands.Layout);
}
```
Inside MySaveCommandHandler class:
```
public virtual void HandleCommand(ReportCommand command, object[] args, ref bool handled) {
if (command != ReportCommand.SaveFileAs && command != ReportCommand.SaveFileAs)
return;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) {
panel.Report.SaveLayout(memoryStream);
this.layout = memoryStream.ToArray();
changesSaved = true;
}
panel.ReportState = ReportState.Saved;
handled = true;
}
``` | I think what you are looking for is the SaveLayout method:
**Saving the report**
```
YourReport report = new YourReport();
// Save the layout to a file.
report.SaveLayout(@"C:\YourReport.repx");
```
**Loading the report**
```
YourReport report = new YourReport();
// Load the layout
report.LoadLayout(@"C:\YourReport.repx");
```
**Edit:**
here a [link](http://www.devexpress.com/Support/Center/e/E1279.aspx) to the devexpress support site explaining how to save the report definition. | How can I serialize a DevExpress XtraReport report design | [
"",
"c#",
".net",
"devexpress",
"reporting",
"xtrareport",
""
] |
I've switched from LINQ to SQL to ADO.NET (with MSSQL) because of [a problem I described earlier](https://stackoverflow.com/questions/1172329/linq-to-sql-filtering-results-in-a-datagridview), but I also ran into a weird problem using ADO.NET.
I import data from an excel worksheet using excel interop and I place its contents to the database. I trim everything that gets inserted, so this is not (supposed to be) the source of the problem.
When I view the contents of the table using DataGridView, what I see is that every cell has got loads of whitespaces after the text they contain. Screenshot below.
[alt text http://shadow.crysis.hu/so\_adonet\_whitespaces.png](http://shadow.crysis.hu/so_adonet_whitespaces.png)
I used Google to find a solution, but the only usable result I found was to
```
SET ANSI_PADDING OFF
GO
```
I did it (so I set ANSI\_PADDING OFF before I began to import and set it back ON when I was done), but nothing changed. Oh, I'm using NCHAR(255) as field type.
If I trim the contents I display in the datagridview, it's fine, but if possible, I'd like to avoid this overhead (after all, I have to loop over ALL the rows and columns displayed, and since I'm working with a lot of data - a few thousand rows - it's not the best solution). What should I do?
Thank you very much in advance! | You're using an `nchar(255)`, which is a static length of 255. Try changing the column to `nvarchar(255)`.
An `nchar(255)` will always give you 255 characters. Those that aren't used are filled in by whitespace (0x20 in ASCII aka a space). `nvarchar(255)` will allocate 255 characters when initialized, but only use the characters necessary.
In this case, you want `nvarchar(255)`, since you have a variable-length string. | Try NVARCHAR instead of NCHAR. | ADO.NET Whitespace padding problem | [
"",
"c#",
"sql-server",
"ado.net",
""
] |
Weird behaviour, I'm sure it's me screwing up, but I'd like to get to the bottom of what's happening:
I am running the following code to create a very simple graph window using matplotlib:
```
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot((1, 3, 1))
[<matplotlib.lines.Line2D object at 0x0290B750>]
>>> plt.show()
```
and as expected I get the chart one would expect, in a new window that has popped up, containing a very simple blue line going from 1 to 3 back to 1 again on y axis, with 0, 1, 2 as the x axis points (just as example). Now I close the graph window (using cross button in the top right under windows). This gives me control to the interpreter, and I start again, creating new objects:
```
>>>
>>> fig1 = plt.figure()
>>> bx = fig1.add_subplot(111)
>>> bx.plot((1, 3, 1))
[<matplotlib.lines.Line2D object at 0x029E8210>]
>>> plt.show()
```
This time though, I get a window frame, with nothing in it (just the frame, no white background nothing), and the whole bang shoot hangs. I have to "end task", the python interpreter is terminated by the system and I get a command prompt back. Similar behaviour on a mac (except it does actually plot the graph first, before also hanging).
So somehow Python and/or matplotlib doesn't want me to close the window manually. Anybody know what's going on and what I should be doing? What I'd like to do is play around with different plots from within the interpreter, and obviously this behaviour doesn't help. I know I could use "Ipython -pylab" but in the interests of learning, I want to understand the above error.
Thanks. | Apparently, this is caused by a bug in the tkinter backend. See, e.g., <https://bugs.launchpad.net/ubuntu/+source/matplotlib/+bug/313834> . It's being worked on...
If you can regress to a slightly older tkinter library, that should be a workaround for the time-being (I ran into this same thing a couple of weeks ago, and that was my only hope). | Three months late to the party, but I found a suggestion in the matlibplot documentation to use draw() rather than show(); the former apparently just does a render of the current plot, while the latter starts up all the interactive tools, which is where the problems seem to start.
It's not terribly prominently placed in the documentation, but here's the link:
<http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show>
For what it's worth, I've tried pylab.show() and had exactly the same issue you did, while pylab.draw() seems to work fine if I just want to see the output. | Python Matplotlib hangs when asked to plot a second chart (after closing first chart window) | [
"",
"python",
"matplotlib",
""
] |
This could sound like a very simple question to many of you, but I seem to be having trouble getting a basic date\_format to work with my mySQL statement and then to be displayed using php. Here is the code that I currently have:
```
$result = mysql_query("SELECT *, DATE_FORMAT('timestamp', '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
```
Then trying to display it using:
```
echo ' Posted: '.$row['timestamp'].'';
```
All I want is to format the date from a PHP myAdmin timestamp to the format I want.
Cheers | Use backticks ( `` `) or nothing at all instead of single-quotes (`'`) around your field in your query:
```
$result = mysql_query("SELECT *, DATE_FORMAT(`timestamp`, '%W %D %M %Y') as date FROM articleDB WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC LIMIT 8");
```
Backticks ( `` `) creates a reference to a table member, single-quotes creates a string (`'`). You were basically trying to`DATE\_FORMAT`the string`'timestamp'` instead of the field.
Also, since you are using `as` to create a field alias, you want to refer to that field using the alias when outputting:
```
echo ' Posted: '.$row['date'];
``` | you need to display the "date" column that you calculate/format in the select statement, the timestamp column contains the unformatted original date value.
```
echo ' Posted: '.$row['date'];
``` | Getting mySQL date_format to display in PHP | [
"",
"php",
"mysql",
"date-format",
""
] |
```
Customer cust = new Customer();
```
`Customer` is a class. `cust` is an assigned name. I'm not sure what `Customer()` does...
What does this line do? Why do we need it? Isn't having `Customer` and `Customer()` a bit repetitive? | It declares a Customer and then initializes it.
```
Customer cust; //declares a new variable of Customer type
cust = new Customer(); //Initializes that variable to a new Customer().
```
new creates the actual object, cust hold's a reference to it.
The empty parentheses indicates that the construction of the Customer object is being passed no parameters, otherwise there would be a comma separated list of parameters within the parenthesis. | It creates a new instance of `Customer()` and assigns a reference to the newly created object to the variable `cust`.
If you want to remove the repetition *and* you're using C# 3.0 or later *and* it's a local variable, you can use:
```
var cust = new Customer();
```
That has *exactly* the same meaning - it's still statically typed, i.e. the variable `cust` is still very definitely of type `Customer`.
Now, it *happened* to be repetitive in this case, but the two `Customer` bits are entirely separate. The first is the type of the variable, the second is used to say which constructor to call. They could have been different types:
```
Customer cust = new ValuedCustomer();
IClient cust = new Customer();
object cust = new Customer();
```
etc. It's only because you created an instance of *exactly* the same type as the type of the variable that the repetition occurred. | In C#, what does "Customer cust = new Customer();" do? | [
"",
"c#",
""
] |
I saw a post on this already, but it didn't really provide a solution (that has worked for me at least)...
I have a PHP page that does some basic MySQL queries, the results of which are displayed on the page. I'm using some $\_GET and $\_SESSION variables throughout this process.
In the same page, I also allow the user to "Export to CSV" (by calling a function). The file returned from the export has the CSV results at the bottom, but also contains the HTML of my page (which calls the function).
Now, at the top of the page I have ob\_start() and at the bottom I have ob\_flush(), otherwise on page load I will receive some "Cannot modify header..." errors. So, as suggested in the post that I read:
```
My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated.
You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits."
(http://stackoverflow.com/questions/207019/why-am-i-getting-html-in-my-mysql-export-to-csv/207046)
```
Does anyone have any ideas on how I can prevent this from happening? Let me know if I should post some of my code and I will...
Thanks!
EDIT:
When calling ob\_end\_clean() before I call my export function, it gets rid of any html before the CSV. However, I am still getting some HTML closing tags after the CSV results...
```
fname lname MONTH WeekdayCount WeekendCount
John Doe 8 1 0
John Doe 7 3 2
Jane Smith 7 3 2
</div>
</div>
</div>
</body>
</html>
```
EDIT:
This issue has been solved by calling exit() after calling the CSV export script. | You could try calling ob\_end\_clean() before you output the csv data, and it should throw away any output you have already printed as HTML.
You could call exit() after outputting your csv data in order to stop the rest of you page being printed.
This doesn't seem a particularly good approach, can you not have a separate PHP script to output the csv which doesn't include the headers and footers by default? | Without seeing your script it's hard to say what exactly the problem is other than to say that you can't send HTTP headers to the client after you've sent **ANY** content. This includes white-space. Sometimes you'll have non-printable characters before your opening `<?php` statement as well. If necessary use a hex editor to find these.
The top of your export.php script should look something like:
```
<?php
header('Content-Type: text/csv');
...
```
Is this the case? | PHP Export MySQL to CSV - Results showing HTML | [
"",
"php",
"mysql",
"html",
"csv",
""
] |
I have a lovely little Java client that sends signed email messages. We have an Exchange server that requires username/password authentication to send a message.
When I connect to the exchange server, I get this error:
```
avax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
```
When I connect to other servers (Unix servers), I have no problem.
Below is the full debug trace. I can't figure it out.
```
DEBUG: JavaMail version 1.4.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SM}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], }
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "SERVER", port 25, isSSL false
220 SERVER ESMTP (deca81216f2ecf4fd6fedb030e3dcfd0)
DEBUG SMTP: connected to host "SERVER", port: 25
EHLO CLIENT
250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you
250-STARTTLS
250-PIPELINING
250-SIZE 100000000
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-8BITMIME
250 HELP
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "100000000"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
STARTTLS
220 Ready to start TLS
EHLO CLIENT
250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you
250-PIPELINING
250-SIZE 100000000
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-8BITMIME
250 HELP
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "100000000"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
AUTH LOGIN
334 VXNlcn5hbWU6
RVJOXHNsK2FyZmlu
334 UGFzc3dvcmQ6
UVdFUnF3ZXIxMjM0IUAjJA==
535 Error: authentication failed
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "SERVER", port 25, isSSL false
220 SERVER ESMTP (deca81216f2ecf4fd6fedb030e3dcfd0)
DEBUG SMTP: connected to host "SERVER", port: 25
EHLO CLIENT
250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you
250-STARTTLS
250-PIPELINING
250-SIZE 100000000
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-8BITMIME
250 HELP
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "100000000"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
STARTTLS
220 Ready to start TLS
EHLO CLIENT
250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you
250-PIPELINING
250-SIZE 100000000
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-8BITMIME
250 HELP
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "100000000"
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
AUTH LOGIN
334 VXNlcm5hbWU6
RVJOXHNsZ2FyZmlu
334 UGFzc3dvcmQ6
UVdFUnF3ZXIxMjM0IUAjJA==
535 Error: authentication failed
Error sending mail: failed to connect
javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
at SignMessage.sendSigned(SignMessage.java:248)
at SignMessage.main(SignMessage.java:340
``` | Apparently, MS Exchange SSL connection is not established properly by Java Mail API. It relies on using `SSLSocketFactory` for that, but, if I remember correctly, MS Exchange requires a somewhat mixed approach.
Anyway, I have this piece of code in one of my projects:
```
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class ExchangeSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory sslSocketFactory;
private SocketFactory socketFactory;
public ExchangeSSLSocketFactory() {
try {
socketFactory = SocketFactory.getDefault();
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new EmptyTrustManager() }, null);
sslSocketFactory = (SSLSocketFactory)context.getSocketFactory();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private final class EmptyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] cert, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] cert, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
public static SocketFactory getDefault() {
return new ExchangeSSLSocketFactory();
}
@Override
public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
return sslSocketFactory.createSocket(socket, s, i, flag);
}
@Override
public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException {
return socketFactory.createSocket(inaddr, i, inaddr1, j);
}
@Override
public Socket createSocket(InetAddress inaddr, int i) throws IOException {
return socketFactory.createSocket(inaddr, i);
}
@Override
public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
return socketFactory.createSocket(s, i, inaddr, j);
}
@Override
public Socket createSocket(String s, int i) throws IOException {
return socketFactory.createSocket(s, i);
}
@Override
public Socket createSocket() throws IOException {
return socketFactory.createSocket();
}
@Override
public String[] getDefaultCipherSuites() {
return sslSocketFactory.getSupportedCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return sslSocketFactory.getSupportedCipherSuites();
}
}
```
You tell the Java Mail API to use this socket factory by setting following properties:
* `ssl.SocketFactory.provider`
* `mail.smtp.socketFactory.class`
to full class name of `ExchangeSSLSocketFactory`
From your debug output, it seems that you already have:
* `mail.smtp.starttls.enable` set to true
With all this in place, the problem should be solved. | I had the same issues. Now it works properly. I disabled the antivirus (McAfee) and corrected the user name (I unnecessarily gave the domain whereas it was not required). | Exchange server will not accept username/password provided with javax.mail API | [
"",
"java",
"email",
"exchange-server",
"jakarta-mail",
"smtp-auth",
""
] |
When I use braces around `case` code block in C++ to localize variables should I put `break` inside or outside the block?
```
case FOO: // 'break' inside
{
int i;
doStuff();
break;
}
case BAR: // 'break' outside
{
int i;
doStuff();
}
break;
```
Thanks. | It's a matter of style.
I would put `break` outside the closing brace just to make it more readable. | You put it wherever you like. Make sure you stay consistent throughout the entire project. (Personally, I put it outside.) | where to put break in switch/case statement with blocks | [
"",
"c++",
"syntax",
""
] |
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <http://www.codeplex.com/htmlagilitypack>), but for using with Python.
Anyone knows? | Use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) like everyone does. | Others have recommended BeautifulSoup, but it's much better to use [lxml](http://codespeak.net/lxml/). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
[Ian Blicking agrees](http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/).
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed. | Is there a good html parser like HtmlAgilityPack (.NET) for Python? | [
"",
"python",
"html",
"parsing",
""
] |
in this post [Stack Overflow Architecture](http://highscalability.com/stack-overflow-architecture) i read about something called nosql, i didn't understand what it means, and i tried to search on google but seams that i can't get exactly whats it.
Can anyone explain what nosql means in simple words? | If you've ever worked with a database, you've probably worked with a *relational* database. Examples would be an Access database, SQL Server, or MySQL. When you think about tables in these kinds of databases, you generally think of a grid, like in Excel. You have to name each column of your database table, and you have to specify whether all the values in that column are integers, strings, etc. Finally, when you want to look up information in that table, you have to use a language called SQL.
A new trend is forming around non-relational databases, that is, databases that do not fall into a neat grid. You don't have to specify which things are integers and strings and booleans, etc. These types of databases are more flexible, but they don't use SQL, because they are not structured that way.
Put simply, that is why they are "NoSQL" databases.
The advantage of using a NoSQL database is that you don't have to know exactly what your data will look like ahead of time. Perhaps you have a Contacts table, but you don't know what kind of information you'll want to store about each contact. In a relational database, you need to make columns like "Name" and "Address". If you find out later on that you need a phone number, you have to add a column for that. There's no need for this kind of planning/structuring in a NoSQL database. There are also potential scaling advantages, but that is a bit controversial, so I won't make any claims there.
Disadvantages of NoSQL databases is really the lack of SQL. SQL is simple and ubiquitous. SQL allows you to slice and dice your data easier to get aggregate results, whereas it's a bit more complicated in NoSQL databases (you'll probably use things like MapReduce, for which there is a bit of a learning curve). | From the [NoSQL Homepage](http://www.strozzi.it/cgi-bin/CSA/tw7/I/en_US/nosql/Home%20Page)
> NoSQL is a fast, portable, relational database management system without arbitrary limits, (other than memory and processor speed) that runs under, and interacts with, the UNIX 1 Operating System. It uses the "Operator-Stream Paradigm" described in "Unix Review", March, 1991, page 24, entitled "A 4GL Language". There are a number of "operators" that each perform a unique function on the data. The "stream" is supplied by the UNIX Input/Output redirection mechanism. Therefore each operator processes some data and then passes it along to the next operator via the UNIX pipe function. This is very efficient as UNIX pipes are implemented in memory. NoSQL is compliant with the "Relational Model".
I would also see this answer on [Stackoverflow](https://stackoverflow.com/questions/1145726/what-is-nosql-how-does-it-work-and-what-benefits-does-it-profide/1145751#1145751). | What nosql means? can someone explain it to me in simple words? | [
"",
"sql",
"nosql",
""
] |
I use this code to gathering the information from Wiki:
> <http://en.wikipedia.org/w/api.php?action=query&rvprop=content&prop=revisions&format=json&titles=apple>
And I can get a JSON String like this
```
{
"query": {
"normalized": [{
"from": "apple",
"to": "Apple"
}],
"pages": {
"18978754": {
"pageid": 18978754,
"ns": 0,
"title": "Apple",
"revisions": [{
"*": "Something....."
}]
}
}
}
}
```
I can eval it to JSON, but the problem is, I can get into the query>pages, after that I can't get deeper, it was Because the Wiki API return me as a String 18978754, but it can't get the value by this:
```
jsonObject.query.pages.18978754
```
Some assumption I need to clarify, I don't know the number 18978754. Do I need to get the number first or I can still get "Something..." within knowing the number. | What about using array-syntax :
```
jsonObject.query.pages[18978754]
```
Seems to be working, using firebug :
```
>>> data.query.pages[18978754]
Object pageid=18978754 ns=0 title=Apple revisions=[1]
```
And :
```
>>> data.query.pages[18978754].title
"Apple"
```
Note accessing data-object with an array-syntax is also possible for the other properties ; for instance :
```
>>> data['query'].pages[18978754].title
"Apple"
```
That's perfectly valid JS syntax **:-)**
---
**Added after seing the comment / edit**
If you don't know the ids of the pages, you can iterate over the pages, with something like this :
```
for (var pageId in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageId)) {
console.log(data.query.pages[pageId].title);
}
}
```
Note that I'm using [`hasOwnProperty`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty) to be sure the object I'm on has the property, and that it's not coming from any kind of inheritance or anything like that :
> Every object descended from Object
> inherits the hasOwnProperty method.
> This method can be used to determine
> whether an object has the specified
> property as a direct property of that
> object; unlike the in operator, this
> method does not check down the
> object's prototype chain.
Depending on what's in "`revision`", you might have to do the same on that one too, btw...
Hope this helps better **:-)**
---
**Second edit, after second set of comments :**
Well, going a bit farther (didn't think you meant it literally) :
```
data.query.pages[pageId].revisions
```
is an array (note the `[]` symbols) that seems to be able to contain several objects.
so, you can get the first one of those this way :
```
data.query.pages[pageId].revisions[0]
```
The second one this way :
```
data.query.pages[pageId].revisions[1]
```
*(there is no second one in the example you provided, btw -- so this is in theory ^^ )*
And so on.
To get everyone of those objects, you'd have to do some kind of loop, like this :
```
var num_revisions = data.query.pages[pageId].revisions.length;
var i;
for (i=0 ; i<num_revisions ; i++) {
console.log(data.query.pages[pageId].revisions[i]);
}
```
And now, inside that loop, you should be able to get the '\*' property of the given object :
```
data.query.pages[pageId].revisions[i]['*']
```
So, the final code becomes :
```
for (var pageId in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageId)) {
var num_revisions = data.query.pages[pageId].revisions.length;
var i;
for (i=0 ; i<num_revisions ; i++) {
console.log(data.query.pages[pageId].revisions[i]['*']);
}
}
}
```
Using this code in firebug, I now get the literral sting you're looking for :
```
Something.....
```
Of course, you could probably just use :
```
for (var pageId in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageId)) {
console.log(data.query.pages[pageId].revisions[0]['*']);
}
}
```
Which will work fine if you always want to deal with only the first element of the `revisions` array.
Just beware : in your example, there was only one revision ; the code I provided should be able to deal with many ; up to you to determine what you want to do with those ;-) | Late but maybe helpful for someone else.
When you add `&indexpageids` to your request you will get the `pageids`. More information [here](http://de.wikipedia.org/w/api.php?action=query&titles=Apple&prop=info&indexpageids&format=jsonfm). | Using Wiki API by format JSON can't get the content | [
"",
"javascript",
"json",
"api",
"mediawiki",
""
] |
I've found <http://lesscss.org/> so interesting! It is a good way to improve reuse of elements in css, but I don't know how to integrate it with Visual Studio 2008. (it would fit nicely with asp.net MVC, for sure)
Do you have any idea for what I need to do in order to **recognize** and **compile** .less files inside VS? | Integration beyond simply being able to invoke an external command line based tool would be a significant task. For simple integration consider using the [following guide](http://msdn.microsoft.com/en-us/magazine/cc163589.aspx) to write a task which invokes the lessc compiler on the file.
Integration at the intellisense level is a massive undertaking for someone not deeply experienced with both the css/less syntax and the visual studio api. | <http://nlesscss.codeplex.com/> - My attempt at playing around with Less for .NET.
EDIT: We now have a new home for the [.NET Less Css Port - www.dotlesscss.com](http://www.dotlesscss.com), enjoy. | How to use a ruby compiler inside VS08 (for LESS CSS)? | [
"",
"c#",
"visual-studio-2008",
"rubygems",
""
] |
I am new to Javascript and trying to extract some text stored in an object.
The object is defined as an object literal and is passed to a function in a [Javascript script](http://query.yahooapis.com/v1/public/yql?q=select%20title%2Cabstract%20from%20search.web%20where%20query%3D%22pizza%22%20LIMIT%202&format=json&callback=foo) that calls the function. The script (and object) have this structure:
```
foo({
"query": {
"count": "2",
"created": "2009-07-25T08:17:54Z",
"lang": "en-US",
},
"results": {
"result": [
{
"abstract": "<b>Pizza</b> Hut®. Order Online for Delivery or Carry-out. Fast & Easy.",
"title": "<b>Pizza</b> Hut"
},
{
"abstract": "Official site of Domino's <b>Pizza</b> delivery chain, which offers thin crust, deep dish, and hand tossed <b>pizzas</b> with a variety of side items and beverages. Site <b>...</b>",
"title": "Domino's <b>Pizza</b>"
}
]
}
}
});
```
The object is passed to to a callback function named "foo":
```
function foo(o){
var out = document.getElementById('container');
out.innerHTML = o.query.count;
}
```
**My Problem:** I know how to print out the query count variable using the callback function above, but I don't know how to print out the the title of the first result in the results array.
How can I change the callback function to display the first result title?
And also, is there a foreach statement, where I could print out all the titles from all the results?
Thanks!
UPDATE: JSBIN for this code is at: <http://jsbin.com/ejiwa/edit> | Does the following work:
```
o.results.result[0].title
```
to get the first result title? And to iterate over all results:
```
for (var i=0; i<o.results.result.length; i++) {
var result = o.results.result[i];
alert(result.title);
}
```
EDIT: Are you sure you copied it right? Here's what I get in Rhino:
```
js> o = {
"query": {
"count": "2",
"created": "2009-07-25T08:17:54Z",
"lang": "en-US",
},
"results": {
"result": [
{
"abstract": "<b>Pizza</b> Hutr. Order Online for Delivery or Carry-out. Fast & Easy.",
"title": "<b>Pizza</b> Hut"
},
{
"abstract": "Official site of Domino's <b>Pizza</b> delivery chain, which offers thin crust, deep dish, and hand tossed <b>pizzas</b> with a variety of side items and beverages. Site <b>...</b>",
"title": "Domino's <b>Pizza</b>"
}
]
}
}
js> o.results.result[0].title
<b>Pizza</b> Hut
``` | As you can see from the JSON, the object has a property called "results" which contains a property called "result" which is an array of objects.
To display the first of that, you simply do as you already did with count, but just follow the structure to the title instead.
```
o.query.results.result[0].title
```
To loop over each result, you can simply loop over the result property like an array, for example like this:
```
var results = o.query.results.result;
for(var i = 0; i < results.length; i++) {
}
```
JSON is simply JavaScript code. Think of the JSON snippet as a JavaScript object declaration and you should have no problems understanding it. | How to process an object literal? | [
"",
"javascript",
"json",
"yql",
""
] |
I'm learning C++ and developing a project to practice, but now i want to turn a variable(String) in code, like this, the user have a file that contains C++ code, but i want that my program reads that file and insert it into the code, like this:
```
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha.find("code") != string::npos)
{
size_t idx = linha.find("\""); //find the first quote on the line
while ( idx != string::npos ) {
size_t idx_end = linha.find("\"",idx+1); //end of quote
string quotes;
quotes.assign(linha,idx,idx_end-idx+1);
// do not print the start and end " strings
cout << quotes.substr(1,quotes.length()-2) << endl;
//check for another quote on the same line
idx = linha.find("\"",idx_end+1);
}
}
}
return 0;
}
```
And here is a file exmaple:
```
code "time_t seconds;\n seconds = time (NULL);\n cout << seconds/3600;"
```
But when i run the program it don't covert the string into code, but it prints exactly what is in the quotes.
Thanks! | You're doing cout right? So obviously it gets displayed.
Maybe what you are trying to do is some code injection in a running process like this <http://www.codeproject.com/KB/DLL/code_injection.aspx> | C++ is a compiled language, not an interpreted language.
So, it is not possible for a program to read C++ code on-the-fly and execute it, since this code requires to be compiled. | Convert a String in C++ Code | [
"",
"c++",
"string",
""
] |
With this code I can get the title out of the following XML file:
```
var xml = XElement.Load (@"C:\\test\\smartForm-customersMain.xml");
string title = xml.Element("title").Value;
```
But how do I make it more exact, e.g. "get the *first element after the smartForm element*, e.g. something like this:
```
//PSEUDO-CODE:
string title = xml.Element("smartForm").FirstChild("title");
```
The XML:
```
<?xml version="1.0" encoding="utf-8" ?>
<smartForm idCode="customersMain">
<title>Customers Main222</title>
<description>Generic customer form.</description>
<area idCode="generalData" title="General Data">
<column>
<group>
<field idCode="anrede">
<label>Anrede</label>
</field>
<field idCode="firstName">
<label>First Name</label>
</field>
<field idCode="lastName">
<label>Last Name</label>
</field>
</group>
</column>
</area>
<area idCode="address" title="Address">
<column>
<group>
<field idCode="street">
<label>Street</label>
</field>
<field idCode="location">
<label>Location</label>
</field>
<field idCode="zipCode">
<label>Zip Code</label>
</field>
</group>
</column>
</area>
</smartForm>
``` | You want to use the `Descendants` axis method and then call the `FirstOrDefault` extension method to get the first element.
Here is a simple example:
```
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
String xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<smartForm idCode=""customersMain"">
<title>Customers Main222</title>
<description>Generic customer form.</description>
<area idCode=""generalData"" title=""General Data"">
<column>
<group>
<field idCode=""anrede"">
<label>Anrede</label>
</field>
<field idCode=""firstName"">
<label>First Name</label>
</field>
<field idCode=""lastName"">
<label>Last Name</label>
</field>
</group>
</column>
</area>
<area idCode=""address"" title=""Address"">
<column>
<group>
<field idCode=""street"">
<label>Street</label>
</field>
<field idCode=""location"">
<label>Location</label>
</field>
<field idCode=""zipCode"">
<label>Zip Code</label>
</field>
</group>
</column>
</area>
</smartForm>";
XElement element = XElement.Parse(xml)
.Descendants()
.FirstOrDefault();
}
}
``` | To add slightly to Andrew's answer if you do not know whether `smartForm` is the root element but still want the title text of the first such entry you would use:
```
xml.DescendantsAndSelf("smartForm").Descendants("title").First().Value;
```
This *requires* that there be a smartForm element with a title element somewhere within it.
If you wanted to ensure that the title element was an *immediate child* in `smartForm` you could use:
```
xml.DescendantsAndSelf("smartForm").Elements("title").First().Value;
```
If you didn't care what the name of `title` was and just wanted the first sub element then you would use:
```
xml.DescendantsAndSelf("smartForm").Elements().First().Value;
``` | How can I get the first element after an element with LINQ-to-XML? | [
"",
"c#",
"linq",
"linq-to-xml",
""
] |
It is probably very simple but I can't find it.
I want to make a .htaccess file so no one can get into the folder.
except for the php on the server.
does anyone know the code line?
Thanks
Matthy | You want
```
Deny from all
``` | Instead of denying all traffic you could try redirecting it with mod\_rewrite to make it useful i.e. back into the flow of the site.
```
RewriteEngine on
rewriteRule ^path/to/forbidden/directory/? index.php [L]
``` | Give no one access in a directory .htaccess | [
"",
"php",
".htaccess",
"directory",
""
] |
Is there a ***standard*** way to access the underlying container of `stack`, `queue`, `priority_queue` ?
I found a method called : `_Get_container()` in `VS2008` implementation of `stack` and `queue`, but no one for `priority_queue`! I think it is not standard anyway.
Also, I know it is a silly question! where can I find official documentation of the standard library ?
---
Just for clarification, I wasn't trying to mess up with the underlying container. All what I was trying to do is this :
```
template <class Container>
std::ostream& printOneValueContainer(std::ostream& outputstream, Container& container)
{
Container::const_iterator beg = container.begin();
outputstream << "[";
while(beg != container.end())
{
outputstream << " " << *beg++;
}
outputstream << " ]";
return outputstream;
}
// stack, queue
template
< class Type
, template<class Type, class Container = std::deque<Type> > class Adapter
>
std::ostream& operator<<(std::ostream& outputstream, const Adapter<Type>& adapter)
{
return printOneValueContainer(outputstream, adapter._Get_container());
}
.
.
.
std::stack<int> iStack;
.
.
std::cout << iStack << std::endl;
```
I hope you see that `_Get_container()` is not standard, and there is no one for `priority_queue` in `VS2008` implementation. | I spotted the following solution somewhere on the web and I'm using it in my projects:
```
template <class T, class S, class C>
S& Container(priority_queue<T, S, C>& q) {
struct HackedQueue : private priority_queue<T, S, C> {
static S& Container(priority_queue<T, S, C>& q) {
return q.*&HackedQueue::c;
}
};
return HackedQueue::Container(q);
}
int main()
{
priority_queue<SomeClass> pq;
vector<SomeClass> &tasks = Container(pq);
return 0;
}
```
Have fun :). | Based on the [accepted answer](https://stackoverflow.com/a/1385520/315052), a more general approach:
```
template <class ADAPTER>
typename ADAPTER::container_type & get_container (ADAPTER &a)
{
struct hack : ADAPTER {
static typename ADAPTER::container_type & get (ADAPTER &a) {
return a.*&hack::c;
}
};
return hack::get(a);
}
```
As I learned from [this answer](https://stackoverflow.com/a/29291621/315052), `.*&` is actually two operators, where the pointer resulting from `&hack::c` (which has type `ADAPTER::container_type ADAPTER::*`) is the target or the `.*` operator to retrieve the underlying container itself. `hack` has access to the protected member, but after the pointer is obtained, protections are lost. So `a.*(&hack::c)` is allowed. | Is there a way to access the underlying container of STL container adaptors? | [
"",
"c++",
"data-structures",
"stl",
"standards",
""
] |
I've created a class witch contains a typed list and derives to another class that I created. This looks as follows:
```
namespace MyIntegretyCheck.Common
{
/// <summary>
/// Description of PolicyErrors.
/// </summary>
public partial class PolicyErrorEndingDates
{
public int ID_P {get;set;}
public DateTime DT_S_E {get;set;}
public DateTime DT_SC_E {get;set;}
public List<PolicyErrorDescr> Errors {get;set;}
}
public partial class PolicyErrorDescr
{
public string Field1{get;set;}
public string Field2 {get;set;}
public string F1IsThanF2 {get;set;}
public string Message {get;set;}
public int ErrorLevel {get;set;} //0= Info | 1= Warning | 2= Error
}
}
```
Now I created a typed list of `PolicyErrorEndingDates`, added an entry and tried then to add entries of his nested list Errors as follows:
```
public List<PolicyErrorEndingDates> MyPolicyEndingDates()
{
DAL.PolicyEndingDates ped = new DAL.PolicyEndingDates();
List<PolicyErrorEndingDates> MyErrors = new List<PolicyErrorEndingDates>();
foreach(var m in ped.CheckTables())
{
bool HasError = false;
PolicyErrorEndingDates p = new PolicyErrorEndingDates();
p.ID_P = m.ID_P;
if(m.DT_S_E != m.DT_SC_E)
{
PolicyErrorDescr e = new PolicyErrorDescr();
HasError = true;
e.Field1 = "DT_S_E";
e.Field2 = "DT_SC_E";
e.Message = "blablabla...";
e.ErrorLevel = 3;
p.Errors.Add(e);
}
if(HasError)
MyErrors.Add(p);
}
}
```
The Debugger crashed with the message `Object reference not set to an instance of an object`, at the line `p.Errors.Add(e);` inside my `if`. What did I do wrong? How can I create an instance of the nested list? | Did you assign a `List<PolicyErrorDescr>` instance to the Errors property?
First, I would probably make the `Errors` collection read-only from the outside, that is, the list can be changed, but you can't give it a new list.
This I would do by making the setter private:
```
public List<PolicyErrorDescr> Errors { get; private set; }
^-----^
this
```
Then I would create a constructor and assign a collection instance to that property from it:
```
public PolicyErrorEndingDates()
{
Errors = new List<PolicyErrorDescr>();
}
```
This should take care of the null reference exception. | My guess, since p is a new instance, the Errors list wasn't instantiated (Like what Lasse mentioned).
```
e.ErrorLevel = 3;
p.Errors = new List<PolicyErrorDescr>(); //add this
p.Errors.Add(e);
``` | C# Nested typed lists | [
"",
"c#",
"inner-classes",
""
] |
I have to use a method which accepts double[,], but I only have a double[]. How can I convert it?
Solution so far:
```
var array = new double[1, x.Length];
foreach (var i in Enumerable.Range(0, x.Length))
{
array[0, i] = x;
}
``` | I just wrote this code which I will use:
```
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace MiscellaneousUtilities
{
public static class Enumerable
{
public static T[,] ToRow<T>(this IEnumerable<T> target)
{
var array = target.ToArray();
var output = new T[1, array.Length];
foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
{
output[0, i] = array[i];
}
return output;
}
public static T[,] ToColumn<T>(this IEnumerable<T> target)
{
var array = target.ToArray();
var output = new T[array.Length, 1];
foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
{
output[i, 0] = array[i];
}
return output;
}
}
}
``` | There's no direct way. You should copy stuff into a `double[,]`. Assuming you want it in a single row:
```
double[,] arr = new double[1, original.Length];
for (int i = 0; i < original.Length; ++i)
arr[0, i] = original[i];
``` | How to convert single dimensional arrays to multi dimensional ones? (C#) | [
"",
"c#",
".net",
"arrays",
"multidimensional-array",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.