Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm writing a Windows service in C#. I've got an `XmlWriter` which is contains the output of an XSLT transformation. I need to get the XML into an `XMLElement` object to pass to a web service.
What is the best way to do this? | You do not need an intermediate string, you can create an XmlWriter that writes directly into an XmlNode:
```
XmlDocument doc = new XmlDocument();
using (XmlWriter xw = doc.CreateNavigator().AppendChild()) {
// Write to `xw` here.
// Nodes written to `xw` will not appear in the document
// until `xw` is closed/disposed.
}
```
and pass xw as the output of the transform.
NB. Some parts of the xsl:output will be ignored (e.g. encoding) because the XmlDocument will use its own settings. | Well, an `XmlWriter` doesn't *contain* the output; typically, you have a backing object (maybe a `StringBuilder` or `MemoryStream`) that is the dumping place. In this case, `StringBuilder` is probably the most efficient... perhaps something like:
```
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
// TODO write to writer via xslt
}
string xml = sb.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement el = doc.DocumentElement;
``` | Creating an XML Element object from an XML Writer in C# | [
"",
"c#",
"xml",
"xmlwriter",
""
] |
What are the often misunderstood concepts in c++? | **C++ is not C with classes!**
And there is no language called C/C++. Everything goes downhill from there. | That C++ *does* have automatic resource management.
(Most people who claim that C++ does not have memory management try to use new and delete way too much, not realising that if they allowed C++ to manage the resource themselves, the task gets much easier).
Example: (Made with a made up API because I do not have time to check the docs now)
```
// C++
void DoSomething()
{
File file("/tmp/dosomething", "rb");
... do stuff with file...
// file is automatically free'ed and closed.
}
// C#
public void DoSomething()
{
File file = new File("/tmp/dosomething", "rb");
... do stuff with file...
// file is NOT automatically closed.
// What if the caller calls DoSomething() in a tight loop?
// C# requires you to be aware of the implementation of the File class
// and forces you to accommodate, thus voiding implementation-hiding
// principles.
// Approaches may include:
// 1) Utilizing the IDisposable pattern.
// 2) Utilizing try-finally guards, which quickly gets messy.
// 3) The nagging doubt that you've forgotten something /somewhere/ in your
// 1 million loc project.
// 4) The realization that point #3 can not be fixed by fixing the File
// class.
}
``` | What are the often misunderstood concepts in C++? | [
"",
"c++",
""
] |
I've discovered that `std::string`s are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall program by a factor of 2.
I expected STL to be slower, I didn't realise it was going to be this much slower.
I'm using Visual Studio 2008, release mode. It shows assignment of a string to be 100-1000 times slower than `char*` assignment (it's very difficult to test the run-time of a `char*` assignment). I know it's not a fair comparison, a pointer assignment versus string copy, but my program has lots of string assignments and I'm not sure I could use the "*const reference*" trick in all places. With a reference counting implementation my program would have been fine, but these implementations don't seem to exist anymore.
My real question is: why don't people use reference counting implementations anymore, and does this mean we all need to be much more careful about avoiding common performance pitfalls of std::string?
My full code is below.
```
#include <string>
#include <iostream>
#include <time.h>
using std::cout;
void stop()
{
}
int main(int argc, char* argv[])
{
#define LIMIT 100000000
clock_t start;
std::string foo1 = "Hello there buddy";
std::string foo2 = "Hello there buddy, yeah you too";
std::string f;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
f = foo1;
foo1 = foo2;
foo2 = f;
}
double stl = double(clock() - start) / CLOCKS\_PER\_SEC;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
}
double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC;
char* goo1 = "Hello there buddy";
char* goo2 = "Hello there buddy, yeah you too";
char *g;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
g = goo1;
goo1 = goo2;
goo2 = g;
}
double charLoop = double(clock() - start) / CLOCKS_PER_SEC;
cout << "Empty loop = " << emptyLoop << "\n";
cout << "char* loop = " << charLoop << "\n";
cout << "std::string = " << stl << "\n";
cout << "slowdown = " << (stl - emptyLoop) / (charLoop - emptyLoop) << "\n";
std::string wait;
std::cin >> wait;
return 0;
}
``` | Well there are definitely known problems regarding the performance of strings and other containers. Most of them have to do with temporaries and unnecessary copies.
It's not too hard to use it right, but it's also quite easy to Do It Wrong. For example, if you see your code accepting strings by value where you don't need a modifiable parameter, you Do It Wrong:
```
// you do it wrong
void setMember(string a) {
this->a = a; // better: swap(this->a, a);
}
```
You better had taken that by const reference or done a swap operation inside, instead of yet another copy. Performance penalty increases for a vector or list in that case. However, you are right definitely that there are known problems. For example in this:
```
// let's add a Foo into the vector
v.push_back(Foo(a, b));
```
We are creating one temporary `Foo` just to add a new `Foo` into our vector. In a manual solution, that might create the `Foo` directly into the vector. And if the vector reaches its capacity limit, it has to reallocate a larger memory buffer for its elements. What does it do? It copies each element separately to their new place using their copy constructor. A manual solution might behave more intelligent if it knows the type of the elements before-hand.
Another common problem is introduced temporaries. Have a look at this
```
string a = b + c + e;
```
There are loads of temporaries created, which you might avoid in a custom solution that you actually optimize onto performance. Back then, the interface of `std::string` was designed to be copy-on-write friendly. However, with threads becoming more popular, transparent copy on write strings have problems keeping their state consistent. Recent implementations tend to avoid copy on write strings and instead apply other tricks where appropriate.
Most of those problems are solved however for the next version of the Standard. For example instead of `push_back`, you can use `emplace_back` to directly create a `Foo` into your vector
```
v.emplace_back(a, b);
```
And instead of creating copies in a concatenation above, `std::string` will recognize when it concatenates temporaries and optimize for those cases. Reallocation will also avoid making copies, but will move elements where appropriate to their new places.
For an excellent read, consider [Move Constructors](http://www.ddj.com/database/184403855) by Andrei Alexandrescu.
Sometimes, however, comparisons also tend to be unfair. Standard containers have to support the features they have to support. For example if your container does not keep map element references valid while adding/removing elements from your map, then comparing your "faster" map to the standard map can become unfair, because the standard map has to ensure that elements keep being valid. That was just an example, of course, and there are many such cases that you have to keep in mind when stating "my container is faster than standard ones!!!". | It looks like you're misusing char\* in the code you pasted. If you have
```
std::string a = "this is a";
std::string b = "this is b"
a = b;
```
you're performing a string copy operation. If you do the same with char\*, you're performing a pointer copy operation.
The std::string assignment operation allocates enough memory to hold the contents of b in a, then copies each character one by one. In the case of char\*, it does not do any memory allocation or copy the individual characters one by one, it just says "a now points to the same memory that b is pointing to."
My guess is that this is why std::string is slower, because it's actually copying the string, which appears to be what you want. To do a copy operation on a char\* you'd need to use the strcpy() function to copy into a buffer that's already appropriately sized. Then you'll have an accurate comparison. But for the purposes of your program you should almost definitely use std::string instead. | How efficient is std::string compared to null-terminated strings? | [
"",
"c++",
"stl",
"performance",
""
] |
I want to execute UPDATE command over a group of records, but it fails, because some records after the update would violate an table constraint. Is it possible to update only suitable records somehow? | Behaviour of Update as all or nothing is by design
You can add Where clauses to your Update command to check all the constraints but this results in code duplication, not a good thing
How about doing the update one row at a time using a Cursor or CLR loop?
If this is part of a multilayer application, then this is where your business objects need to know about your SQL constraints via meta data or schema interrogation so that data validation can be done before it hits the database
The [CSLA framework](http://www.lhotka.net/cslanet/) has some goodies for this | The update statement is itself atomic, it will either all succeed or all fail. You need to modify the SQL to update only the rows where the constraint will not be violated. | Partial UPDATE command | [
"",
"sql",
"sql-server",
"transactions",
""
] |
I have a Database class which contanins the follwing methods:
* public bool ExecuteUDIQuery(string query) // UDI = Update Delete Insert
* public bool ExecuteSelectQuery(string query)
* public bool ExecuteSP(string sp, string[,] parms)
* public int ExecuteSPReturnValue(string sp, string[,] parms)
The results of the methods are stored in private datasets or datatables. These objects are defined as getters.
There're about 10 classes which use the Database class. Every class creates an object of the class Database. Now i was thinking to make the Database class static. Is this a good idea? If so, why? Of not, why not? | If I understand, the database class has some properties that store the result of the query? If so, you cannot make them static, since that is not thread-safe. If the result of a query is stored in these properties, what would happen if a second query would execute right after the first? It would be stored in the same static variable. The same goes for a web application: the result of another user browsing the site would change the results of the first user.
EDIT: To summarize, do NOT make the class static when you store the result of the queries in static variables, especially not when the class is used in a website, as the properties value will be shared amongst all visitors of your website. If 20 visitors do a query at the same time, visitor 1 will see the results of visitor 20's query. | In your specific example, I'd advise against making the class static: you're keeping state in the Database class, and by making the class static, that state will be shared amongst all classes using your Database. In your current setup, each Database instance keeps its own state, so there's no problem with Database calls interfering with each other.
If you'd refactor the Database class to return the datasets when doing a method call, you'd be fine making it static: there would be no stateful information left in the Database class.
But since this is not the case: no, don't make the class static. | C# static database class? | [
"",
"c#",
"database",
"static",
"data-access-layer",
"data-access",
""
] |
I need to make a large c++ library avaiable for use in .Net languages such as C#.
The library contains a large number of classes which can be broken into two groups. Refrence counted classes, which implement the IRefCounted abstract class and use a factory method to create them, and just plain classes using new/delete.
In adittion there are many plain functions.
Origenannly I was just going to write wrapper classes for everything in c++/clr. However it is desired that the resulting wrapper libraries will work on Mono. Recompiling the library and the wrapper to target each platform is fine, however the problem is that it seems that c++/clr can only target windows as there is no compiler for it to target other platforms and thus the wrapper code wont work on other patforms...
Is there somthing I missed here (like a howto run c++/clr on x platform guide) or is there an alterative way to make all the c++ functions, structs and classes avaible to C#?
EDIT: By avaible I mean avaible to use eg say in my c++ lib I had
```
//namespace maths{
class Vector2
{
public:
float x,y;
Vector2();
Vector2(const Vector&);
Vector2(float x, float y);
float Dot();
//operators
...
};
```
Then in C# id like to be able to use it like a normal class eg
```
maths::Vector2 a = new maths::Vector2(5, 5);
maths::Vector2 b = new maths::Vector2(1, 10);
b *= 3
maths::Vector2 c = a + b;
//c.x == 8, c.y == 35
```
Also however I do it I cant edit the c++ library, anything must be done as a wrapper around the existing classes and functions. | C++/CLI wrappers are definitely the best option if you are only targetting Windows. They perform very well, are very easy to write and maintain, etc. But, as you said, this will not work on Mono. The issue is that the assembly that gets created is not a clr:pure assembly, but one that has mixed native and IL code, so it will not work outside of Windows. In addition, you need to create separate assemblies in C++/CLI for x86 and x64 targets, if you're going to be targetting 64bit systems.
SWIG is definitely an option. It can handle all of the complexities of wrapping a C++ class, but when you get to more complex issues, you typically have to do some tweaking.
I'd recommend checking out the [SWIG main site](http://www.swig.org), and especially their [C# section.](http://www.swig.org/Doc1.3/CSharp.html)
For good examples of using SWIG to wrap a very complex library, check out [OGRE Dot Net](http://www.ogre3d.org/wiki/index.php/OgreDotNet) (nearly dead, but still a good example) or [GDAL](http://www.gdal.org). From what I remember, both have special handling for C# specific features, and handle reference counted classes, enums, etc.
The other nice thing about SWIG - if you make SWIG wrappers, it's very easy to extend it to other languages if you ever need to. Once you have the wrappers, making Java, python, ruby, etc wrappers is easy. | I used [SWIG](http://www.swig.org/) to wrap some C++ code and calling it from mono worked great. | Making C++ library Avaiable to .Net | [
"",
"c++",
".net",
"mono",
"cross-platform",
"native",
""
] |
Suppose I have two classes:
```
public class Student
{
public int Id {get; set;}
public string Name {get; set;}
public IList<Course> Courses{ get; set;}
}
public class StudentDTO
{
public int Id {get; set;}
public string Name {get; set;}
public IList<CourseDTO> Courses{ get; set;}
}
```
I would like to copy value from Student class to StudentDTO class:
```
var student = new Student();
StudentDTO studentDTO = student;
```
How can I do that by reflection or other solution? | The lists make it tricky... my earlier reply (below) only applies to like-for-like properties (not the lists). I suspect you might just have to write and maintain code:
```
Student foo = new Student {
Id = 1,
Name = "a",
Courses = {
new Course { Key = 2},
new Course { Key = 3},
}
};
StudentDTO dto = new StudentDTO {
Id = foo.Id,
Name = foo.Name,
};
foreach (var course in foo.Courses) {
dto.Courses.Add(new CourseDTO {
Key = course.Key
});
}
```
---
edit; only applies to **shallow** copies - not lists
Reflection is an option, but slow. In 3.5 you can build this into a compiled bit of code with `Expression`. Jon Skeet has a pre-rolled sample of this in [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) - just use as:
```
Student source = ...
StudentDTO item = PropertyCopy<StudentDTO>.CopyFrom(student);
```
Because this uses a compiled `Expression` it will vastly out-perform reflection.
If you don't have 3.5, then use reflection or ComponentModel. If you use ComponentModel, you can at least use [`HyperDescriptor`](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) to get it *nearly* as quick as `Expression`
```
Student source = ...
StudentDTO item = new StudentDTO();
PropertyDescriptorCollection
sourceProps = TypeDescriptor.GetProperties(student),
destProps = TypeDescriptor.GetProperties(item),
foreach(PropertyDescriptor prop in sourceProps) {
PropertyDescriptor destProp = destProps[prop.Name];
if(destProp != null) destProp.SetValue(item, prop.GetValue(student));
}
``` | Ok I just looked up the [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) that Marc posted about and its just awesome. I hope mark doesn't mind me adding the code here.
```
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
class Program
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public IList<int> Courses { get; set; }
public static implicit operator Student(StudentDTO studentDTO)
{
return PropertyCopy<Student>.CopyFrom(studentDTO);
}
}
public class StudentDTO
{
public int Id { get; set; }
public string Name { get; set; }
public IList<int> Courses { get; set; }
public static implicit operator StudentDTO(Student student)
{
return PropertyCopy<StudentDTO>.CopyFrom(student);
}
}
static void Main(string[] args)
{
Student _student = new Student();
_student.Id = 1;
_student.Name = "Timmmmmmmmaaaahhhh";
_student.Courses = new List<int>();
_student.Courses.Add(101);
_student.Courses.Add(121);
StudentDTO itemT = _student;
Console.WriteLine(itemT.Id);
Console.WriteLine(itemT.Name);
Console.WriteLine(itemT.Courses.Count);
}
}
// COOLEST PIECE OF CODE FROM - http://www.yoda.arachsys.com/csharp/miscutil/
/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// </summary>
public class PropertyCopy<TTarget> where TTarget : class, new()
{
/// <summary>
/// Copies all readable properties from the source to a new instance
/// of TTarget.
/// </summary>
public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
{
return PropertyCopier<TSource>.Copy(source);
}
/// <summary>
/// Static class to efficiently store the compiled delegate which can
/// do the copying. We need a bit of work to ensure that exceptions are
/// appropriately propagated, as the exception is generated at type initialization
/// time, but we wish it to be thrown as an ArgumentException.
/// </summary>
private static class PropertyCopier<TSource> where TSource : class
{
private static readonly Func<TSource, TTarget> copier;
private static readonly Exception initializationException;
internal static TTarget Copy(TSource source)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
return copier(source);
}
static PropertyCopier()
{
try
{
copier = BuildCopier();
initializationException = null;
}
catch (Exception e)
{
copier = null;
initializationException = e;
}
}
private static Func<TSource, TTarget> BuildCopier()
{
ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
var bindings = new List<MemberBinding>();
foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
{
if (!sourceProperty.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
if (targetProperty == null)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
}
if (!targetProperty.CanWrite)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
}
if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
}
bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
}
Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
}
}
}
}
``` | How to copy value from class X to class Y with the same property name in c#? | [
"",
"c#",
".net",
"reflection",
""
] |
I can't seem to get this working, here is my (stripped down) code: -
```
[XmlRoot("report")]
public class Report
{
[XmlArray("sections"), XmlArrayItem("section")]
public List<Section> Sections;
}
public class Section
{
public Report Report;
}
```
Am I missing something? | Your objects contain circular references which is not supported by the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class. You could instead look at the [DataContractSerializer](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx) which [supports](http://www.jameskovacs.com/blog/GoingAroundInCirclesWithWCF.aspx) such scenarios. | You should make sure you know how you want those classes to serialize and deserialize. Write the XML you want as a result, and figure out how you want objects to become XML and vice versa. It's not a no-brainer. | How can I get a reference to the parent object when deserializing XML in C#? | [
"",
"c#",
".net",
"serialization",
"parent-child",
""
] |
I'm looking for a control for C# that can contain other controls, takes care of layout and allows drag and drop rearranging of the layout order.
Simularly to the way the iphone/ipod allows you to rearrange apps.
Thanks. | Using something like [DockPanelSuite](http://sourceforge.net/projects/dockpanelsuite) as a basis might be a good starting point. | I think you can implement your own easily, using FlowLayoutPanel and MouseUp, MouseDown, MouseMove events of the controls where you change the Location property approximately and FlowLayoutPanel should handle it. | I need a drag and drop control for C# winforms | [
"",
"c#",
"winforms",
"drag-and-drop",
""
] |
I'm writing a small program to help split passwords ( see below for explanation)
I have code to convert text to a int ( text-ascii binary -> dec int)
so in this case the word "test" would = 1952805748
Now the interesting part.(encoding the password)
I would then take x1 = 1952805748 and y1 = 0
then i make up a random point where x2 = 7 and y2 = 142
this will draw a line between x1,y1 and x2,y2 (using Y=mx+B)
I need to how find any random point along the line that these two points create (well call that x3,y3)
If anyone has any ideas i would love to hear them. Im trying to work out the code that both points are ints ( its easier on everyone if we dont have huge decimal points behind each number)
++ The why ++
the general idea is that if you had to split up a password between two parties that one party could possibly figure out the password based on the string they were given
if you use this method they would get a single point each and from that single point it would be mathmaticly impossible to deterimine where the line meets x (x=? y =0)
so you could feel safe handing one set of points to your lawyer and one to your wife
they would do the math (entering it into a program) then they would get a number that would be decode to say a password that could decrpt a file with your will or some other sensitve document that you wouldnt want them to access with out the other preseent | This algorithm is actually called "[Shamir's Secret Sharing](http://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing)" and is a really good way of splitting up secrets. You can split up arbitrarily large secrets which require whichever number of people you want to come together to recover the secret.
I would suggest you generalize slightly and go for a solution that will let you specify that N points are required to solve for the N-1 degree polynomial. You can use [Lagrange Polynomials](http://en.wikipedia.org/wiki/Lagrange_polynomial) to solve this for you.
The pseudo code at Wikipedia, however, is only good for floats, and needs to be modified slightly for use with integers. [Check out my full python implementation](http://gist.github.com/585345) if you want some ideas (and assuming it is at all helpful).
It gives me this output:
```
1 -- 50383220533284199945706810754936311181214547134666382315016772033813961148457676
2 -- 125723425896904546349739165166331731432281836699962161072279259011758052396215820
3 -- 235794378436564714387676526976517945151880763730707233042654663244625708155520494
'This is my super secret password.'
```
***Edit:*** A year later I have updated the implementation to work within a finite field, which is required for it to be provably secure. Hooray! | Other answers have addressed your mathematical idea, but on the encryption front I would *strongly* recommend that you don't try to work out your own encryption scheme.
If you want to encrypt something with two passwords such that both are necessary, there's a much easier way to do it: encrypt the file twice:
```
Plaintext -> Encrypted1 (with password 1)
Encrypted1 -> Encrypted2 (with password 2)
```
`Encrypted2` is what you store. Throw away `Encrypted1`.
To decrypt, just decrypt `Encrypted2` with password 2 to get `Encrypted1`, then decrypt `Encrypted1` to get back to the plaintext.
Either password on its own is useless, just as intended, and you don't need to work out *any* encryption algorithms/code.
EDIT: As an even simpler solution, just make up a really long password and give each party half of it. For instance, encrypt the file with the key "this is a very long password" and give your wide "this is a very" and your lawyer " long password". Obviously you need to choose the password appropriately so that knowing one half doesn't give any hints about the other. | Find random point along a line | [
"",
"c#",
".net",
"encryption",
"geometry",
""
] |
I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found [this old post](http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html) about it, but maybe six years later something more straightforward has emerged? ^^;
I found [this recipe](http://code.activestate.com/recipes/546511/) too, but when I use it, the resulting PDF is missing the images.. | I was able to implement the NumberedCanvas approach from ActiveState. It was very easy to do and did not change much of my existing code. All I had to do was add that NumberedCanvas class and add the canvasmaker attribute when building my doc. I also changed the measurements of where the "x of y" was displayed:
```
self.doc.build(pdf)
```
became
```
self.doc.build(pdf, canvasmaker=NumberedCanvas)
```
**doc** is a BaseDocTemplate and **pdf** is my list of flowable elements. | use doc.multiBuild
and in the page header method (defined by "onLaterPages="):
```
global TOTALPAGES
if doc.page > TOTALPAGES:
TOTALPAGES = doc.page
else:
canvas.drawString(270 * mm, 5 * mm, "Seite %d/%d" % (doc.page,TOTALPAGES))
``` | Showing page count with ReportLab | [
"",
"python",
"reportlab",
""
] |
I've tried to research this mechanism but only find hints and these are not very consistent. How is the session \_id sent to the browser and how is the browser instructed to return it when the user requests a new page?
Thanks, Chris | PHP will do 2 things:
* It will rewrite all links to pass an extra GET parameter, usually PHPSESSID but this can be changed by setting session.name in php.ini
* It will add a hidden input with the same name after all `<form>` opening tags.
Note that this is a dangerous thing to do, because anyone who you e.g. copy/paste a URL to containing an PHPSESSID parameter will be able to share your login session on the site - the webserver has no easy way of telling that you are different from the person you sent the link to... | PHP's own session module supports fetching the session id from GET and POST data (besides cookies). You can use <http://uk.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid> and <http://uk.php.net/manual/en/session.configuration.php#ini.url-rewriter.tags> to let php handle the forwarding of the id. But in any case keep in mind that especially if you're using GET to transport the id it's more likely some of your users give away their (valid) session id by accident.
The underlying mechanism doesn't care *how* the session id was transported from the client to the server. As long as you pass the "right" value to session\_id() it will work - even if you do something as weird (stupid?) as abusing the etag-header as a vehicle for the session id ;-) | How do PHP sessions work when cookies are disabled? | [
"",
"php",
"session",
"cookies",
""
] |
When you know that your software (not a driver, not part of the os, just an application) will run mostly in a virtualized environment are there strategies to optimize your code and/or compiler settings? Or any guides for what you should and shouldn't do?
This is not about a 0.0x% performance gain but maybe, just maybe there are simple things that will improve performance drastically or things that seem simple but are known to be disastrous in virtualized environments. For example enabling CONFIG\_PARAVIRT in a kernel build is easily done and can boost performance a lot. Now I'm looking for similar things for applications, if there are any.
In my case it will be C++ Code and probably VMWare but I want to keep the question as language/product-agnostic as possible. I wonder if there even are such strategies or if this would be a complete waste of time - after all the concept of virtualization is that you don't have to care too much about it. | The only advice that I can give you is careful use of mlock() / mlockall() .. while looking out for buggy balloon drivers.
For instance, if a Xen guest is booted with 1GB, then ballooned down to 512 MB, its very typical that the privileged domain did NOT look at how much memory the paravirtualized kernel was actually promising to processes (i.e. Committed\_AS). Actually, with Xen, unless this value is placed on Xenbus, the privileged host has no idea what such a balloon will do. I believe this also coincides with KVM, depending upon how the kernel is configured .. but your question presumes that we know nothing about such things :)
So, protect stuff (be careful, but prudent) that simply can not be paged out, always account for the 'sky is falling' scenario.
Likewise, use of posix\_fadvise() / posix\_madvise() to tell the PV kernel just how much you do or do not need buffering is always a good idea.
Beyond that, there's very little that you can do .. since you're talking only to the paravirtualized kernel, which is designed to make processes oblivious to virtualization in the first place.
I don't use KVM much (yet), though I plan to explore it more in the future. However, 90% of the stuff that I have been writing lately is specifically designed to run on paravirtualized Xen guests. Sorry to be a little Xen / C centric, but that's where my experience is and pv\_ops is in mainline (soon also xen-0 ops) :)
Good question, btw :)
**Edit:**
When I said 'careful but prudent' , I meant one step above conservative. If your program allocates some job structure that most functions need, lock it. If your allocating buffers to read huge files, don't lock them .. and be sure to call posix\_fadvise() to let the kernel know you only intend to access it once (if that's the case). Also, be sure to advise the kernel on your use of memory mapped files, especially if they serve to organize concurrency.
In short, help your host kernel manage memory, don't let critical allocated blocks get thrown into dirty paging, don't assume your program is more important than anything else by locking everything it allocates :)
Sorry for the ambiguity. The best phrase I could come up with was 'careful, but prudent'. | I've found it to be all about I/O.
VMs typically suck incredibly badly at IO. This makes various things much worse than they would be on real tin.
Swapping is especially a bad killer - it completely wrecks VM performance, even a little, as IO is so slow.
Most implementations have a large amount of IO contention between VMs, I've not seen one which avoids this or handles it sensibly.
So use a ramdisc for temporary files if you can, but don't cause it to swap, because that would be even worse. | Software optimization for virtual machines | [
"",
"c++",
"optimization",
"virtualization",
""
] |
-edit- I am sending binary and not a string. My test is using html pages so in this example i am only using a string but my question is about binary, vectors and debugging with ostream. I make this clears some confusion.
I have the following code:
```
cout << string(&v[0]).substr(0, len);
```
Is there a better way to print the string *v* with cout up the length *len*? I thought of doing v[len] = 0 but I an assertion is thrown with a size of 1. My code is:
```
vector<char> v;
v.reserve(1024*16); //required
v.resize(1); //so we can do &v[0]
recv(sockfd, &v[0], v.capacity(), 0);
while (l > 0)
{
cout << string(&v[0]).substr(0, l);
recv(sockfd, &v[0], v.capacity(), 0);
}
cout << "the size is " << v.size();
``` | You can use the method ostream::write on the cout object:
```
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> test;
test.push_back('a');
test.push_back('b');
test.push_back('c');
cout.write(&test[0], 3);
cout << endl;
}
```
Outputs:
> abc
Since ostream::write returns an ostream& containing \*this, you can even do
```
cout.write(&test[0], 3) << endl;
```
but I'm not sure that is actually any better (or clearer). | ```
vector<char> v;
v.reserve(1024*16); //required
v.resize(1); //so we can do &v[0]
recv(sockfd, &v[0], v.capacity(), 0);
```
That code has a bug. Calling `reserve` will only guarantee you that you can push\_back at least that many elements until references and iterators to the vector are invalidated again (through a possible reallocation of the used buffer). It will *not* allow you to write into v[0..1024\*16-1], as you do there with `recv`. You have to do
```
v.resize(1024*16); //required
```
to actually have that many elements available and actually pass `v.size()` instead of `v.capacity()`.
For your substring operation, i would probably do
```
std::string str(&v[0], n);
std::cout << str;
```
Where n ranges from 0 up to v.size(). You can use `std::min(n, v.size())` to guarantee that, if n could be larger in your case and you need an upper limit.
(on a side node, i would avoid having a variable called "l" (ell) there, because it can look very much like an "1" (one), which can confuse the hell out of people) | Is there a better way to print a string with cout up to N characters? | [
"",
"c++",
"vector",
""
] |
I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but had no luck.
Is there a way i can get the traceback to execute a function so i can dump the file so i can look at the file input and see were my code went wrong? | [sys.excepthook](http://docs.python.org/library/sys.html#sys.excepthook) may help you here, where you can set a global exception handler. I am not sure how pycurl exceptions are handled, it being a binding library, but it will probably work to reassign it to a generic function. Something like:
```
>>> import sys
>>>
>>> def my_global_exception_handler(type, value, traceback):
... print traceback
... sys.exit()
...
>>> sys.excepthook = my_global_exception_handler
>>> raise
<traceback object at 0xb7cfcaa4>
```
This exception hook function could easily be an instance method that has access to the file that needs dumping. | You can use a generic exception handler.
```
logging.basicConfig( file="someFile.log", level=logging.DEBUG )
logger= logging.getLogger( __name__ )
try:
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
# etc.
curl.perform()
curl.close
logger.info( "Read %s", url )
except Exception, e:
logger.exception( e )
print e, repr(e), e.message, e.args
raise
logging.shutdown()
```
This will write a nice log that has the exception information you're looking for. | python runtime error, can dump a file? | [
"",
"python",
"error-handling",
"pycurl",
""
] |
I have a TextBox which I would like to implement undo/redo functionality for. I [have read](https://stackoverflow.com/questions/434658/textbox-undo-redo-commands) that it might have some slight undo functionality already, but that it is buggy? Anyways, I would like to implement both undo and redo functionality also just to learn how you would go ahead and do that.
I have read about the [Memento Pattern](http://en.wikipedia.org/wiki/Memento_pattern) and looked some on a [Generic Undo/Redo](http://www.codeproject.com/Articles/18025/Generic-Memento-Pattern-for-Undo-Redo-in-C) example on CodeProject. And the pattern kiiind of makes sense. I just can't seem to wrap my head around how to implement it. And how to do it effeciently for the contents of a `TextBox`.
Of course I could just store `textbox.Text` when `TextChanges`, but that would hug up quite a lot of memory pretty fast, especially if the `TextBox` contained a lot of text.
So anyways, I'm looking for some advice on how to implement a good, clear and efficient way of implementing this functionality. Both in general and especially for a TextBox c",) | The .NET `System.ComponentModel` namespace comes with an `IEditableObject` interface, you could also use `INotifyPropertyChanging` and `INotifyPropertyChanged`. MVC Pattern would also make it that your interface responds to changes in the model through events thus updating or restoring the value of your textbox.
Effectively the *Memento Pattern*.
Have you had a look into these? [Here](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.ieditableobject) is a how to.
A simple and quicker version would be to store the state of the textbox `OnTextChanged`. Each undo would return the last event in an Array. The C# Stack Type would be handy here. You could clear the state once you are off the interface also or after `Apply`. | Here's a way to achieve it with minimal code:
(This is the code behind of a win form with a single textbox on it)
```
public partial class Form1 : Form
{
Stack<Func<object>> undoStack = new Stack<Func<object>>();
public Form1()
{
InitializeComponent();
}
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.U && Control.ModifierKeys == Keys.Control && undoStack.Count > 0)
undoStack.Pop()();
}
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 'u' || Control.ModifierKeys != Keys.Control)
{
var textBox = (TextBox)sender;
undoStack.Push(textBox.Text(textBox.Text));
}
}
}
public static class Extensions
{
public static Func<TextBox> Text(this TextBox textBox, string text)
{
return () => { textBox.Text = text; return textBox; };
}
}
```
By implementing an extension method for other input types the undoStack can service the whole of your UI, undoing all UI actions in order. | How to implement good and efficient undo/redo functionality for a TextBox | [
"",
"c#",
"undo-redo",
"memento",
""
] |
I'm looking for a side-by-side diff program a la xxdiff or DiffMerge that, instead of diffing files, allows blocks of text to be dragged into either the left side or right side window.
I'm refactoring some SQL embedded in source files, and it would be nice to drag the sql statements from each source file into the diff program instead of having to cut and paste to files and then diff the files.
Any clues appreciated, bonus for mac and linux compatibility... Thanks!
**update: both winmerge and beyond do this perfectly... thanks again guys!** | [Winmerge](http://winmerge.org/) allows you to use Alt + Left and Alt + Right to move different text blocks to left and right.
It's free / open source and overall great tool as well. | If you use beyond compare and start a new text compare you can just paste into the windows and it will diff what you've pasted. Not quite drag and drop, but the same really.
No need to have the contents you want to diff in a file. I'd really recommend beyond compare, it's a great tool. You can get a trial version at:
<http://www.scootersoftware.com/>
Just to mention, it is linux compatible, but I've only ever used it on windows. | side-by-side diff program that supports dragging blocks of text into windows? | [
"",
"sql",
"merge",
"diff",
""
] |
What I am asking, is what is the best way (i.e. the way that is easiest for neophyte web developers) to consume/integrate data that I make available on my website, into their own website.
I have a website written in asp.net/sql server back end.
I have clients that would like to be able to incorporate selections of data (say for example a table of data and some images that varies in length and is different for each user) into their website, so that the data looks like it belongs to them, and is branded by them (ideally the data would come to them with default css formatting, but they could customizing as much as they want). When the data on my website changes, the data on their website needs to change.
I'd like the user of my data to come to my website, login, and then be able to " copy" a customized script/code from my website, paste it into theirs and then just have it work, no matter what their website is written in (i.e. pure html, php, asp.net or others).
I am assuming that a some sort of javascript script would be the best way to go, but I am at a loss as to how to make this completely simple for the user and what the script might contain (javascript is not my strong point yet). I.e. can I get a javascript on a clients website call a asp.net script on my server and then stream HTML back to their website..
I am sure there must be examples of this done elsewhere, can someone point me in the right direction?
**EDIT: Let me try to give a better example of what I am trying to do**.
My app is not a real-estate app, but lets assume it us (pretend realtor.com the MLS database). Now every realtor in the country has their own website, and they are written in all kinds of languages so I can't assume anything about the consumer of the data, nor can I assume they have any programming expertise.
If I was realtor.com owner, I'd like every realtor to be able to come to my website, copy a snippet of code (like I said, perhaps some javascript but I am not sure), go back to their website and paste it into the source of their page and then when one of their users goes to "Joesrealty.com" and clicks on "Show all properties for sale" the script/code/page would actually pull html down from my site by executing something on my website (realtor.com) and retrieve a list of all properties that that agent had for sale (say a table with accompanying picture).
I know I saw a great implementation of this somewhere on a big name site, but for the life of me can't remember where I saw it, and never bothered at the time to try and see what technology they used. | > I have clients that would like to be able to incorporate selections of data (...) into their website, so that the data looks like it belongs to them, and is branded by them
A number of sites make this functionality available via snippets of javascript code, e.g. [TechnicalJobs.ie](http://technicaljobs.ie/widgets/).
The user pastes some javascript code in to their page. This code calls back to your website to pull the most recent data, then displays it on the client's website.
**Example**
We can send back an unstyled list of new widgets, and allow the user to style the css to tweak the display on their site.
On your page, tell the user to copy the following javascript in to their page:
```
<script src="http://www.yoursite.com/widgets.asp?action=getNewWidgets"
type="text/javascript"></script>
<script type="text/javascript">
showWidgets('widget-container', 'widget-list');
</script>
```
On your site, `widgets.asp` will be responsible for looking up the data on new widgets from your database. It will pull the data together, then output it in [JSON-encoded](http://json.org/) format. The logic is all handled in ASP or your language of choice, and outputted in the format outlined below.
This page will also return the `showWidgets` method, which handles converting your data for display on the user's website.
`widgets.asp`'s final output should look something like:
```
// Widget product data
var widgets = [
{
"url":"http:\/\/www.yoursite.com\/widgets\/foo-widget",
"title":"Brand new Foo Widget, available now!"
},
{
// More widget details..
}
];
// Function to display list of widgets on calling page
function showWidgets(container_div, style)
{
// Start building the html for the list
var html = "<ul class='" + style + "'>";
// Loop through all of the widgets we have, ading to list
for (i = 0; i < widgets.length; i++)
{
html += "<li><a target='_blank' href='" + widgets[i].url + "'>";
html += widgets[i].title;
html += "</a></li>";
}
html += "</ul>";
// We have the html, now write to the container
// If the user hasn't created this already, we'll make it
if (document.getElementById(container_div))
{
document.getElementById(container_div).innerHTML = html;
}
else
{
// Target div wasn't made by user, create it inline
document.write("<div id='" + container_div + "'>");
document.write(html);
document.write("</div>");
}
}
```
Once the user embeds your js code on to their page, the output of `widgets.asp` will take care of writing out the recent data. You can specify styles etc, or leave this all up to the end user to style it in accordance with the rest of their website. | Your list of requirements seem to be pretty broad.
I was going to suggest building some kind of RESTful Web Service, through which users could consume your data in what ever format is most appropriate. This could be XML or JSON if they have the capability to parse that, or if they just want to embed an iframe in their page it could return plain HTML.
Take a look at some of Yahoo's Web Services and get an idea of how they do things:
<http://developer.yahoo.com/> | Best technology to allow consumers of my website to incorporate dynamic data into their website | [
"",
"javascript",
""
] |
I have a .Net application. I want this application to send an email to me. How do I implement this without installing an SMTP server? | Using an [`SmtpClient`](http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx) to send a [`MailMessage`](http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage_members.aspx) does not require you to have a server on your local machine.
Your e-mail service provider is the one with the server (e.g. smtp.gmail.com), and your `SmtpClient` talks to it. | This article by Peter Bromberg on eggheadcafe.com
[C# SMTP Mail without SMTP Service or CDO](http://www.eggheadcafe.com/articles/20030316.asp)
explains how to send email without relying on an SMTP client:
> Sending email via TCP using the native
> SMTP RFC commands "HELO", "MAIL From",
> RCPT TO", etc. is no big deal. That's
> one of the first tricks we learn with
> Telnet. Finding or writing managed
> code that will do so reliably is
> another story. The code in the class
> that follows is not my original code -
> I've cobbled it together from three
> different sample sources, fixing
> namespaces, error handling, and other
> minor items, changing console code to
> class library code, and providing a
> complete Winforms - based test harness
> front end that illustrates its correct
> usage.
>
> I've also included sample code
> to correctly process and add a mail
> attachment via an OpenFileDialog here.
> This code MIME encodes and transmits
> the attachment(s) according to the
> specification. | Sending mail without installing an SMTP server | [
"",
"c#",
".net",
"email",
"smtp",
""
] |
How could I set a constraint on a table so that only one of the records has its `isDefault` bit field set to 1?
The constraint is not table scope, but one default per set of rows, specified by a FormID. | Here's a modification of Damien\_The\_Unbeliever's solution that allows one default per FormID.
```
CREATE VIEW form_defaults
AS
SELECT FormID
FROM whatever
WHERE isDefault = 1
GO
CREATE UNIQUE CLUSTERED INDEX ix_form_defaults on form_defaults (FormID)
GO
```
But the serious relational folks will tell you this information should just be in another table.
```
CREATE TABLE form
FormID int NOT NULL PRIMARY KEY
DefaultWhateverID int FOREIGN KEY REFERENCES Whatever(ID)
``` | ## Use a unique filtered index
On SQL Server 2008 or higher you can simply use a **unique filtered index**
```
CREATE UNIQUE INDEX IX_TableName_FormID_isDefault
ON TableName(FormID)
WHERE isDefault = 1
```
Where the table is
```
CREATE TABLE TableName(
FormID INT NOT NULL,
isDefault BIT NOT NULL
)
```
For example if you try to insert many rows with the same `FormID` and `isDefault` set to 1 you will have this error:
> Cannot insert duplicate key row in object 'dbo.TableName' with unique
> index 'IX\_TableName\_FormID\_isDefault'. The duplicate key value is (1).
Source: <http://technet.microsoft.com/en-us/library/cc280372.aspx> | Constraint for only one record marked as default | [
"",
"sql",
"sql-server",
""
] |
How can I find the state of NumLock, CapsLock and ScrollLock keys in .NET? | Import the WinAPI function *GetKeyState*:
```
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
```
And then you can use it like this:
```
bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
```
It is for framework 1.1. For framework 2.0 (and later) you can use:
[`Control.IsKeyLocked`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked(VS.80).aspx) | With Framework 2.0 and above, you can use a framework function:
*[Control.IsKeyLocked(Keys) Method](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.iskeylocked#System_Windows_Forms_Control_IsKeyLocked_System_Windows_Forms_Keys_)*
```
public static bool NumlockActive()
{
return Control.IsKeyLocked(Keys.NumLock);
}
``` | How can I find the state of NumLock, CapsLock and ScrollLock in .NET? | [
"",
"c#",
".net",
"capslock",
""
] |
Although class friendship is one of the last resorts of C++, does this pattern make sense?
```
class Peer
{
public:
friend class Peer;
void GetSecret(const Peer& other)
{
const std::string& secret = other.GiveSecret();
std::cout << secret << std::endl;
}
private:
const std::string& GiveSecret() const
{
return "secrety stuff";
}
};
int main(int argc, char* argv[])
{
Peer peerA;
Peer peerB;
peerA.GetSecret(peerB);
return 0;
}
```
Ok the reason for this pattern is because the Peers are all of the same rank, and they need to share knowledge among each other, however this knowledge is secret, because no one but the peers should use it, or the program is no longer valid.
One very real example of this is that when one peer is copy-constructed from another peer it needs to access secret information from its source peer, but again there is no reason for anyone else to know about these internals, just the peers. | friend is not necessary in this case. An object of a class can access the private members of any other object of the same type. It should work just fine without the friend declaration. | standard c++ says that the private clause has class scope. That's means that every Peer can access the private part of any other Peer. This isn't implementation specific | Is C++ friendship among peers healthy? | [
"",
"c++",
"class-design",
"friend",
""
] |
Greetings everyone. Having an issue compiling my script containing the following function. Three errors occur, all on the same line where I set distance += to distances [][]:
error C2108: subscript is not of integral type
error C2108: subscript is not of integral type
error C2297: '+=' : illegal, right operand has type 'double (\*)[15]'
Assistance would be much appriciated.
```
double S_initial;
double distances [15][15];
double order [15];
void Initialize()
{
double x, y ,z;
double distance = 0;
for (int i = 0; i <= 14; i++)
{
x = order [i];
y = order [i + 1];
distance += distances [x][y];
}
S_initial = distance;
}
``` | Well, the array subscripts `x` and `y` are not of an integral type like `int`, but of type `double`:
```
double x, y, z;
...
distance += distances[x][y];
```
And something like the 1.46534th element of an array doesn't make sense, so the compiler complains. | x and y are not integers... You need to pass integers as array subscripts. | Saving an array value into a double variable | [
"",
"c++",
"arrays",
"operators",
""
] |
In c# how do I evenly divide 100 into 7?
So the result would be
1. 16
2. 14
3. 14
4. 14
5. 14
6. 14
7. 14
The code below is incorrect as all 7 values are set to 15 (totalling 105).
```
double [] vals = new double[7];
for (int i = 0; i < vals.Length; i++)
{
vals[i] = Math.Ceiling(100d / vals.Length);
}
```
Is there an easy way to do this in c#?
Thanks | To get my suggested result of 15, 15, 14, 14, 14, 14, 14:
```
// This doesn't try to cope with negative numbers :)
public static IEnumerable<int> DivideEvenly(int numerator, int denominator)
{
int rem;
int div = Math.DivRem(numerator, denominator, out rem);
for (int i=0; i < denominator; i++)
{
yield return i < rem ? div+1 : div;
}
}
Test:
foreach (int i in DivideEvenly(100, 7))
{
Console.WriteLine(i);
}
``` | Here you go:
```
Func<int, int, IEnumerable<int>> f = (a, b) =>
Enumerable.Range(0,a/b).Select((n) => a / b + ((a % b) <= n ? 0 : 1))
```
Good luck explaining it in class though :) | Evenly divide in c# | [
"",
"c#",
""
] |
I am trying to serialize a .NET `TimeSpan` object to XML and it is not working. A quick google has suggested that while `TimeSpan` is serializable, the `XmlCustomFormatter` does not provide methods to convert `TimeSpan` objects to and from XML.
One suggested approach was to ignore the `TimeSpan` for serialization, and instead serialize the result of `TimeSpan.Ticks` (and use `new TimeSpan(ticks)` for deserialization). An example of this follows:
```
[Serializable]
public class MyClass
{
// Local Variable
private TimeSpan m_TimeSinceLastEvent;
// Public Property - XmlIgnore as it doesn't serialize anyway
[XmlIgnore]
public TimeSpan TimeSinceLastEvent
{
get { return m_TimeSinceLastEvent; }
set { m_TimeSinceLastEvent = value; }
}
// Pretend property for serialization
[XmlElement("TimeSinceLastEvent")]
public long TimeSinceLastEventTicks
{
get { return m_TimeSinceLastEvent.Ticks; }
set { m_TimeSinceLastEvent = new TimeSpan(value); }
}
}
```
While this appears to work in my brief testing - is this the best way to achieve this?
Is there a better way to serialize a TimeSpan to and from XML? | The way you've already posted is probably the cleanest. If you don't like the extra property, you could implement `IXmlSerializable`, but then you have to do **everything**, which largely defeats the point. I'd happily use the approach you've posted; it is (for example) efficient (no complex parsing etc), culture independent, unambiguous, and timestamp-type numbers are easily and commonly understood.
As an aside, I often add:
```
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
```
This just hides it in the UI and in referencing dlls, to avoid confusion. | This is only a slight modification on the approach suggested in the question, but [this Microsoft Connect issue](http://connect.microsoft.com/VisualStudio/feedback/details/386602/system-timespan-xml-serialization "Microsoft Connect") recommends using a property for serialization like this:
```
[XmlIgnore]
public TimeSpan TimeSinceLastEvent
{
get { return m_TimeSinceLastEvent; }
set { m_TimeSinceLastEvent = value; }
}
// XmlSerializer does not support TimeSpan, so use this property for
// serialization instead.
[Browsable(false)]
[XmlElement(DataType="duration", ElementName="TimeSinceLastEvent")]
public string TimeSinceLastEventString
{
get
{
return XmlConvert.ToString(TimeSinceLastEvent);
}
set
{
TimeSinceLastEvent = string.IsNullOrEmpty(value) ?
TimeSpan.Zero : XmlConvert.ToTimeSpan(value);
}
}
```
This would serialize a TimeSpan of 0:02:45 as:
```
<TimeSinceLastEvent>PT2M45S</TimeSinceLastEvent>
```
Alternatively, the `DataContractSerializer` supports TimeSpan. | How to serialize a TimeSpan to XML | [
"",
"c#",
"serialization",
"timespan",
""
] |
I've been developing "traditional" ASP.NET applications with server side ASP.NET controls and code behind files, etc. Now I'm exploring several JavaScript libraries like: jQuery, YUI, Ext Js, Prototype. (also it's hard to pick one, but it's another post). All these libraries make client to server communication a lot easier, but they also offer nice set of very sleek UI controls. And some controls are way sleeker than ASP.NET server side controls in my opinion.
But now I am questioning the traditional ASP.NET model. I am leaning towards all HTML/JS UI talking to the server (just a simple aspx page) via REST.
What do you think? Have anyone used this approach? What are some drawbacks and gotchas? Also if you could comment on what JS Library/Framework you used and your experience with it, that would be great too.
Thanks | This is a very lengthy topic covered by numerous people, but at its core the difference is basically this:
For **very form-heavy web applications, which maintain a great deal of state information**; frequently stay on the same page and behave similarly to a desktop application, **the traditional ASP.NET WebForms model** provides a lot of the glue to hold all that together for you.
For **everything else**, the **REST/MVC model** works best.
This is a generalization and does not apply to every single situation, but on the whole it's a good rule of thumb.
It's also very important to point out that if you don't have a captive audience (such as a corporate intranet, and sometimes even then) you should code your site, WebForms *or* REST, to work without JS. Then go back and add the sweet goodness for those who can support it. | Don't rule out a hybrid model. ASP.NET now supports server controls that natively output javascript to the browser. If you have traditional controls that render markup and use the ASP.NET WebForms model for posting data, consider modifying the controls to be ScriptControls, which allows you to handle loading data, etc. in your existing codebehind, but write javascript to handle the UI of the control entirely. You can write server controls that output the javascript you need (and set variable values, etc. with data from your codebehind during load), and then instead of doing postbacks, have your javascript communicate with a web service using AJAX. Definitely explore ajax.asp.net. | ASP.NET server side tags vs. JavaScript-based UI and REST | [
"",
".net",
"asp.net",
"javascript",
"ajax",
"asp.net-ajax",
""
] |
I get this problem in IE7 when running a piece of code that uses jquery and 2 jquery plugins. The code works in FF3 and Chrome.
The full error is:
```
Line: 33
Char: 6
Error: bg is null or not an object
Code: 0
URL: http://localhost/index2.html
```
However line 33 is a blank line.
I am using 2 plugins: draggable and zoom. No matter what I do to the code it is always line 33 that is at fault. I check the source has update via view source but I feel this could be lying to me.
```
<body>
<div id="zoom" class="zoom"></div>
<div id="draggable" class="main_internal"><img src="tiles/mapSpain-smaller.jpg" alt=""></div>
<script type="text/javascript">
$(document).ready(function() {
$('#draggable').drag();
$('#zoom').zoom({target_div:"draggable", zoom_images:new Array('tiles/mapSpain-smaller.jpg', 'tiles/mapSpain.jpg') });
});
</script>
</body>
```
Essentially what I am trying to do is recreate the Pragmatic Ajax map demo with jQuery.
---
It would appear that the second line of this snippet is causing the trouble:
```
bg = $(this).css('background-position');
if(bg.indexOf('%')>1){
```
It seems to be trying to select the background-position property of `#draggable` and not finding it? Manually adding a `background-position: 0 0;` didn't fix it. Any ideas on how to get around this problem?
I tried using the MS Script Debugger but that is nearly useless. Can't inspect variables or anything else. | A bit more digging about on the Interweb has revealed the answer: IE doesn't understand the selector `background-position`. It understands the non-standard `background-position-x` and `background-position-y`.
Currently hacking something together to workaround it.
Nice one, Redmond. | To get around the fact that Internet Explorer does not support the "background-position" CSS attribute, as of jQuery 1.4.3+ you can use the [.cssHooks](http://api.jquery.com/jQuery.cssHooks/) object to normalize this attribute between browsers.
To save yourself some time, there is a [background position jQuery plugin](https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js) available that allows both "background-position" and "background-position-x/y" to work as expected in browsers that don't support one or the other by default. | Fix for background-position in IE | [
"",
"javascript",
"jquery",
"internet-explorer",
"background-position",
""
] |
I'm using Visual C# 2008 Express. I'd like to use the same icon for the application (ie, the icon shown for the .exe), and for the main form. Unfortunately, VC# doesn't seem to be very smart about this, and insists on duplicating the icon data.
There doesn't seem to be a way of selecting an "already embedded" icon for use in the form or project icon (only selecting a file), and using the same file for both icons just embeds the file twice as far as I can see. It's not a big deal (hard drive space is cheap now, right?), but it bugs me.
Any idea how to avoid this? Is there a way to programatically load the executable's icon for use when the form is constructed, say? A couple of forum posts about similar things seem to suggest that .NET resources don't use the normal old Windows resource system -- is there a way from within the framework of getting at the old-style resources? Or do I have to bind the Win32 API functions to do it? | Yeah, it's pretty annoying. But the problem with the proposed answer of Icon.ExtractAssociatedIcon is that it will retrieve the 32x32 icon, and then downsample to a 16x16 icon in your forms window or on the taskbar, which will look terrible unless your 32x32 icon is very cleverly constructed.
The way I'm doing it is with interop (put the first line in your form constructor):
```
this.Icon = ExtractSmallIconFromLibrary(Application.ExecutablePath);
...
public static Icon ExtractSmallIconFromLibrary(string file) {
IntPtr[] reficon = new IntPtr[1];
int nextracted = ExtractIconEx(file, 0, null, reficon, 1);
if (nextracted < 1)
return null;
Icon unmanaged_icon = Icon.FromHandle(reficon[0]);
Icon icon = (Icon)unmanaged_icon.Clone();
DestroyIcon(unmanaged_icon.Handle);
return icon;
}
[DllImport("Shell32", CharSet = CharSet.Auto)]
extern static int ExtractIconEx(
[MarshalAs(UnmanagedType.LPTStr)]
string lpszFile,
int nIconIndex,
IntPtr[] phIconLarge,
IntPtr[] phIconSmall,
int nIcons
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);
```
But this isn't great, either, since you *do* want the 32x32 icon for things like the Alt-Tab icon list. So you really need to extract the *entire* icon, which is a bigger job. Maybe there's a straightforward way to combine the two icons into one. Or you can do like this [codeproject](http://www.codeproject.com/KB/dialog/AssigningDefaultIcon.aspx) program, which extracts the whole icon in the first place with a huge pile of code. | You're right, and it's rather annoying.
You have to load the icons yourself instead of relying on designer-generated code. Save the icon as a project resource, then load the resource into the form's `Icon` property in the form's constructor:
```
this.Icon = Properties.Resources.myIconResourceName;
``` | Avoiding duplicate icon resources in a .NET (C#) project | [
"",
"c#",
"winforms",
"winapi",
"resources",
""
] |
What would be the best approach to migrate a .NET Windows Service to Linux using mono? I've been trying to avoid executing the application as a scheduled command.
Is it possible to obtain a service/system daemon(in linux) like behavior? | Under Linux, [deamons](http://en.wikipedia.org/wiki/Daemon_(computer_software)) are simple background processes. No special control methods (e.g `start()`, `stop()`) are used as in Windows. Build your service as a simple (console) application, and run it in the background. Use a tool like [`daemonize`](http://www.clapper.org/software/daemonize/daemonize.1.html) to run a program as a Unix daemon, and remember to specify `mono` as the program to be activated.
As noted by others, [mono-service](http://linux.die.net/man/1/mono-service) is a host to run services built with the `ServiceProcess` assembly. Services built for Windows can use this method to run unmodified under Linux. You can control the service by sending signals to the process (see man page). | Can you use mono-service to wrap it?
See [this question](https://stackoverflow.com/questions/351971/using-mono-service-to-wrap-a-windows-service-on-linux). | How to migrate a .NET Windows Service application to Linux using mono? | [
"",
"c#",
".net",
"linux",
".net-2.0",
"mono",
""
] |
I have installed Eclipse and CDT (to use C/C++ in eclipse CDT is needed), as well as installing Cygwin so that I can compile my files.
In environment variables I've set Path to include the following: "C:\cygwin\bin;"
g++, make and GDC are all installed via Cygwin. I made sure of this by searching for them in the bin folder - they're all there.
If I enter "make" into the windows command prompt, this appears:
```
make: *** No targets specified and no makefile found. Stop.
```
If I enter "g++" or "gdc" into the windows command prompt, this appears (or similar):
```
'g++' is not recognized as an internal or external command,
operable program or batch file.
```
So, in other words make is working but the rest isn't..but they're in the same bin folder! Has got me completely confused.
If I attempt to open Cygwin Bash Shell, g++, make and GDC all work there.
However, I need it to work in the command prompt so that Eclipse is able to compile the programs I write in the IDE.
If you know why this is happening, please let me know. | I haven't used cygwin much, but my understanding is you *have* to use it from the cygwin bash shell.
if you need g++, make, etc, use [mingw](http://www.mingw.org/), with it, g++ works from the normal windows command line. | Here is what happened to me and how I fixed it.
My C:\cygwin\bin\g++.exe is a shortcut pointing to C:\etc\alternatives\g++.exe, which points back to C:\cygwin\bin\g++-3.exe.
Replacing g++ with g++-3 worked for me. | g++ not working on Windows command prompt. Cygwin installed | [
"",
"c++",
"command-line",
"cygwin",
"g++",
"eclipse-cdt",
""
] |
Is it possible to set up continuous build of projects written in .NET and Java on single build server with single set of applications?
I've seen CruiseControl has support for both world but as far as I know these are two separate applications. Should I go with a separate machine to build Java projects (a machine for .NET projects is already set up)? | [Hudson](http://hudson-ci.org/) has support for both Ant (out of the box IIRC) and [NAnt](http://wiki.hudson-ci.org/display/HUDSON/NAnt+Plugin) (through plugin) so that's an option for you. | CruiseControl supports several different [build options](http://cruisecontrol.sourceforge.net/main/configxml.html#schedule) include [Ant](http://cruisecontrol.sourceforge.net/main/configxml.html#ant), [Maven](http://cruisecontrol.sourceforge.net/main/configxml.html#maven2), [NAnt](http://cruisecontrol.sourceforge.net/main/configxml.html#nant), [Phing](http://cruisecontrol.sourceforge.net/main/configxml.html#phing) (php), [Rake](http://cruisecontrol.sourceforge.net/main/configxml.html#rake), [XCode](http://cruisecontrol.sourceforge.net/main/configxml.html#xcode), and then the generic "[exec](http://cruisecontrol.sourceforge.net/main/configxml.html#exec)" which you can use to invoke any command-line script/tool you want. Not a problem mixing Java and .NET on the same server.
Of course this is not unique to CruiseControl. There are lots of CI tools that support multiple build technologies as you can see on this [matrix of features](http://confluence.public.thoughtworks.org/display/CC/CI+Feature+Matrix).
Disclaimer: I work on CruiseControl. OTOH since I don't make money on it I don't much care which tool people choose. I care more about advancing the state of CI practices which is why I organize the Continuous Integration and Testing Conference ([CITCON](http://citconf.com/)). | Continuous build with .NET and Java projects on a single machine | [
"",
"java",
".net",
"continuous-integration",
"cruisecontrol",
""
] |
What is more efficient in terms of memory and CPU usage — an array of `boolean`s or a BitSet? Specific BitSet methods are not used, only get/set/clear (==, =, Arrays.fill respectively for an array). | From some benchmarks with Sun JDK 1.6 computing primes with a sieve (best of 10 iterations to warm up, give the JIT compiler a chance, and exclude random scheduling delays, Core 2 Duo T5600 1.83GHz):
BitSet is more memory efficient than boolean[] except for very small sizes. Each boolean in the array takes a byte. The numbers from runtime.freeMemory() are a bit muddled for BitSet, but less.
boolean[] is more CPU efficient except for very large sizes, where they are about even. E.g., for size 1 million boolean[] is about four times faster (e.g. 6ms vs 27ms), for ten and a hundred million they are about even. | * `Boolean[]` uses about 4-20 bytes per boolean value.
* `boolean[]` uses about 1 byte per boolean value.
* `BitSet` uses about 1 bit per boolean value.
Memory size might not be an issue for you in which case boolean[] might be simpler to code. | boolean[] vs. BitSet: Which is more efficient? | [
"",
"java",
"arrays",
"performance",
"memory",
"bitsets",
""
] |
I've been using the Java Service wrapper in a custom application for quite a while and it's been working fine. Since updating our application to a new version in the last few days the JVM started hanging and then wrapper prints this in the log:
JVM appears hung: Timed out waiting for signal from JVM.
It then automatically terminates the JVM and starts the app again. This happens after about 10 hours of running, which just makes it harder to debug.
Of course I am going to look through the changes that we've made, but no major changes were made that I would suspect is causing this type of problem.
Where can I look to try and figure out what is happening? Debug messages from the application don't indicate anything interesting. If the JVM just crashes it will usually create a dump, which can help in debugging it, but it's hanging, so it's not creating a dump. If I make it not restart the service automatically is there anything I can do to get some useful information out of the JVM before restarting it?
It seems to me that the JVM shouldn't hang from typical programming errors. What have you run into before that can cause the JVM to hang? | I had a couple different versions of a library on the classpath (JBPM). With wrapper you can use wildcards to include jars. Be careful with this though as you may accidentally include more than you should.
Here is an IBM article that gives information on [debugging hangs in Java](http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/index.jsp?topic=/com.ibm.java.doc.diagnostics.142j9/html/debughangwin.html). It basically says that there are two things that can cause hangs:
1. An infinite loop,
2. A deadlock.
Since then I've had to debug other hanging issues. On linux you can send the JVM the QUIT signal to make it do a thread dump to the console. This really helps figuring out where the issue is. Use this command to do that: kill -QUIT
Edit 6/13/2017
These days I use jmap included in the JDK to dump the entire memory of the program. Then I use Eclipse Memory Analyzer to see the exact state of the program when it crashed. You can look at the list of threads that are active and then inspect the variables in each stack frame.
```
/usr/java/latest/bin/jmap -dump:file=/tmp/app-crash.hprof <PID>
```
Where PID is the process ID of the java process. | Read up on the [wrapper.ping.timeout property](http://wrapper.tanukisoftware.org/doc/english/prop-ping-timeout.html). The wrapper software communicates with your JVM every so often to make sure that it is alive. If that communication fails for whatever reason, the wrapper deems the process hung and attempts to restart it.
Depending on how your application is architected, your JVM might be busy processing something else when the wrapper tries to "ping" it. | Java appears hung | [
"",
"java",
"debugging",
"freeze",
"java-service-wrapper",
""
] |
What's better to use in PHP for appending an array member,
```
$array[] = $value;
```
or
```
array_push($array, $value);
```
?
Though the manual says you're better off to avoid a function call, I've also read `$array[]` is much slower than `array_push()`. What are some clarifications or benchmarks? | I personally feel like `$array[]` is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.
I ran this code:
```
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
$array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
array_push($array, $i);
}
print microtime(true) - $t;
```
The first method using `$array[]` is almost 50% faster than the second one.
### Some benchmark results:
```
Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]
Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]
Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]
```
This shouldn't be surprising, as the PHP manual notes this:
> If you use array\_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
The way it is phrased I wouldn't be surprised if `array_push` is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual `$array[]` calls are faster than one big `array_push`. Interesting. | The main use of array\_push() is that you can push multiple values onto the end of the array.
It says in the [documentation](http://docs.php.net/array_push):
> If you use array\_push() to add one
> element to the array it's better to
> use $array[] = because in that way
> there is no overhead of calling a
> function. | Which is faster in PHP, $array[] = $value or array_push($array, $value)? | [
"",
"php",
"arrays",
"performance",
""
] |
I need to find random nodes according to random attribute values.
To do that I use getAtrribute on nodes from getElementsByTagName.
It seems like when I look for class name as attribute it does not work on IE (works on FF).
Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well? (if its only class I'll do a workaround.) | It's worth testing all of your Javascript cross-platform, if you're not using something like [jQuery](http://jquery.com/) to take the pain away, but Class may just be a special case.
This should be a cross-platform way of getting the class:
```
element.className
``` | > Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well?
It fails for all attributes where the HTML attribute name differs from the DOM property name (className, htmlFor), plus you have to use the DOM-style capitalisation. It also returns the wrong datatype for attributes whose DOM properties aren't strings:
```
disabled, readOnly, checked, selected, multiple,
compact, declare, isMap, noHref, defer, noResize,
size, cols, rows, width, height, hspace, vspace,
maxLength, tabIndex, colSpan, rowSpan
```
and possibly others I've missed!
```
element.getAttribute(x)
```
in IE is *exactly* the same as saying:
```
element[x]
```
So in general you should avoid using getAttribute, and use the simple DOM Level 1/2 HTML interfaces such as ‘element.className’ instead.
This is finally fixed in IE8. | getAttribute cannot return class in IE7? | [
"",
"javascript",
"internet-explorer-7",
""
] |
What options for async io (socket-based) are there in java other then java.nio? Also does java.nio use threads in the backround (as I think .NET's async-socket-library does, maybe it's been changed) or is it "true" async io using a proper select call? | Java's NIO package (as of Java6), provides support for *non-blocking I/O* only, via [Selector](http://java.sun.com/javase/6/docs/api/java/nio/channels/Selector.html)s. Java7 is hopefully going to ship with NIO.2, which includes asynchronous I/O support. Today, your best bet is to make use of a framework. ARMistice mentioned Mina. Here are some others.
1. [Grizzly](http://grizzly.java.net/). This is the I/O core for Sun's [GlassFish](http://glassfish.java.net/) server. Grizzly provides a facility for doing asynchronous reads/writes (via a queue model). It supports TCP and UDP alike. I've used Grizzly in a couple of projects. There are things I like and dislike about the framework, but to detail this is really another topic. I will say that it's quite easy to get something up and running and Grizzly does a lot of the heavy lifting for you.
2. [Netty](http://www.jboss.org/netty/). This project comes from one of the original authors of the Mina project. I haven't used this one so I don't know about its support for asynchronous I/O. You should take a look.
Now, with regard to your question about threads, NIO Selectors do not use threads for non-blocking I/O. In JDK6 they use **select()** under Windows and the epoll facility on newer Linux kernels. For asynchronous I/O, threading details depend on the framework. | JAVA 7 arrived so new answer is NIO.2 with Future class. Example :
On server side:
```
final AsynchronousServerSocketChannel serverSocket=
AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 2587)); // Listening on port 2587 for client connection
Future<AsynchronousSocketChannel> future= serverSocket.accept();
final AsynchronousSocketChannel clientSocket= future.get(); // now it's blocking, useful: future.isDone() and .isCancelled()
//Do whatever you want ..
InputStream stream = Channels.newInputStream(clientSocket) (...)
```
On client side:
```
AsynchronousSocketChannel clientChannel = AsynchronousSocketChannel.open();
Future connected = localSocket.connect(ourServerSocketAddress);
// later: if(future.isDone())
connected.get();
//Send something
OutputStream os = Channels.newOutputStream(clientChannel );
os.write (...)
```
**Update:**
If you can use actor model then [AKKA TCP IO](http://doc.akka.io/docs/akka/snapshot/scala/io-tcp.html) would be even better. | Asynchronous IO in Java? | [
"",
"java",
"networking",
"sockets",
"asynchronous",
""
] |
Recently, I've got a dangerous idea into my head after reading [this](http://www.codinghorror.com/blog/archives/001145.html "Don't Reinvent The Wheel, Unless You Plan on Learning More About Wheels") blog post. That idea can be expressed like this:
I don't need most of what the C++ standard library offers. So, why don't I implement a less general, but easier to use version?
As an example, using the STL spits out reams of incomprehensible and mangled compiler errors. But, I don't care about allocators, iterators and the like. So why don't I take a couple of hours and implement an easy to use linked list class, for example?
What I'd like to know from the StackOverflow community is this: what are the dangers, possible disadvantages and possible advantages to "rolling my own" for most of the existing functionality in C++?
**Edit:** I feel that people have misunderstood me about this idea. The idea was to understand whether I could implement a **very** small set of STL functionality that is greatly simplified - more as a project to teach me about data structures and the like. I don't propose re-inventing the entire wheel from the ground up, just the part that I need and want to learn about. **I suppose what I wanted to figure out is whether the complexity of using the STL warrants the creation of smaller, simpler version of itself.**
**Re-using boost or similiar.**
Most of what I code is for University and we're not allowed to use external libraries. So it's either the C++ standard library, or my own classes.
**Objectivity of this question.**
This question is **not** subjective. Nor should it be community Wiki, since it's not a poll. I want concrete arguments that highlight one advantage or one disadvantage that could **possibly** occur with my approach. Contrary to popular belief, this is not opinion, but based on experience or good logical arguments.
**Format.**
Please post only one disadvantage **or** one advantage per answer. This will allow people to evaluate individual ideas instead of all your ideas at once.
**And please...**
No religious wars. I'm not a fan boy of any language. I use whatever's applicable. For graphics and data compression (what I'm working on at the moment) that seems to be C++. Please constrain your answers to the question or they will be downvoted. | > So, why don't I implement a less
> general, but easier to use version?
Because you can't. Because whatever else you might say about C++, it is not a simple language, and if you're not already very good at it, your linked list implementation will be buggy.
Honestly, your choice is simple:
Learn C++, or don't use it. Yes, C++ is commonly used for graphics, but Java has OpenGL libraries too. So does C#, Python and virtually every other language. Or C. You don't have to use C++.
But if you do use it, learn it and use it properly.
If you want immutable strings, create your string as const.
And regardless of its underlying implementation, the STL is remarkably simple to use.
C++ compiler errors *can* be read, but it takes a bit of practice. But more importantly, they are not exclusive to STL code. You'll encounter them no matter what you do, and which libraries you use. So get used to them. And if you're getting used to them anyway, you might as well use STL too.
Apart from that, a few other disadvantages:
* No one else will understand your code. If you ask a question on SO about std::vector, or bidirectional iterators, everyone who's reasonably familiar with c++ can answer. If you ask abut My::CustomLinkedList, no one can help you. Which is unfortunate, because rolling your own also means that there will be more bugs to ask for help about.
* You're trying to cure the symptom, rather than the cause. The problem is that you don't understand C++. STL is just a symptom of that. Avoiding STL won't magically make your C++ code work better.
* The compiler errors. Yes, they're nasty to read, but they're there. A lot of work in the STL has gone into ensuring that wrong use will trigger compiler errors in most cases. In C++ it's very easy to make code that compiles, but doesn't work. Or seems to work. Or works on my computer, but fails mysteriously elsewhere. Your own linked list would almost certainly move more errors to runtime, where they'd go undetected for a while, and be much harder to track down.
* And once again, it will be buggy. Trust me. I've seen damn good C++ programmers write a linked list in C++ only to uncover bug after bug, in obscure border cases. And C++ is all border cases. Will your linked list handle exception safety correctly? Will it guarantee that everything is in a consistent state if creating a new node (and thereby calling the object type's constructor) throws an exception? That it won't leak memory, that all the appropriate destructors will be called? Will it be as type-safe? Will it be as performant? There are a lot of headaches to deal with when writing container classes in C++.
* You're missing out on one of the most powerful and flexible libraries in existence, in *any* language. The STL can do a lot that would be a pain even with Java's giant bloated class library. C++ is hard enough already, no need to throw away the few advantages it offers.
> I don't care about allocators,
> iterators and the like
Allocators can be safely ignored. You pretty much don't even need to know that they exist. Iterators are brilliant though, and figuring them out would save you a lot of headaches. There are only three concepts you need to understand to use STL effectively:
* Containers: You already know about these. vectors, linked lists, maps, sets, queues and so on.
* Iterators: Abstractions that let you navigate a container (or subsets of a container, or any other sequence of value, in memory, on disk in the form of streams, or computed on the fly).
* Algorithms: Common algorithms that work on *any* pair of iterators. You have sort, for\_each, find, copy and many others.
Yes, the STL is small compared to Java's library, but it packs a surprising amount of power when you combine the above 3 concepts. There's a bit of a learning curve, because it is an unusual library. But if you're going to spend more than a day or two with C++, it's worth learning properly.
And no, I'm not following your answer format, because I thought actually giving you a detailed answer would be more helpful. ;)
*Edit:*
It'd be tempting to say that an advantage of rolling your own is that you'd learn more of the language, and maybe even why the STL is one of its saving graces.. But I'm not really convinced it's true. It might work, but it can backfire too.
As I said above, it's easy to write C++ code that *seems* to work. And when it stops working, it's easy to rearrange a few things, like the declaration order of variables, or insert a bit of padding in a class, to make it *seemingly* work again. What would you learn from that? Would that teach you how to write better C++? Perhaps. But most likely, it'd just teach you that "C++ sucks". Would it teach you how to use the STL? Definitely not.
A more useful approach might be utilizing the awesome power of StackOverflow in learning STL the right way. :) | **Disadvantage:** no one but you will use it.
**Advantage:** In the process of implementing it you will learn why the Standard Library is a good thing. | Good Idea / Bad Idea Should I Reimplement Most Of C++? | [
"",
"c++",
"code-reuse",
"standard-library",
""
] |
I need to validate an object to see whether it is null, a value type, or `IEnumerable<T>` where `T` is a value type. So far I have:
```
if ((obj == null) ||
(obj .GetType().IsValueType))
{
valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
// TODO: check whether the generic parameter is a value type.
}
```
So I've found that the object is null, a value type, or `IEnumerable<T>` for some `T`; how do I check whether that `T` is a value type? | (edit - added value type bits)
You need to check all the interfaces it implements (note it could in theory implement `IEnumerable<T>` for multiple `T`):
```
foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type itemType = interfaceType.GetGenericArguments()[0];
if(!itemType.IsValueType) continue;
Console.WriteLine("IEnumerable-of-" + itemType.FullName);
}
}
``` | Can you do somethin with `GetGenericArguments` ? | How do I find out whether an object's type is a subclass of IEnumerable<T> for any value type T? | [
"",
"c#",
".net",
"generics",
"reflection",
""
] |
The question says it all really. Am I allowed derive a class from a struct, or should I create a class that embeds my struct and defines copy constructors and an = operator to move between the two? | In C++ `struct` is (almost) synonymous to a `class` (except of different default access level), so yes, you can.
```
struct A {
// fields are public by default
};
class B: public A {
// fields are private by default
};
```
I'm not familiar with MFC, but it looks like an attempt to maintain both C and C++ APIs. | Of course you are. What is different regarding the inheritance is that if you define a class, it will inherit private from other classes/structs. If you define a struct and derive it from a class or struct, it will be a public inheritance by default:
```
// the following two are equivalent except that one time class is
// used and the other time struct
struct f : g { };
class f : public g { };
```
If you wonder how you should wrap C structs - i would embed them as a member into the class. Because the C structs were not designed to be inherited from (think of the neither protected nor virtual destructor in the C structs - they can't have one). They are simple aggregates that collect data. And putting them as members uses them as such (as in "a point has a pair of an x and an y coordinate").
C structs also expose members that possibly should not be exposed in the class. Containment allows precise control over what is exposed and what not by get/set functions and you can still let it give you a copy or reference to the contained naked C struct object. | in C++, can I derive a class from a struct | [
"",
"c++",
"data-structures",
""
] |
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.
After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.
What is the most straightforward way to keep the interpreter window open until any key is pressed?
In batch files, one can end the script with pause. The closest thing to this I found in python is `raw_input()` *which is sub-optimal* because it requires pressing the return key (instead of any key). | One way is to leave a `raw_input()` at the end so the script waits for you to press Enter before it terminates. | Try `os.system("pause")` — I used it and it worked for me.
Make sure to include `import os` at the top of your script. | How to pause a script when it ends on Windows? | [
"",
"python",
"windows",
"cmd",
"command-line",
""
] |
I have a dialog that has to process large quantaties of data (the procedure is quite time consuming - first the ODBC fill takes its time, then the data processing kicks in) and the result is that the Form becomes unresponsive. This is not a problem really, it is enough to just open a "loading screen" in a new thread to notify the user of the process.
Recently I have discovered, that *sometimes* (it appears to be random) the new thread will throw an unhandled ThreadAbortException causing a crash report dialog box to show up (or JIT).
I do not understand why this exception would be thrown, or why it would be unhandled. Has anyone dealt with this before, or can anyone point me towards the probable cause of this behaviour?
Thank you!
EDIT: In case it matters, I open the loading screen like this:
```
//start of work load
Thread th = new Thread(new ThreadStart(MakeStep));
th.Start();
...
//end of work or error occurance:
th.Abort();
```
// | You're calling `th.Abort()` which injects a `ThreadAbortException` on the thread `th`. If that thread doesn't handle the exception it will be reported as an unhandled exception.
It is generally not recommended to abort other threads in this way, as you have no idea if the thread will handle an abort gracefully. A better solution is to use signaling between your threads. | ThreadAbortExceptions are raised when you call Thread.Abort(). Looks like you or a lib you are using is trying to kill your Thread. | Unhandled ThreadAbortException occuring - sometimes | [
"",
"c#",
"multithreading",
"exception",
""
] |
I have a string as mentioned below:
```
$ts = "3/11/09 11:18:59 AM";
```
which I got using the `date()` function.
Now I need to convert this to a readable format like below
```
11-Mar-2009
```
I have tried everything using `date()`. How can I achieve this? | You need to convert it to something you can use for further formatting. [strtotime()](http://de.php.net/manual/en/function.strtotime.php) is a good start, which yields a unix timestamp. You can format that one using [strftime()](http://de.php.net/manual/en/function.strftime.php) then.
```
strftime("%d-%b-%G", strtotime($ts));
``` | If you initially get the string from the date() function, then pass on formatting arguments to the date-function instead:
date('Y-m-d')
instead of converting the string once again.
EDIT: If you need to keep track of the actual timestamp, then store it as a timestamp:
```
// Store the timestamp in a variable. This is just an integer, unix timestamp (seconds since epoch)
$time = time();
// output ISO8601 (maybe insert to database? whatever)
echo date('Y-m-d H:i', $time);
// output your readable format
echo date('j-M-Y', $time);
```
Using strtotime() is convinient but unessecary parsing and storage of a timerepresentation is a stupid idea. | date formatting in php | [
"",
"php",
"date",
""
] |
We have a website that emails the contents of a contact form to our client. We would like to change this to make it a bit more secure (sensitive data can be sent over the contact form), we have encrypted the page with an SSL certificate so the only weak link we have at the moment is the email.
We already have an SSH connection setup to our client's servers and I was wondering if anyone knows if it is possible to send an email (possibly with attachments) over that connection?
Our web server is a linux machine and we are able to install applications ourselves. The client's server is a unix server, however their email system is Microsoft Exchange.
We've discussed PGP and it is not an option for our client, they will not install it on their systems.
Thanks for any help.
Peter | If the client's server is configured so the "[mail](http://en.wikipedia.org/wiki/Mail_(Unix))" command works you ought to be able to use that. And it is easy to test: ssh in and try it.
Otherwise, you probably want to go with [smtp over SSL with encryption](http://email.about.com/od/emailprogrammingtips/qt/et073006.htm) direct to their mail server. | To make my answer clearer I see three (3) systems here.
1. The webserver running the PHP script; later refered as the WebServer
2. The Unix server running on your client site; later refered to as the UnixServer
3. The Exchange server running on your client site; later refered to as the ExchangeServer
What you could do is use [autossh](http://www.harding.motd.ca/autossh/) to tunnel a connection from the WebServer through the UnixServer server with an endpoint at ExchangeServer. It is no end-to-end encrypton since you would not have an encrypted link from the UnixServer to the ExchangeServer it gets you closer to your goal.
Full documentation on autossh can be found [here](http://www.harding.motd.ca/autossh/README)
The basic steps for the setup would be this:
A. [Setup passwordless authentication](http://www.freebsdwiki.net/index.php/SSH:_Passwordless_authentication) from the WebServer to the UnixServer. You'll have to be carefull to protect the RSA key generated otherwise you've just opened a gaping hole on their system. Ideally run autossh under an unprivilege user and have the account used on the UnixServer to be unprivileged as well. **Make sure you test the connection before you start using autossh**
B. Setup your ssh options for keepalive (autossh is a fallback option). Make sure that the `~/.ssh/config` file for the user launching autossh has these option setup:
```
TCPKeepAlive yes
ClientAliveInterval 60
ServerAliveInterval 15
ServerAliveCountMax 3
```
C. Setup autossh. Linux.com as an articile about it [here](http://www.linux.com/feature/134133) and debianadmin.com as one [here](http://www.debianadmin.com/autossh-automatically-restart-ssh-sessions-and-tunnels.html). | PHP Send email over SSH | [
"",
"php",
"security",
"email",
""
] |
I'm reading through Jon Skeet's book reviews and he is going over the [numerous inaccuracies](http://msmvps.com/blogs/jon_skeet/archive/2008/03/21/book-review-head-first-c.aspx) of [Head First C#](https://rads.stackoverflow.com/amzn/click/com/0596514824).
One of them caught my eye:
> [Under Errors Section] Claiming that structs always live on the stack.
In what situations would structs *not* live on the stack? This goes contrary to what I thought I knew about structs. | One common example is where the struct is a member of an object that is allocated in the heap. There is lots of additional detail in this question here. [What’s the difference between struct and class in .Net?](https://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net) | **Whenever they are a field on a class**
Unusual examples of this:
a: When a value-type variable is captured:
```
int i = 2;
Action action = delegate {i++;}
action();
Console.WriteLine(i);
```
This is compiled to something more like:
```
class Foo {
public int i;
public void Bar() {i++;}
}
...
Foo foo = new Foo();
foo.i = 2;
Action action = foo.Bar;
action();
Console.WriteLine(foo.i);
```
b: When a value-type variable is used in an iterator block:
```
IEnumerable<int> GetValues() {
for(int i = 0 ; i < 5 ; i++) yield return i;
}
```
(the compiler generates a state machine to represent the iterator, of which all local variables (such as `i`) are fields) | When do structs not live on the stack? | [
"",
"c#",
"stack",
"struct",
""
] |
If I had a function like this:
```
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
```
Will it be possible to set `valid` from within the child function which is called after the Ajax request completes? If not, how can I return true/false from the parent function based on the result of the ajax request? | > If not, how can I return true/false from the parent function based on the result of the ajax request?
You can't; that's not how [Asynchrony](http://en.wikipedia.org/wiki/Asynchrony) works.
The AJAX call may never even return!
The parent function should fire off the request for validation, and then assume it is invalid (say, by disabling the submit button) or display a "I'm thinking" feedback (spinning indicator).
Then the AJAX return handling function will clean those parts up (by enabling the button or changing the indicator to a green checkmark or red X). If the AJAX call never goes through - it stays invalid. If it does go through, that's when the clean up happens. | Valid will be updated, yes. But: The AJAX-Call is asynchronous, ie. your function will most certainly be called after the parent function returns. There is no way to wait for the asynchronous process to finish. | Javascript variable scoping question | [
"",
"javascript",
""
] |
I am trying to make an application in which one component captures the screen of the user (for screen casting). I am aware that there are two options to achieve the same using a Java applet (please correct me if I am wrong). First is to use the java applet to take screen shots continuously and convert it into a video and upload it as a video file. And second is to create a java vnc server and record it as a .fbs file and play it using a player like: <http://www.wizhelp.com/flashlight-vnc/index.html>
I would like to know the best solution in terms of video quality, file size, cross-platform compatibility (windows and mac), firewall problems and finally ease of implementation.
I am very new to Java. Please tell me whats the best solution for my problem. Also, is it easy enough for me to program it on my own or should I get it developed via a freelancer. I have tons of programming experience (5+ years in LAMP) but none in Java.
Thank you very much. | I agree that this is pretty hard. I implemented those two solutions (VNC and onboard screen capture) plus a third (capture from an external VGA source via an [Epiphan](http://www.epiphan.com/products/frame-grabbers/) grabber) for a former employer. I had the best bandwidth-to-quality ratio with VNC, but I got higher framerate with VGA capture. In all three cases, I reduced the frames + capture times to PNGs and sequenced them in a QuickTime reference movie. Then I made flattened video (MPEG4 or SWF) of the results. In my case, I then synchronized the screen video with a DV stream.
In the end the technology worked (see [a sample](http://www.media-landscape.com/yapc/2006-06-26.ChrisDolan/) of the output) but our business model failed. | From what I know, the older versions of applet had security restrictions that may not allow for screen capture. Instead, a java application may be feasible.
Regarding the build-it-yourself vs the fire-a-coder, it depends on how you value your time compared to what you can find on a freelancer site.
I think you can find someone from India/Romania/Poland/Other countries that can make it for an affordable price | Java VNC Applet vs Screen Capture | [
"",
"java",
"video-capture",
"vnc",
""
] |
Anyone know if there is a PHP wrapper for the latest version (5.X) of [XML/SWF charts](http://www.maani.us/xml_charts/index.php) | <http://www.maani.us/charts/index.php>
*"As of version 5.0, there isn't a dedicated PHP interface for this charts tool. However, PHP or any other scripting language can still be used with XML/SWF Charts (the XML version of the same tool)."*
There are examples how to use XML version with PHP:
<http://www.maani.us/xml_charts/index.php?menu=Reference&submenu=Scripting> | As part of another project, I developed an open-source CodeIgniter library for generating the XML required by XML/SWF Charts: <http://milktek.com/XML-SWF-Charts-for-CI>
However, looking over the code in this library, I believe it will work outside of CodeIgniter as well. Just create a new `Maani_xml_swf_charts` object and call the various available methods. It should work because there is no CodeIgniter dependent code in the library.
```
$mxsc = new Maani_xml_swf_charts();
$mxsc->chart_type("stacked column");
$mxsc->chart_data(
array("sales","non-sales"),
array("Clothing","Food","Toys"),
array(
array("100","145"),
array("34","54"),
array("84","21")));
$mxsc->chart_label(array(
"shadow"=>'low',
"color"=>'ffffff',
"alpha"=>'95',
"size"=>'20',
"position"=>'inside',
"as_percentage"=>'true'));
``` | PHP wrapper for XML/SWF charts | [
"",
"php",
"charts",
"xml-swf-charts",
""
] |
I need to parse and return the tagname and the attributes in our PHP code files:
```
<ct:tagname attr="attr1" attr="attr2">
```
For this purpose the following regular expression has been constructed:
```
(\<ct:([^\s\>]*)([^\>]*)\>)
```
This expression works as expected but it breaks when the following code is parsed
```
<ct:form/input type="attr1" value="$item->field">
```
The original regular expression breaks because of the > character in the $item->field. I would need to construct a regular expression that ignores the -> or => but not the single >.
I am open to any suggestions... Thanks for your help in advance. | You could try using negative lookbehind like that:
```
(\<ct:([^\s\>]*)(.*?)(?<!-|=)\>)
```
Matches :
```
<ct:tagname attr="attr1" attr="attr2">
<ct:form/input type="attr1" value="$item->field">
```
Not sure that it the best suited solution for your case, but that respects the constraints. | Try this:
```
<ct:([^\s\>]*)((?:\s+\w+\s*=\s*(?:"[^"]*"|'[^']*')\s*)*)>
```
But if that’s XML, use should better use a XML parser. | Escaping -> and => when parsing HTML using regular expression | [
"",
"php",
"regex",
""
] |
I have a minute value and i want to have to 2 string values one with how many hours and the other with the minutes, e.g.:
Value - 121 minutes
string hours = 2
string minutes = 1
Value - 58 minutes
string hours = 0
string minutes = 58
How can I work this out in C#? | ```
var span = System.TimeSpan.FromMinutes(121);
var hours = ((int)span.TotalHours).ToString();
var minutes = span.Minutes.ToString();
```
The ToString() is because you asked for string values ...
TotalHours are the complete hours in the TimeSpan, they can be more than 24 (whereas the "Hours" field has a maximum of 24)
Oh, and on second thought: Why use the TimeSpan and not calculate it yourself? Because TimeSpan is already there debugged & tested by Microsoft, it has a nice clean interface (looking at the code you easily see whats going on without having to follow a calculation mentally) and it easily extends to further solutions. (Have the input in seconds? Use TimeSpan.FromSeconds(). Want the days? Use span.TotalDays ...)
***Update:***
I just noticed mistake in my answer: TotalHours returns a fractional value of all the hours, so we have to truncate it to an integer before converting it to a string. | Use a Timespan struct and its [Parse](http://msdn.microsoft.com/en-us/library/system.timespan.parse.aspx) method. | Work out min and hours | [
"",
"c#",
".net",
"datetime",
""
] |
I have a list of tuples (always pairs) like this:
```
[(0, 1), (2, 3), (5, 7), (2, 1)]
```
I'd like to find the sum of the first items in each pair, i.e.:
```
0 + 2 + 5 + 2
```
How can I do this in Python? At the moment I'm iterating through the list:
```
sum = 0
for pair in list_of_pairs:
sum += pair[0]
```
I have a feeling there must be a more Pythonic way. | In modern versions of Python I'd suggest [what SilentGhost posted](https://stackoverflow.com/a/638069/56541) (repeating here for clarity):
> ```
> sum(i for i, j in list_of_pairs)
> ```
---
In an earlier version of this answer I had suggested this, which was necessary because SilentGhost's version didn't work in the version of Python (2.3) that was current at the time:
```
sum([pair[0] for pair in list_of_pairs])
```
Now that version of Python is beyond obsolete, and SilentGhost's code works in all currently-maintained versions of Python, so there's no longer any reason to recommend the version I had originally posted. | ```
sum(i for i, j in list_of_pairs)
```
will do too. | How do I sum the first value in each tuple in a list of tuples in Python? | [
"",
"python",
"list",
"tuples",
""
] |
I'm trying to get an understanding of what the the java keyword `this` actually does.
I've been reading Sun's documentation but I'm still fuzzy on what `this` actually does. | The `this` keyword is a reference to the current object.
```
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
```
Another way to think about it is that the `this` keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses `Me` and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use `self`.
If you were to reference objects that are intrinsically yours you would say something like this:
> *My* arm or *my* leg
Think of `this` as just a way for a type to say "my". So a psuedocode representation would look like this:
```
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
``` | The keyword `this` can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: `return this;`
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
```
MyClass(String name)
{
this.name = name;
}
```
It can be used to invoke a different constructor of a a class from within a constructor:
```
MyClass()
{
this("default name");
}
```
It can be used to access enclosing instances from within a nested class:
```
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
``` | Using the keyword "this" in java | [
"",
"java",
"keyword",
""
] |
I have a Visual Studio 2008 project that produces a file called: "**Game-Release.exe**".
This was configured under **Project Properties** -> **C/C++** -> **Linker** -> **General**:
```
$(OutDir)\$(ProjectName)-Release.exe
```
I would like to take this a bit further by have an incrementing build number so I would have something which says:
```
Game-Release-Build-1002.exe
```
The number on the end should be an incrementing integer. I will be storing the build exe's on subversion so I think i would find this useful (although not necessary).
Perhaps there is a built in macro in Visual Studio that could handle this. Quite possibly I was thinking I could have a text file with the build number in it and have the compiler read, use and increment the number in the file each time the project is built. My goal is however to make the process as automated as possible. What is the best way to accomplish this?
If you offer an opinion, please also provide the code we can all share. Thnx. | The [Versioning Controlled Build](http://www.codeproject.com/KB/macros/versioningcontrolledbuild.aspx) add-in seems like it would do the job.
**Update:** Your question specifically mentions using Visual Studio to increment the version, but there is nothing automated about that. Have you considered using Nant and a CI server? That way, it is easy to inject the SVN revision number into AssemblyInfo.cs equivalent for C++. Automatically, on the build server. | If you are using svn to version your project you could follow the instructions in [this link](http://www.zachburlingame.com/2011/03/integrating-the-subversion-revision-into-the-version-automatically-with-native-cc/) it works perfectly for me because I can track bugs in a release application using its version information and comparing the source code.
All information below is not included in the link:
* setup your rc file like this *version.rc*
```
#include "resource.h"
#include "version.h" //<-----------Don't forget the include
/////////////////////////////////////////////////////////////////////////////
//
// Version.rc
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILE_VERSION
PRODUCTVERSION VER_PRODUCT_VERSION
FILEFLAGSMASK 0x17L
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040704b0"
BEGIN
VALUE "CompanyName", "Your Company Name"
VALUE "FileDescription", "Your Application Description"
VALUE "FileVersion", VER_FILE_VERSION_STR "\0"
VALUE "InternalName", "Internal Name"
VALUE "LegalCopyright", "CopyRight stuff - Copyright (C) 2015"
VALUE "OriginalFilename", "yourapp.exe"
VALUE "ProductName", "Your Application"
VALUE "ProductVersion", VER_PRODUCT_VERSION_STR "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x407, 1200
END
END
```
* Next add *version.h* file to your project which defines everything, setup like this:
```
#include "svn_version.h"
#define STRINGIZE2(s) #s
#define STRINGIZE(s) STRINGIZE2(s)
#define VERSION_MAJOR 1
#define VERSION_MINOR 0
#define VERSION_REVISION SVN_REVISION
#define VERSION_BUILD 0
#if SVN_LOCAL_MODIFICATIONS
#define VERSION_MODIFIER "M"
#else
#define VERSION_MODIFIER
#endif
#define VER_FILE_VERSION VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION, VERSION_BUILD
#define VER_FILE_VERSION_STR STRINGIZE(VERSION_MAJOR) \
"." STRINGIZE(VERSION_MINOR) \
"." STRINGIZE(VERSION_REVISION) \
"." STRINGIZE(VERSION_BUILD) \
#define VER_PRODUCT_VERSION VER_FILE_VERSION
#define VER_PRODUCT_VERSION_STR VER_FILE_VERSION_STR
```
after this you can follow the [link](http://www.zachburlingame.com/2011/03/integrating-the-subversion-revision-into-the-version-automatically-with-native-cc/) above. | How to Increment Visual Studio build number using C++? | [
"",
"c++",
"c",
"visual-studio-2008",
"compiler-construction",
"build-automation",
""
] |
I have a part in my code where I need to divide and have a remainder instead of a decimal answer.
How can I do this? | You can do what you are describing using the "%" (modulus) operator. The following code is an example of dividing with a remainder.
```
$remainder=$num % $divideby;
$number=explode('.',($num / $divideby));
$answer=$number[0];
echo $answer.' remainder '.$remainder;
``` | ```
$quotient = intval($dividend / $divisor);
$remainder = $dividend % $divisor;
```
Using `intval` instead of `floor` will round the quotient towards zero, providing accurate results when the dividend is negative. | Dividing with a remainder in PHP | [
"",
"php",
""
] |
```
function getLink($sa){
if($sa=='1'){
$sa = 'qp_bbl';
} else {
$sa = 'qp_sbl';
}
return $sa;
}
if(!$_POST['action']){
header ("Location: index.php");
}else{
$sa = $_POST['select'];
$sa = getLink($sa);
$link = connect(HOST, USER, PASSWORD, $sa);
(....)
}
```
This is driving me crazy. Select can be '1' or '2'. If i hard code $sa = '1' or '2' it all works great but if get set it from $\_POST['select'] it's a no go. I don't really understand... | With this solution you need to post "sa" on every page request, otherwise it will always fall back to "qp\_sbl" for any other request, since you don't seem to store which database you want to use during the session. | You could try examining the contents of $\_POST using print\_r($\_POST) to make sure that $\_POST['select'] is getting passed.
You should not be making a database connection based on $\_POST data, though. This is not very secure. If you want to conditionally select a database based on $\_POST, try something like this:
```
switch($_POST['select']) {
case '1': $db = '1'; break;
default: $db = '2';
}
```
That way you are sure that you are selecting a valid db. | Switching between mysql databases | [
"",
"php",
"mysql",
""
] |
For the equivalent mechanism in C++ (the destructor), the advice is that [it should usually not throw any exceptions](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.3). This is mainly because by doing so you might terminate your process, which is only very rarely a good strategy.
In the equivalent scenario in .NET ...
1. A first exception is thrown
2. A finally block is executed as a result of the first exception
3. The finally block calls a Dispose() method
4. The Dispose() method throws a second exception
... your process does not terminate immediately. However, you lose information because .NET unceremoneously replaces the first exception with the second one. A catch block somewhere up the call stack will therefore never see the first exception. However, one is usually more interested in the first exception because that normally gives better clues as to why things started to go wrong.
Since .NET lacks a mechanism to detect whether code is being executed while an exception is pending, it seems there are really only two choices how IDisposable can be implemented:
* Always swallow all exceptions that occur inside Dispose(). Not good as you might also end up swallowing OutOfMemoryException, ExecutionEngineException, etc. which I'd usually rather let tear down the process when they occur without another exception already pending.
* Let all exceptions propagate out of Dispose(). Not good as you might lose information about the root cause of a problem, see above.
So, which is the lesser of the two evils? Is there a better way?
**EDIT**: To clarify, I'm not talking about actively throwing exceptions from Dispose() or not, I'm talking about letting exceptions thrown by methods called by Dispose() propagate out of Dispose() or not, for example:
```
using System;
using System.Net.Sockets;
public sealed class NntpClient : IDisposable
{
private TcpClient tcpClient;
public NntpClient(string hostname, int port)
{
this.tcpClient = new TcpClient(hostname, port);
}
public void Dispose()
{
// Should we implement like this or leave away the try-catch?
try
{
this.tcpClient.Close(); // Let's assume that this might throw
}
catch
{
}
}
}
``` | I would argue that swallowing is the lesser of the two evils in this scenario, as it is better to raise the *original* `Exception` - caveat: **unless**, perhaps the failure to cleanly dispose is itself pretty darned critical (perhaps if a `TransactionScope` couldn't dispose, since that could indicate a rollback failure).
See [here](http://marcgravell.blogspot.com/2008/11/dontdontuse-using.html) for more thoughts on this - including a wrapper/extension method idea:
```
using(var foo = GetDodgyDisposableObject().Wrap()) {
foo.BaseObject.SomeMethod();
foo.BaseObject.SomeOtherMethod(); // etc
} // now exits properly even if Dispose() throws
```
Of course, you could also do some oddity where you re-throw a composite exception with both the original and second (`Dispose()`) exception - but think: you could have multiple `using` blocks... it would quickly become unmanageable. In reality, the original exception is the interesting one. | The [*Framework Design Guidelines*](https://rads.stackoverflow.com/amzn/click/com/0321545613) (2nd ed) has this as (§9.4.1):
> **AVOID** throwing an exception from within Dispose(bool) except under critical
> situations where the containing process has been corrupted (leaks, inconsistent
> shared state, etc.).
Commentary [Edit]:
* There are guidelines, not hard rules. And this is an "AVOID" not a "DO NOT" guideline. As noted (in comments) the Framework breaks this (and other) guidelines in places. The trick is knowing when to break a guideline. That, in many ways, is the difference between a Journeyman and a Master.
* If some part of the clean-up could fail then should provide a Close method that will throw exceptions so the caller can handle them.
* If you are following the dispose pattern (and you should be if the type directly contains some unmanaged resource) then the `Dispose(bool)` may be called from the finaliser, throwing from a finaliser is a bad idea and will block other objects from being finalised.
*My* view: exceptions escaping from Dispose should only be those, as in the guideline, that as sufficiently catastrophic that no further reliable function is possible from the current process. | Should you implement IDisposable.Dispose() so that it never throws? | [
"",
"c#",
".net",
"idisposable",
""
] |
I want to do a query to retrieve the record immediately after a record for any given record, in a result set ordered by list. I do not understand how to make use of the limit keyword in sql syntax to do this.
I can use WHERE primarykey = number, but how will limiting the result help when I will only have one result?
How would I obtain the next record with an arbitrary primary key number?
I have an arbitrary primary key, and want to select the next one ordered by date. | Might be as simple as:
```
select *
from mytable
where datecolumn > (select datecolumn from mytable where id = @id)
order by datecolumn
limit 1
```
(Edited after comments) | This will emulate the `LEAD()` analytic function (i. e. select the next value for each row from the table)
```
SELECT mo.id, mo.date,
mi.id AS next_id, mi.date AS next_date
FROM (
SELECT mn.id, mn.date,
(
SELECT id
FROM mytable mp
WHERE (mp.date, mp.id) > (mn.date, mn.id)
ORDER BY
mp.date, mp.id
LIMIT 1
) AS nid
FROM mytable mn
ORDER BY
date
) mo,
mytable mi
WHERE mi.id = mo.nid
```
If you just want to select next row for a given ID, you may use:
```
SELECT *
FROM mytable
WHERE (date, id) >
(
SELECT date, id
FROM mytable
WHERE id = @myid
)
ORDER BY
date, id
LIMIT 1
```
This will work most efficiently if you have an index on `(date, id)` | selecting subsequent records arbitrarily with limit | [
"",
"sql",
"mysql",
""
] |
Here's what I'm trying to do.
* When the 'Submit' form is clicked on my form, a javascript function will loop through all the fields of the form.
* For each field a function will be called which would return `true`/`false` to indicate if it was filled in correctly or not.
* If a `false` is returned, it shows an error message next to that field.
* If all fields are correct, it submits the form. If not, it doesn't submit.
Here's the tricky part. While most of the validation is being done via javascript, the username and email need to be validated via ajax to see if the username/email is already in use or not.
The structure i'm currently using for this ajax function is something similar to this:
```
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
```
But that currently doesn't work.
What can I do to make it work, i.e can I stop the validateSomething() function from returning a value until its set to true/false by the inner function?
Would something like this work:
```
function validateSomething()
{
var valid="unset";
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
//Loop without returning until valid is set to true or false
while (valid=='unset')
{
//Do nothing?
}
return valid/
}
``` | You can force the ajax-call to wait with async: false.
Like this using jquery:
```
function validateSomething() {
var valid;
$.ajax({
url: "something.php",
data: {x: y},
type: "GET",
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
valid= response.valid;
}
});
return valid;
}
```
However, the big win when using AJAX is that it is asynchronous. This synchronous call might lock up the browser while it is waiting for the server. | You probably don't want to. (Or more appropriately, "Go for it, but be careful when doing so.")
Validating via AJAX is hip and slick and awesome. But it is -not- a substitute for validating server-side. And AJAx validation is -not- server-side validation. I can take the return of your function that says false and flip it to true and submit the form happily, even though you checked to make sure the username wasn't taken 'on the server'. Javascript runs on the client and can't be trusted.
Any validation you do via an AJAX call must be re-done on the server when you actually submit the form.
If you do that, then yea, AJAX validation is, again, hip and slick and awesome. So go for it. To submit a form using javascript (e.g. in the AJAX call-back handler function) you would say:
```
if(formwasValid)
{
document.getElementById('idOfForm').submit();
$('#idOfForm').submit(); //jQuery
}
else
{
alert('Invalid text');
}
``` | Validating and Submitting a form using Javascript + Ajax | [
"",
"javascript",
"ajax",
"asynchronous",
""
] |
I am looking for an elegant way to get the OS version like: "Windows XP Professional Service Pack 1" or "Windows Server 2008 Standard Edition" etc.
Is there an elegant way of doing that?
I am also interested in the processor architecture (like x86 or x64). | You can use WMI to get the product name ("Microsoft® Windows Server® 2008 Enterprise "):
```
using System.Management;
var name = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";
``` | You should really try to avoid WMI for local use. It is very convenient but you pay dearly for it in terms of performance. This is quick and simple:
```
public string HKLM_GetString(string path, string key)
{
try
{
RegistryKey rk = Registry.LocalMachine.OpenSubKey(path);
if (rk == null) return "";
return (string)rk.GetValue(key);
}
catch { return ""; }
}
public string FriendlyName()
{
string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
string CSDVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");
if (ProductName != "")
{
return (ProductName.StartsWith("Microsoft") ? "" : "Microsoft ") + ProductName +
(CSDVersion != "" ? " " + CSDVersion : "");
}
return "";
}
``` | How to get the "friendly" OS Version Name? | [
"",
"c#",
".net",
"winforms",
"operating-system",
""
] |
There are a lot of Java embedded VMs. What do you suggest for ARM development?
* <http://www.cacaovm.org/>
* <http://www.rtjcom.com/main.php?p=home>
* <http://www.k-embedded-java.com/>
* <http://jamvm.sourceforge.net/>
I'm currently using the [TINI](http://en.wikipedia.org/wiki/Tiny_Internet_Interface) platform from Dallas and works great (512 KB RAM and 1 MB flash), but now I need more power (memory and CPU). | My final choice is JamVM + GNU Classpath. Works great! :) | 4 different VMs have been ported to Symbian OS, which runs on ARM cpus.
Sun's KVM, Sun's hotspot (or cldc-hi) VM, Sun's CDC VM and IBM J9 VM.
I suspect there are several more.
a good place to start your research would be the list of JavaME licensees:
<http://java.sun.com/javame/licensees/index.jsp> | What Java embedded VM do you suggest for ARM development? | [
"",
"java",
"embedded",
"arm",
""
] |
Have you used any profiling tool like Intel Vtune analyzer?
What are your recommendations for a C++ multi threaded application on Linux and windows? I am primarily interested in cache misses, memory usage, memory leaks and CPU usage.
I use valgrind (only on UNIX), but mainly for finding memory errors and leaks. | Following are the good tools for multithreaded applications. You can try evaluation copy.
1. Runtime sanity check tool
* Thread Checker -- Intel Thread checker / VTune, [here](https://software.intel.com/en-us/articles/intel-thread-checker-documentation)
2. Memory consistency-check tools (memory usage, memory leaks)
- Memory Validator, [here](http://www.softwareverify.com/cpp/memory/index.html)
3. Performance Analysis. (CPU usage)
- AQTime , [here](http://www.softpedia.com/get/Programming/Other-Programming-Files/AQtime.shtml)
**EDIT**: Intel thread checker can be used to diagnose Data races, Deadlocks, Stalled threads, abandoned locks etc. Please have lots of patience in analyzing the results as it is easy to get confused.
Few tips:
1. Disable the features that are not required.(In case of identifying deadlocks, data race can be disabled and vice versa.)
2. Use Instrumentation level based on your need. Levels like "All Function" and "Full Image" are used for data races, where as "API Imports" can be used for deadlock detection)
3. use context sensitive menu "Diagnostic Help" often. | On Linux, try [oprofile](http://oprofile.sourceforge.net/).
It supports various performance counters.
On Windows, AMD's [CodeAnalyst](http://developer.amd.com/CPU/CODEANALYST/Pages/default.aspx) (free, unlike VTune) is worth a look.
It only supports event profiling on AMD hardware though
(on Intel CPUs it's just a handy timer-based profiler).
A colleague recently tried [Intel Parallel Studio](http://software.intel.com/en-us/intel-parallel-studio-home/) (beta) and rated it favourably
(it found some interesting parallelism-related issues in some code). | Profiling C++ multi-threaded applications | [
"",
"c++",
"performance",
"multithreading",
"profiling",
""
] |
This might be a stupid question, but is there any common practice for initializing collection properties for a user, so they don't have to new up a new concrete collection before using it in a class?
Are any of these preferred over the other?
Option 1:
```
public class StringHolderNotInitialized
{
// Force user to assign an object to MyStrings before using
public IList<string> MyStrings { get; set; }
}
```
Option 2:
```
public class StringHolderInitializedRightAway
{
// Initialize a default concrete object at construction
private IList<string> myStrings = new List<string>();
public IList<string> MyStrings
{
get { return myStrings; }
set { myStrings = value; }
}
}
```
Option 3:
```
public class StringHolderLazyInitialized
{
private IList<string> myStrings = null;
public IList<string> MyStrings
{
// If user hasn't set a collection, create one now
// (forces a null check each time, but doesn't create object if it's never used)
get
{
if (myStrings == null)
{
myStrings = new List<string>();
}
return myStrings;
}
set
{
myStrings = value;
}
}
}
```
Option 4:
Any other good options for this? | In this case, I don't see the reason for the lazy loading, so I would go with option 2. If you are creating a ton of these objects, then the number of allocations and GCs that result would be an issue, but that's not something to consider really unless it proves to be a problem later.
Additionally, for things like this, I would typically not allow the assignment of the IList to the class. I would make this read-only. In not controlling the implementation of the IList, you open yourself up to unexpected implementations. | For Option 1: if you want to force user to initialize something before using your class then best place to force it is in constructor.
For Option 2: If you're not forcing the user then you really have to initialize an empty collection yourself in the constructor/initializer.
For Option 3: Lazy initialization only makes sense if it involves too much work or its a slow/bulky operation.
My vote goes for option 2. | Initializing a collection so the user doesn't have to | [
"",
"c#",
"collections",
""
] |
I am writing an app to discover what features exist on a pc. The user would go to a web page, download the app and execute it (with all the appropriate warnings, this is not spyware). The app would use the standard MS api to determine such things as connection speed, installed memory, firewall health, etc. Writing the app is not a problem, I could use Scripting Host, C#, C++, etc. The question is, if I chose C# is there any guarantee that a certain flavor of windows would have .net installed? The target pc is XP SP2 or better and Vista.
Thanks for the help. | Vista does have .NET 3.0 installed. XP SP2 doesn't have any .NET framework installed by default. | You may want to read [Scott Hanselman's](http://www.hanselman.com/blog/) blog post [SmallestDotNet: On the Size of the .NET Framework](http://www.hanselman.com/blog/SmallestDotNetOnTheSizeOfTheNETFramework.aspx), specifically the `What's the "Client Profile?"` section:
> The Client Profile is an even smaller
> install option for .NET 3.5 SP1 on XP.
> It's [small 277k bootstrapper](http://www.microsoft.com/downloads/details.aspx?FamilyId=8CEA6CD1-15BC-4664-B27D-8CEBA808B28B&displaylang=en). When
> it's run on a Windows XP SP2 machines
> with no .NET Framework installed, it
> will download a 28 meg payload and
> give you a client-specific subset of
> .NET 3.5. If the Client Profile
> bootstrapper is run on a machine with
> any version of .NET on it, it'll act
> the same as the 3.5 SP1 web installer
> and detect what it needs to download,
> then go get it. There's more details
> in the [Client Profile Deployment Guide](http://download.microsoft.com/download/5/a/a/5aa86d6c-969b-42d8-bc6b-30e02bfeccf0/NETFXClientProfile_DeploymentGuide.htm). | Which versions of .NET Framework I can count on? | [
"",
"c#",
".net",
""
] |
In C# code, I have three objects **A**, **B** and **C**. **A** and **B** each hold a reference to **C**. When **A** is destroyed I would like the reference from **B** to **C** to be deleted as well so that **C** can be destroyed by the Garbage Collector.
Is there a way to do this without deleting it manually from **B**? (The destructor in **C** is not called before the reference from **B** to **C** is deleted, so it is not effective here.) | **Solution 1**
Is B referenced from anywhere else in you application?
If B is only accessable through A, then B and C will be "removed" when A is "removed".
**Solution 2**
You should send a signal to B when A is "removed". If B is known to A you can signal B from A. I would use an [IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) pattern for this
**Solution 3**
Instead of directly referencing C from B, you can use a WeakReference from B to get to C. | It smells like a job for a [WeakReference](http://msdn.microsoft.com/en-us/library/system.weakreference.aspx):
> A weak reference allows the garbage
> collector to collect an object while
> still allowing an application to
> access the object. If you need the
> object, you can still obtain a strong
> reference to it and prevent it from
> being collected.
Sounds like you should refer from B to C via a WeakReference, instead of directly. | Garbage collector problem in C# | [
"",
"c#",
"garbage-collection",
""
] |
[Edit 2: More information and debugging in answer below...]
I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing solutions? Let's just say the restrictions aren't of a technical nature).
I've successfully exported the full contents and structure of the database using ADO and ADOX via the comtypes library, but I'm getting a problem re-importing the data.
I'm exporting the contents of each table into a text file with a list on each line, like so:
```
[-9, u'No reply']
[1, u'My home is as clean and comfortable as I want']
[2, u'My home could be more clean or comfortable than it is']
[3, u'My home is not at all clean or comfortable']
```
And the following function to import the said file:
```
import os
import sys
import datetime
import comtypes.client as client
from ADOconsts import *
from access_consts import *
class Db:
def create_table_contents(self, verbosity = 0):
conn = client.CreateObject("ADODB.Connection")
rs = client.CreateObject("ADODB.Recordset")
conn.ConnectionString = self.new_con_string
conn.Open()
for fname in os.listdir(self.file_path):
if fname.startswith("Table_"):
tname = fname[6:-4]
if verbosity > 0:
print "Filling table %s." % tname
conn.Execute("DELETE * FROM [%s];" % tname)
rs.Open("SELECT * FROM [%s];" % tname, conn,
adOpenDynamic, adLockOptimistic)
f = open(self.file_path + os.path.sep + fname, "r")
data = f.readline()
print repr(data)
while data != '':
data = eval(data.strip())
print data[0]
print rs.Fields.Count
rs.AddNew()
for i in range(rs.Fields.Count):
if verbosity > 1:
print "Into field %s (type %s) insert value %s." % (
rs.Fields[i].Name, str(rs.Fields[i].Type),
data[i])
rs.Fields[i].Value = data[i]
data = f.readline()
print repr(data)
rs.Update()
rs.Close()
conn.Close()
```
Everything works fine except that numerical values (double and int) are being inserted as zeros. Any ideas on whether the problem is with my code, eval, comtypes, or ADO?
Edit: I've fixed the problem with inserting numbers - casting them as strings(!) seems to solve the problem for both double and integer fields.
However, I now have a different issue that had previously been obscured by the above: the first field in every row is being set to 0 regardless of data type... Any ideas? | And found an answer.
```
rs = client.CreateObject("ADODB.Recordset")
```
Needs to be:
```
rs = client.CreateObject("ADODB.Recordset", dynamic=True)
```
Now I just need to look into why. Just hope this question saves someone else a few hours... | Is `data[i]` being treated as a string? What happens if you specifically cast it as a int/double when you set `rs.Fields[i].Value`?
Also, what happens when you print out the contents of `rs.Fields[i].Value` after it is set? | Problem Inserting data into MS Access database using ADO via Python | [
"",
"python",
"ms-access",
"ado",
"comtypes",
""
] |
I'm from a Java school, but I'd like to get my hands dirty in C/C++ development as well. Can you suggest:
1. a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download)
2. a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download)
3. should I use GCC or other compilers?
Thanks a lot guys! | > 1) a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download)
[Eclipse with CDT](http://www.eclipse.org/cdt/) (~40 MB download) or [Visual Studio 2008 Express](http://www.microsoft.com/Express/) edition (2.6 MB download for installer and then tons of stuff that it'll pull from the net) -- it's free. Also, get the SP1. But, I still suggest that you take a look at Visual Studio.
> 2) a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download)
[Eclipse with CDT](http://www.eclipse.org/cdt/) (~40 MB download) or Visual Studio 2008 Professional (if you are going to pay).
> 3) should I use GCC or other compilers?
Yes and no. Depends on your needs. GNU g++ is great to get started with. However, hooking up with CDT may prove to be difficult.
If you intend to do professional Windows programming in near future, it is best to buy the Visual Studio 2008 Pro (and install SP1) and get used to it. | If you have to do it in Vista and if it is Microsoft platform-specific, then there is no better full-blown IDE than Visual Studio. You can download Visual Studio Express Edition for C++ development as a lighter IDE (Not that light though but it is free). Eclipse with GCC works great as well if you want to go cross-platform. | C/C++ Programming in Vista | [
"",
"c++",
"c",
"ide",
"windows-vista",
""
] |
I'm working from an example piece of code that allocates a relatively large local array. (32768 to be precise) When I try the same I'm getting behaviour that appears to be a stack overflow. Now I was wondering if my example has maybe set the stack to be larger then my application. Is this possible? if so how? | With the Microsoft compiler you can use [/F](https://learn.microsoft.com/en-us/cpp/build/reference/f-set-stack-size?view=msvc-160) to set the stack size, however it seems like you should just allocate the object on the heap. You should have a reason you're allocating this on the stack rather than the heap.
Edit: [This page](http://www.cs.nyu.edu/exact/core/doc/stackOverflow.txt) gives a good cross-platform breakdown, though it may be dated. | You can use the /F compiler flag to set the default stack size, or specify it as the second parameter to the [CreateThread](http://msdn.microsoft.com/en-us/library/ms682453(VS.85).aspx) function. | Can you set the size of the call stack in c++? (vs2008) | [
"",
"c++",
"callstack",
""
] |
I need to read ~50 files on every server start and place each text file's representation into memory. Each text file will have its own string (which is the best type to use for the string holder?).
What is the fastest way to read the files into memory, and what is the best data structure/type to hold the text in so that I can manipulate it in memory (search and replace mainly)?
Thanks | A memory mapped file will be fastest... something like this:
```
final File file;
final FileChannel channel;
final MappedByteBuffer buffer;
file = new File(fileName);
fin = new FileInputStream(file);
channel = fin.getChannel();
buffer = channel.map(MapMode.READ_ONLY, 0, file.length());
```
and then proceed to read from the byte buffer.
This will be significantly faster than `FileInputStream` or `FileReader`.
EDIT:
After a bit of investigation with this it turns out that, depending on your OS, you might be better off using a new `BufferedInputStream(new FileInputStream(file))` instead. However reading the whole thing all at once into a char[] the size of the file sounds like the worst way.
So `BufferedInputStream` should give roughly consistent performance on all platforms, while the memory mapped file may be slow or fast depending on the underlying OS. As with everything that is performance critical you should test your code and see what works best.
EDIT:
Ok here are some tests (the first one is done twice to get the files into the disk cache).
I ran it on the rt.jar class files, extracted to the hard drive, this is under Windows 7 beta x64. That is 16784 files with a total of 94,706,637 bytes.
First the results...
(remember the first is repeated to get the disk cache setup)
* ArrayTest
+ time = 83016
+ bytes = 118641472
* ArrayTest
+ time = 46570
+ bytes = 118641472
* DataInputByteAtATime
+ time = 74735
+ bytes = 118641472
* DataInputReadFully
+ time = 8953
+ bytes = 118641472
* MemoryMapped
+ time = 2320
+ bytes = 118641472
Here is the code...
```
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.HashSet;
import java.util.Set;
public class Main
{
public static void main(final String[] argv)
{
ArrayTest.main(argv);
ArrayTest.main(argv);
DataInputByteAtATime.main(argv);
DataInputReadFully.main(argv);
MemoryMapped.main(argv);
}
}
abstract class Test
{
public final void run(final File root)
{
final Set<File> files;
final long size;
final long start;
final long end;
final long total;
files = new HashSet<File>();
getFiles(root, files);
start = System.currentTimeMillis();
size = readFiles(files);
end = System.currentTimeMillis();
total = end - start;
System.out.println(getClass().getName());
System.out.println("time = " + total);
System.out.println("bytes = " + size);
}
private void getFiles(final File dir,
final Set<File> files)
{
final File[] childeren;
childeren = dir.listFiles();
for(final File child : childeren)
{
if(child.isFile())
{
files.add(child);
}
else
{
getFiles(child, files);
}
}
}
private long readFiles(final Set<File> files)
{
long size;
size = 0;
for(final File file : files)
{
size += readFile(file);
}
return (size);
}
protected abstract long readFile(File file);
}
class ArrayTest
extends Test
{
public static void main(final String[] argv)
{
final Test test;
test = new ArrayTest();
test.run(new File(argv[0]));
}
protected long readFile(final File file)
{
InputStream stream;
stream = null;
try
{
final byte[] data;
int soFar;
int sum;
stream = new BufferedInputStream(new FileInputStream(file));
data = new byte[(int)file.length()];
soFar = 0;
do
{
soFar += stream.read(data, soFar, data.length - soFar);
}
while(soFar != data.length);
sum = 0;
for(final byte b : data)
{
sum += b;
}
return (sum);
}
catch(final IOException ex)
{
ex.printStackTrace();
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
return (0);
}
}
class DataInputByteAtATime
extends Test
{
public static void main(final String[] argv)
{
final Test test;
test = new DataInputByteAtATime();
test.run(new File(argv[0]));
}
protected long readFile(final File file)
{
DataInputStream stream;
stream = null;
try
{
final int fileSize;
int sum;
stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
fileSize = (int)file.length();
sum = 0;
for(int i = 0; i < fileSize; i++)
{
sum += stream.readByte();
}
return (sum);
}
catch(final IOException ex)
{
ex.printStackTrace();
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
return (0);
}
}
class DataInputReadFully
extends Test
{
public static void main(final String[] argv)
{
final Test test;
test = new DataInputReadFully();
test.run(new File(argv[0]));
}
protected long readFile(final File file)
{
DataInputStream stream;
stream = null;
try
{
final byte[] data;
int sum;
stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
data = new byte[(int)file.length()];
stream.readFully(data);
sum = 0;
for(final byte b : data)
{
sum += b;
}
return (sum);
}
catch(final IOException ex)
{
ex.printStackTrace();
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
return (0);
}
}
class DataInputReadInChunks
extends Test
{
public static void main(final String[] argv)
{
final Test test;
test = new DataInputReadInChunks();
test.run(new File(argv[0]));
}
protected long readFile(final File file)
{
DataInputStream stream;
stream = null;
try
{
final byte[] data;
int size;
final int fileSize;
int sum;
stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
fileSize = (int)file.length();
data = new byte[512];
size = 0;
sum = 0;
do
{
size += stream.read(data);
sum = 0;
for(int i = 0; i < size; i++)
{
sum += data[i];
}
}
while(size != fileSize);
return (sum);
}
catch(final IOException ex)
{
ex.printStackTrace();
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
return (0);
}
}
class MemoryMapped
extends Test
{
public static void main(final String[] argv)
{
final Test test;
test = new MemoryMapped();
test.run(new File(argv[0]));
}
protected long readFile(final File file)
{
FileInputStream stream;
stream = null;
try
{
final FileChannel channel;
final MappedByteBuffer buffer;
final int fileSize;
int sum;
stream = new FileInputStream(file);
channel = stream.getChannel();
buffer = channel.map(MapMode.READ_ONLY, 0, file.length());
fileSize = (int)file.length();
sum = 0;
for(int i = 0; i < fileSize; i++)
{
sum += buffer.get();
}
return (sum);
}
catch(final IOException ex)
{
ex.printStackTrace();
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
return (0);
}
}
``` | The most efficient way is:
* Determine the length of the file (`File.length()`)
* Create a char buffer with the same size (or slightly larger)
* Determine the *encoding* of the file
* Use `new InputStreamReader (new FileInputStream(file), encoding)` to read
* Read the while file into the buffer with a single call to read(). Note that read() might return early (not having read the whole file). In that case, call it again with an offset to read the next batch.
* Create the string: `new String(buffer)`
If you need to search&replace once at startup, use String.replaceAll().
If you need to do it repeatedly, you may consider using StringBuilder. It has no replaceAll() but you can use it to manipulate the character array in place (-> no allocation of memory).
That said:
1. Make your code as short and simple as possible.
2. Measure the performance
3. It it's too slow, fix it.
There is no reason to waste a lot of time into making this code run fast if it takes just 0.1s to execute.
If you still have a performance problem, consider to put all the text files into a JAR, add it into the classpath and use Class.getResourceAsStream() to read the files. Loading things from the Java classpath is highly optimized. | What is the fastest way to read a large number of small files into memory? | [
"",
"java",
"performance",
"file",
"types",
"io",
""
] |
Code that not affecting the collection needs Mutual Exclusion
```
List<string> _itemColection = new List<string>();
object _criticalSection = new object();
private void Add(string item)
{
lock (_criticalSection)
{
_itemColection.Add(item);
}
}
private void Remove(string item)
{
lock (_criticalSection)
{
_itemColection.Remove(item);
}
}
private void GetCount()
{
///Is it lock is reuired here?
return _itemColection.Count;
}
//Thread method
private void Run()
{
lock (_criticalSection)
{
foreach (string item in _itemColection)
{
///Some operation
}
}
}
```
Is it Mutex is required in GetCount() method. The collection value's are not changed | Yes, you should lock there. You're requesting access to shared data, and if you don't have some sort of memory barrier there'll be no guarantee that it'll be "fresh" information. The memory model can be a real mind-bender sometimes :)
In addition, while I'd *expect* `List<T>.Count` to be a pretty simple operation, it could *theoretically* be complicated - and if another thread is mutating stuff (e.g. adding an item, which then requires a buffer expansion) while it's working out the count, you could *theoretically* run into trouble.
Basically, unless a type *claims* to be thread-safe for your particular scenario, I'd always make sure you don't perform two operations on it at the same time. | In practise its probably not needed, but I would include it myself to be on the safe side. \_itemCollection.Count is a property, so effectively you are calling a function on the collection, and you have no guarantee what this function is doing. | Mutual Exclusion Required | [
"",
"c#",
""
] |
I'm looking for an ORM that offers complete or near-complete LINQ support.
LINQ to SQL
- Supports about everything inside of LINQ (.Contains, Math.Log, etc)
- Cannot eager load relationship properties without creating a new datacontext
ADO.NET Entity Framework
- Terrible LINQ support (lots of missing features).
- Great mapping features
- Can eager load on demand with .Include methods on an ObjectQuery<>
LightSpeed
- Great LINQ support missing some features (.Contains within a Where)
- Some of the SQL generated is very inefficient.
None of these seem to fit just perfectly, I honestly wish I could take bits and pieces from each. I personally really like ADO.NET EF except the features it is missing make it just frustrating to use.
I know some people praise NHibernate up and down and I'm not knocking it but I spent today trying it out and it's ok but it's LINQ support is not that great. | NHibernate with Linq to NHibernate | Try DataObjects.NET.
I'm one of the DO developers. And my latest activity within that project is to implement LINQ for DataObjects. So I could describe it briefly:
* Supports almost all LINQ methods except Last/LastOrDefault/Aggregate/Reverse/TakeWhile/SkipWhile etc. and methods that has .NET specific arguments - such as IComparer (nobody supports them).
* Almost all string and Math methods supported (and you have ability to write your own function mappings!).
* Complex scenarios with GroupBy\SelectMany\Contains\Single\etc. in subqueries and correlated subqueries are supported.
We have about 1000 tests of LINQ implementation and 99% of them are passed. So I can say that current implementation is close to EF. Some methods do not work with EF, some with our framework.
Check this brief description <http://www.x-tensive.com/Products/DO/>. | Most complete ORM with LINQ support? | [
"",
"sql",
"linq-to-sql",
"orm",
""
] |
I use C# and SQL Server 2005 and I need a recommendation on how to populate my objects.
I have a Customers collection containing a collection of customer objects. Each customer object contains a Orders collection, containing a collection of orders.
I use a public Fetch() method on my Customers collection to populate the customers and their orders.
You can only have one DataReader open per connection, right. So that would mean that I need one connection for the 'SELECT \* Customers' reader, and while I iterate through the customers reader I would need another connection for each 'SELECT \* Orders WHERE CustomerId\_fk = @Id'.
My question : Would you recommend I use the above way or just plain DataSets ?
EDIT
I had 'SELECT \* Customers WHERE Id = @Id' Instead of 'SELECT \* Customers'. | Actually, your assertion ("You can only have one DataReader open per connection") is incorrect; you can [enable MARS](http://msdn.microsoft.com/en-us/library/h32h3abf(VS.80).aspx) (Multiple Active Result Sets) via a tweak to the connection string, and job done; except of course that you'll still have lots of round-trips (n+1).
I also don't think that the immediate alternative is datasets. Personally, I'd use two result grids (either from a single query or 2 queries) and stitch them together back at the caller.
Alternatively, use something like LINQ-to-SQL with `LoadWith<Customer>(c=>c.Orders);` (`DataLoadOptions`). Even without `LoadWith`, it'll do the same n+1 behaviour automatically simply by loading the collection for each `Customer` (navigation properties are loaded lazily by default). | I would probably use a SqlDataAdapter to query both in one pass into a DataSet. Something like this:
```
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM CUSTOMERS WHERE CustomerId = @id; SELECT * FROM ORDERS WHERE CustomerId = @id",connection);
adapter.Fill(dataSet);
```
Then, I'd set up the relation using something like this:
```
dataSet.Relations.Add(new DataRelation("relationName", dataSet.Tables[0].Columns["CustomerId"], dataSet.Tables[1].Columns["CustomerId"]);
```
This way, you only open one connection, you query all the data, and then set up the relationship in memory. | C# multiple connections vs Dataset | [
"",
"c#",
"database",
""
] |
I want to record the time using `System.currentTimeMillis()` when a user begins something in my program. When he finishes, I will subtract the current `System.currentTimeMillis()` from the `start` variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.
What's the best way to do this? | Use the [`java.util.concurrent.TimeUnit`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html#toMinutes(long)) class:
```
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
```
Note: `TimeUnit` is part of the Java 1.5 specification, but `toMinutes` was added as of Java 1.6.
To add a leading zero for values 0-9, just do:
```
String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
```
If `TimeUnit` or `toMinutes` are unsupported (such as on Android before API version 9), use the following equations:
```
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...
``` | Based on @siddhadev's answer, I wrote a function which converts milliseconds to a formatted string:
```
/**
* Convert a millisecond duration to a string format
*
* @param millis A duration to convert to a string form
* @return A string of the form "X Days Y Hours Z Minutes A Seconds".
*/
public static String getDurationBreakdown(long millis) {
if(millis < 0) {
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
return(sb.toString());
}
``` | How to convert Milliseconds to "X mins, x seconds" in Java? | [
"",
"java",
"time",
""
] |
I am having trouble when removing an item from a list. The list is defined in a superclass, but the Hibernate annotations are applied to property accessors in a subclass. There are two methods in the superclass that manipulate the list. The "add" method works fine, but the "remove" does not persist changes. I have checked my Cascade settings, and I seem to have things correct. Am I doing something that is impossible. If not, am I doing something incorrectly?
Here are my classes:
```
@Entity
abstract class Temporal<T> {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version = null;
@Transient
protected List<T> content = new ArrayList<T>();
public void remove(T value) {
// business logic ...
content.remove(value);
}
public void add(T value) {
// business logic ...
content.add(value);
}
}
@Entity
@AccessType("property")
class TemporalAsset extends Temporal<Asset> {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "temporal")
public List<Asset> getContent() {
return super.content;
}
protected void setContent(List<Asset> list) {
super.content = list;
}
}
```
I use an instance of the TemporalAsset class as follows (note that I am only use the "refresh" method to demonstrate the behavior. The list does not persist correctly even if I flush or close the session and open a new session):
```
temporalAsset.add(value1);
temporalAsset.getContent().size() == 1; // true
session.update(temporalAsset);
session.refresh(temporalAsset);
temporalAsset.getContent().size() == 1; // true
temporalAsset.remove(value1);
temporalAsset.getContent().size() == 0; // true
session.update(temporalAsset);
session.refresh(temporalAsset);
temporalAsset.getContent().size() == 0; // false, its 1
```
Thanks. | You have to explicitly specify cascade as CascadeType.DELETE\_ORPHAN.
Try to change code to
```
@OneToMany
@Cascade(cascade = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}, mappedBy = "temporal")
```
Part from hibernate [docs](http://www.hibernate.org/hib_docs/entitymanager/reference/en/html/objectstate.html):
> If the child object's lifespan is
> bounded by the lifespan of the parent
> object, make the parent a full
> lifecycle object by specifying
> CascadeType.ALL and
> org.hibernate.annotations.CascadeType.DELETE\_ORPHAN
> (please refer to the Hibernate
> reference guide for the semantics of
> orphan delete) | This is the currently recommended way.
```
@OneToMany(mappedBy = "temporal", orphanRemoval = true, cascade = CascadeType.ALL)
``` | Hibernate: Removing item from a List does not persist | [
"",
"java",
"hibernate",
""
] |
I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.
I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.
Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.
**Ed** Removed the word 'interface' to avoid confusion. | No, there is no language support for this in C#. There are two workarounds that I can think of immediately:
* use reflection at runtime; crossed fingers and hope...
* use a singleton / default-instance / similar to implement an interface that declares the methods
(**update**)
Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my [generic operators](https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html) code works - it *hopes* you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time. | No. Basically it sounds like you're after a sort of "static polymorphism". That doesn't exist in C#, although I've suggested a sort of ["static interface" notion which could be useful in terms of generics](http://codeblog.jonskeet.uk/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces/).
One thing you *could* do is write a simple unit test to verify that all of the types in a particular assembly obey your rules. If other developers will also be implementing the interface, you could put that test code into some common place so that everyone implementing the interface can easily test their own assemblies. | Is there a way to force a C# class to implement certain static functions? | [
"",
"c#",
".net",
"interface",
"static-methods",
""
] |
The question pretty much already says everything.
I'm starting to add some features to my [weekend project](http://www.my-clock.net). It's a small app for me and a couple of friends, as we're exchange students it's kinda useful for us.
But the thing is the following, I'm doing this in php and structuring everything with includes so i can get the code separated. Some of these pieces of code are dependent on javascripts snipets, so how bad is it to put a javascript in the middle of the body? Or should i just make double includes so the javascript stays in the header? | It's not bad at all.
[It's actually considered good practice to put your script tags as late as possible in the page](http://developer.yahoo.com/performance/rules.html#js_bottom). | It is perfectly fine to place Javascript into the body. There is even such a thing as "inline" Javascript. Just don't overdo it. If you can package your scripts into a separate file (which is not always possible), it will make your code more maintainable. | How bad is it to put javascript outside of the header? | [
"",
"javascript",
"design-patterns",
"coding-style",
""
] |
I'd like to create a data table given a List using the CopyToDataTable method available in DataTableExtensions. I've previously asked the question [How do I transform a List into a DataSet?](https://stackoverflow.com/questions/523153/how-do-i-transform-a-listt-into-a-dataset) and got an [exceptional answer](https://stackoverflow.com/questions/523153/how-do-i-transform-a-listt-into-a-dataset/523168#523168) from [CMS](https://stackoverflow.com/users/5445/cms) which was to achieve what I wanted by creating an extension `public static DataTable ToDataTable<T>(this IEnumerable<T> collection)`
I've been using what he suggested...but recently I've [seen in a blog](http://www.danielmoth.com/Blog/2007/07/linq-to-dataset.html) that there already exists such an extension... `CopyToDataTable<T>(this IEnumerable<T> source) : DataTable` which exists in System.Data.DataTableExtensions.
As a result, I figure I should switch over to using this inbuilt extension method instead of using one that I'd have to maintain myself.
Unfortunately, I'm having a bit of trouble figuring out how to use it.
I can take my IList and say myListofMyClass.CopyToDataTable() but I get a compile error that says "The type 'MyClass' must be convertible to 'System.Data.DataRow' in order to use it as parameter 'T' in the generic method..."
Is there something special I need to do MyClass in order to make it convertible to System.Data.DataRow? Is there some interface I need to implement? | See this link:
<http://blogs.msdn.com/aconrad/archive/2007/09/07/science-project.aspx>
Basically, it did used to be part of Linq, but for some reason it was removed. His method there does work great though, so check it out. | Alas, for `CopyToDataTable`, `T` must be `DataRow` (or a type derived from `DataRow`).
(See [the MSDN documentation](http://msdn.microsoft.com/en-us/library/bb396189.aspx) for more information.) | How do I use System.Data.DataTableExtensions' CopyToDataTable method? | [
"",
"c#",
"datatable",
"generic-list",
""
] |
In Unix all disks are exposed as paths in the main filesystem, so `os.walk('/')` would traverse, for example, `/media/cdrom` as well as the primary hard disk, and that is undesirable for some applications.
How do I get an `os.walk` that stays on a single device?
Related:
* [Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?](https://stackoverflow.com/questions/530645/is-there-a-way-to-determine-if-a-subdirectory-is-in-the-same-filesystem-from-pyth/) | From `os.walk` docs:
> When topdown is true, the caller can
> modify the dirnames list in-place
> (perhaps using del or slice
> assignment), and walk() will only
> recurse into the subdirectories whose
> names remain in dirnames; this can be
> used to prune the search
So something like this should work:
```
for root, dirnames, filenames in os.walk(...):
dirnames[:] = [
dir for dir in dirnames
if not os.path.ismount(os.path.join(root, dir))]
...
``` | I think [os.path.ismount](http://docs.python.org/library/os.path.html#os.path.ismount) might work for you. You code might look something like this:
```
import os
import os.path
for root, dirs, files in os.walk('/'):
# Handle files.
dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)),
dirs)
```
You may also find [this answer](https://stackoverflow.com/questions/571850/adding-elements-to-python-generators) helpful in building your solution.
\*Thanks for the comments on filtering `dirs` correctly. | How do I prevent Python's os.walk from walking across mount points? | [
"",
"python",
"linux",
"unix",
""
] |
I'm having a hard time dealing with a Java garbage collection problem, and interpreting the logs.
My application requires that no GC takes longer than 2 seconds, and ideally less than 100ms.
Based on some previous advice I'm trying the following command line options:
```
java -XX:MaxGCPauseMillis=100 -XX:NewRatio=9 -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -server -Xmx9g -Xms9g
```
The application has a large amount of long-term stored objects, which are kept in a ConcurrentLinkedHashMap. I'm seeing occasional long pauses, in the worst case up to 10 seconds (this is the second last like of the GC logs below)!
Here is some of the output I'm getting:
```
16938.968: [GC 16938.968: [ParNew: 153343K->17022K(153344K), 7.8608580 secs] 6184328K->6122510K(9420160K) icms_dc=7 , 7.8614100 secs] [Times: user=0.63 sys=0.01, real=7.86 secs]
16947.087: [GC 16947.087: [ParNew: 153342K->17022K(153344K), 7.2604030 secs] 6258830K->6198642K(9420160K) icms_dc=7 , 7.2609780 secs] [Times: user=0.44 sys=0.00, real=7.27 secs]
16954.614: [GC 16954.614: [ParNew: 153342K->17024K(153344K), 8.4307620 secs] 6334962K->6274625K(9420160K) icms_dc=7 , 8.4313150 secs] [Times: user=0.62 sys=0.01, real=8.43 secs]
16963.310: [GC 16963.310: [ParNew: 153344K->17023K(153344K), 6.2588760 secs] 6410945K->6350748K(9420160K) icms_dc=7 , 6.2594290 secs] [Times: user=0.48 sys=0.01, real=6.25 secs]
16969.834: [GC 16969.834: [ParNew: 153343K->17022K(153344K), 6.0274280 secs] 6487068K->6425868K(9420160K) icms_dc=7 , 6.0279830 secs] [Times: user=0.50 sys=0.01, real=6.03 secs]
16976.122: [GC 16976.123: [ParNew: 153342K->17022K(153344K), 11.7774620 secs] 6562188K->6503030K(9420160K) icms_dc=7 , 11.7780180 secs] [Times: user=0.43 sys=0.04, real=11.78 secs]
16988.164: [GC 16988.164: [ParNew: 153342K->17024K(153344K), 10.9477920 secs] 6639350K->6579928K(9420160K) icms_dc=7 , 10.9483440 secs] [Times: user=0.37 sys=0.02, real=10.95 secs]
16999.371: [GC 16999.372: [ParNew: 153344K->17023K(153344K), 9.8828360 secs] 6716248K->6655886K(9420160K) icms_dc=7 , 9.8833940 secs] [Times: user=0.42 sys=0.01, real=9.88 secs]
17009.509: [GC 17009.509: [ParNew: 153343K->17023K(153344K), 5.0699960 secs] 6792206K->6727987K(9420160K) icms_dc=7 , 5.0705660 secs] [Times: user=0.55 sys=0.01, real=5.07 secs]
17014.838: [GC 17014.838: [ParNew: 153343K->17023K(153344K), 6.6411750 secs] 6864307K->6790974K(9420160K) icms_dc=7 , 6.6417400 secs] [Times: user=0.37 sys=0.01, real=6.63 secs]
17021.735: [GC 17021.735: [ParNew: 153343K->17024K(153344K), 8.0545970 secs] 6927294K->6856409K(9420160K) icms_dc=7 , 8.0551790 secs] [Times: user=0.34 sys=0.03, real=8.05 secs]
17030.052: [GC 17030.053: [ParNew: 153344K->17023K(153344K), 7.9756730 secs] 6992729K->6922569K(9420160K) icms_dc=7 , 7.9762530 secs] [Times: user=0.34 sys=0.01, real=7.98 secs]
17038.398: [GC 17038.398: [ParNew: 153343K->17022K(153344K), 12.9613300 secs] 7058889K->6990725K(9420160K) icms_dc=7 , 12.9618850 secs] [Times: user=0.39 sys=0.01, real=12.96 secs]
17051.630: [GC 17051.630: [ParNew: 153342K->17022K(153344K), 6.8942910 secs] 7127045K->7059607K(9420160K) icms_dc=7 , 6.8948380 secs] [Times: user=0.56 sys=0.02, real=6.89 secs]
17058.798: [GC 17058.798: [ParNew: 153342K->17024K(153344K), 10.0262190 secs] 7195927K->7126351K(9420160K) icms_dc=7 , 10.0267860 secs] [Times: user=0.37 sys=0.01, real=10.02 secs]
17069.096: [GC 17069.096: [ParNew: 153344K->17023K(153344K), 10.0419500 secs] 7262671K->7195002K(9420160K) icms_dc=7 , 10.0425020 secs] [Times: user=0.40 sys=0.02, real=10.04 secs]
17079.410: [GC 17079.410: [ParNew: 153343K->17022K(153344K), 13.5389040 secs] 7331322K->7264275K(9420160K) icms_dc=7 , 13.5394610 secs] [Times: user=0.30 sys=0.01, real=13.54 secs]
17093.223: [GC 17093.224: [ParNew: 153342K->17023K(153344K), 10.5909450 secs] 7400595K->7330446K(9420160K) icms_dc=7 , 10.5915060 secs] [Times: user=0.33 sys=0.00, real=10.58 secs]
17104.083: [GC 17104.084: [ParNew: 153343K->17024K(153344K), 5.8420210 secs] 7466766K->7392173K(9420160K) icms_dc=7 , 5.8425920 secs] [Times: user=0.57 sys=0.00, real=5.84 secs]
```
I've spent hours pouring over the various webpages that describe Java GC tuning, but none have really given me the ability to interpret the logs above and come up with a course of action. Any specific advice based on the logs I've provided would be greatly appreciated.
**Update:** Per a question below:
The machine has 16G of RAM, here is the info from top:
Mem: 15483904k total, 15280084k used, 203820k free, 155684k buffers
Swap: 2031608k total, 1347240k used, 684368k free, 3304044k cached
Its a different run, but here is the current top output for the process:
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1016 sanity 17 0 10.2g 6.5g 9464 S 1 44.2 10:24.32 java
```
**Update 2:** Some more detailed logging, this looked like it caused a 400ms delay:
```
{Heap before GC invocations=1331 (full 1):
par new generation total 153344K, used 153343K [0x00002aaaae200000, 0x00002aaab8860000, 0x00002aaab8860000)
eden space 136320K, 100% used [0x00002aaaae200000, 0x00002aaab6720000, 0x00002aaab6720000)
from space 17024K, 99% used [0x00002aaab77c0000, 0x00002aaab885fff0, 0x00002aaab8860000)
to space 17024K, 0% used [0x00002aaab6720000, 0x00002aaab6720000, 0x00002aaab77c0000)
concurrent mark-sweep generation total 7169664K, used 4258496K [0x00002aaab8860000, 0x00002aac6e200000, 0x00002aac6e200000)
concurrent-mark-sweep perm gen total 21248K, used 13269K [0x00002aac6e200000, 0x00002aac6f6c0000, 0x00002aac73600000)
484.738: [GC 484.738: [ParNew: 153343K->17022K(153344K), 0.3950480 secs] 4411840K->4341689K(7323008K), 0.3954820 secs] [Times: user=0.49 sys=0.07, real=0.40 secs]
Heap after GC invocations=1332 (full 1):
par new generation total 153344K, used 17022K [0x00002aaaae200000, 0x00002aaab8860000, 0x00002aaab8860000)
eden space 136320K, 0% used [0x00002aaaae200000, 0x00002aaaae200000, 0x00002aaab6720000)
from space 17024K, 99% used [0x00002aaab6720000, 0x00002aaab77bfb68, 0x00002aaab77c0000)
to space 17024K, 0% used [0x00002aaab77c0000, 0x00002aaab77c0000, 0x00002aaab8860000)
concurrent mark-sweep generation total 7169664K, used 4324666K [0x00002aaab8860000, 0x00002aac6e200000, 0x00002aac6e200000)
concurrent-mark-sweep perm gen total 21248K, used 13269K [0x00002aac6e200000, 0x00002aac6f6c0000, 0x00002aac73600000)
}
``` | Turns out the problem was that the heap was getting swapped out to disk, and the delay was Java's GC having to wait for it to be swapped back in.
Solved (mostly) by setting Linux' "swappiness" parameter to 0. | From the times, it seems the GC actually doesn't run all the time (see the user times), so most of the time, it's waiting.
Just a wild guess: Doesn't it swap? How much memory does the machine have? How much of it does the java process get (resident set size)?
Edit: why is it waiting:
Look at this (from your transcript)
```
[Times: user=0.39 sys=0.01, real=12.96 secs]
```
This means that (I guess from the beginning to the end of GC), 12 (almost 13) seconds passed. Of these 13 seconds, .39 was spent running in user mode, .01 was spent running in kernel mode. If the time collection method isn't totally flawed (ie. the numbers really represent the running time of the GC process/thread), this means at least 12 seconds waiting. | Experiencing occasional long garbage collection delays, why? | [
"",
"java",
"garbage-collection",
""
] |
I have been studying Java for a few months and am now starting to learn C.
I am a little confused, I was under the impression that passing an object by reference and passing a pointer to that object were the same thing: I thought the difference was that in Java all passing of objects is done with pointers automatically, where as in C one has to actually sprinkle little asterisks and ampersands here and there. Recently, in conversation, I was assured that there was a difference!
What is the difference between passing by reference and passing a pointer? | Neither Java *nor* C has pass-by-reference. They are both strictly pass-by-value.
Pass-by-reference semantics mean that when you change the value of the parameter in the method, the caller will see that change in the argument.
Now, you may be thinking: "But that's the case in Java! If I change an object during the method, the caller sees that change." *The object isn't the parameter.* The parameter is *just* the variable - and if you change the value of that variable, the caller won't see that. For example:
```
public void foo(Object x)
{
x = null;
}
public void caller()
{
Object y = new Object();
foo(y);
// y is still not null!
}
```
If the parameter were *really* passed by reference, `y` would be null afterwards. Instead, the value of `y` is just a reference, and that reference is passed by value. It's confusing because the word "reference" is in both terms, but they're different things.
You may want to look at [my article about C# parameter passing](http://pobox.com/~skeet/csharp/parameters.html) to see what would be possible if Java *did* have pass-by-reference semantics, as C# does when (and only when) you use the `ref` keyword.
You may also want to look at the comments to [my Stack Overflow answer](https://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve/423833#423833) related to the topic. | > I thought the difference was that in Java all passing of objects is done with pointers automatically, where as in C one has to actually sprinkle little asterisks and ampersands here and there.
Conceptional, that's quite right. If we are pedantic (and that's a good thing), we can even say objects are not passed at all in Java. What is passed is only ever the "pointer", which in Java is called the reference. All indirection is done automatically. So when you do "objref->foo" instead of "objref.foo" in C and can't use the dot because you work with a pointer, in Java you can still use the dot because it doesn't know anything else to access members anyway. In C, you can pass the pointer (and here, it *is* actually called pointer) *and* you can pass the object itself, in which case a copy is passed. In C, you access the object that a pointer refers to by indirection using the star or "->". In Java, the only way objects are accessed anyway are using the dot (objref.member).
If we are pedantic again (now more important again), neither in Java nor in C there is "pass by reference". What we pass in Java is the reference/pointer to the object and in C we either pass a copy of the object (obvious case) or we pass again just a copy of a pointer to the object. So in both cases - Java and C - what we pass are the addresses of the objects. Not talking about primitive java types, which are copied in both Java and C - even though you can pass their address in C too, there is no difference between an aggregate type (i.e a struct) and a "primitive type" in C in *that* regard. | What is the difference between passing by reference in Java and passing a pointer in C? | [
"",
"java",
"c",
"pointers",
"pass-by-reference",
""
] |
I've been working on the Cell processor and I'm trying to create a struct that will hold an `spe_context_ptr_t`, which will be used within the thread to launch an spe context and will also hold a pointer to something else that will be passed to the spu context from within the thread (currently I'm trying to just make it a generic pointer, but in actuality it will be a pointer to another structure I've defined). When I try and compile, I get the following error:
```
spu/../common.h:38: error: expected specifier-qualifier-list before 'spe_context_ptr_t'
// here is the offending line(s)
typedef struct _PTHREAD_BLOCK {
spe_context_ptr_t * context; // Error happens here
uintptr32_t args;
} PTHREAD_BLOCK;
``` | The compiler doesn't know that spe\_context\_ptr\_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file. | I had the same error message but the solution is different.
The compiler parses the file from top to bottom.
Make sure a struct is defined BEFORE using it into another:
```
typedef struct
{
char name[50];
wheel_t wheels[4]; //wrong, wheel_t is not defined yet
} car_t;
typedef struct
{
int weight;
} wheel_t;
``` | What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"? | [
"",
"c++",
"c",
"pointers",
"struct",
""
] |
I have a routine
```
public void SomeRoutine(List<IFormattable> list) { ... }
```
I then try to call this routine
```
List<Guid>list = new List<Guid>();
list.Add(Guid.NewGuid());
SomeRoutine(list);
```
And it fails with a compile-time error. System.Guid implements IFormattable, but the error I get is
> cannot convert from
> 'System.Collections.Generic.List'
> to
> 'System.Collections.Generic.List'
NOTE: You will get the same error if you just use an array of Guids. Generics is NOT the cause....
But! Given this
```
public void SomeRoutine2(IFormattable obj) { ... }
```
and this
```
Guid a = Guid.NewGuid();
SomeRoutine2(a);
```
It compiles! So the question is WHY? Why am I able to pass a Guid object (which implements IFormattable) into a routine that accepts an object of IFormattable, but when I try to expand that to a collection (a generic list, or an array, or anything else), I get a conversion error?
I have had a heck of a time finding an answer, and I figured this would be the best place to go. | This is that whole covariance thing everyone talks about. It will work in .NET 4.0.
See here: <http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx>
Some more reading:
<http://www.infoq.com/news/2008/08/GenericVariance;jsessionid=188695B18864997E8D360E0EEED5983E>
<http://blogs.msdn.com/lucian/archive/2008/10/02/co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx> | This is a classic generics use-case; try:
```
public static void SomeRoutine<T>(IList<T> list) where T : IFormattable
{ ... }
```
Now inside `SomeRoutine` you have access to all the `IFormattable` members, but it will work with:
```
List<Guid>list; ...
SomeRoutine(list); // note no need to specify T
```
Edit: I've additionally [blogged](http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html) on the differences between 4.0 covariance and generics for this scenario. | C# .NET passing a collection of InterfaceImplementingClass objects to a routine that takes a collection of Interface objects | [
"",
"c#",
".net",
"generics",
"interface",
"clr",
""
] |
**Problem:**
* Call to **send()**, returns Winsock Error **10038** against socket handle
**Illustration:**
```
acceptedSocket = accept (server, (sockaddr *)&sin, &len);
```
* **accept()**, returns **0**
+ A new **thread**, is created for each connection
+ **send()**, (in thread function) returns **10038**
**Illustration:** - in thread function
```
//omitted
SOCKET RemoteSocket = (SOCKET) client;
//omitted
send (RemoteSocket, stringToSpend, strlen(stringToSpend), 0)
```
**Suggestions:**
* Possible, race condition?
* Could use I/O completion ports, but not at this stage | Isn't the problem in the line
```
acceptedSocket = accept (server, (sockaddr *)&sin, &len) == INVALID_SOCKET)
```
You make `acceptedSocket` the result of the comparison, but you should store the actual socket returned from accept somehow:
```
acceptedSocket = accept (server, (sockaddr *)&sin, &len);
isOK= acceptedSocket!=INVALID_SOCKET;
```
Although I'm a bit confused by the unbalanced parentheses in your post, so I may be wrong | accept() returns you a handle to a new connection-specific socket. for server code it's 2+ sockets involved: one is in listen state you are calling accept() for and second is one returned from accept() - it's an incoming connection socket. Following accept() can return socket for second incoming connection etc. if accept() returns 0 it's not an incoming connection - it's an error. | send(), returns Winsock Error 10038 | [
"",
"c++",
"windows",
"visual-studio-2008",
"multithreading",
"winsock",
""
] |
I have a console application that I am rebuilding from C to C#. This application has to be able to support the legacy method of storing information like parameters from a command-line and parameters from a file (called the system parameters) that customize each run. The system parameters file is in plain-text with a simple key-value structure.
## My questions are:
* Should I combine these different parameters into a single Configuration object?
* How would I call this configuration object from the code to store parameters?
* How would I call this configuration object from the code to retrieve parameters?
+ Should this object be strongly-typed?
* I will need access to this structure from a lot of different places in the code. What is the most elegant way to retrieve the values in the object without passing the object itself around everywhere?
I have a feeling that it should be a single, strongly-typed object and that it should be an instantiated object that is retrieved from a repository with a static retrieval method however I really want validation of this method. | I like using [`Settings`](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx). These can be generated automatically either by creating a settings file using the *Add New File* dialog box, or by adding a default settings file from project properties.
Each setting may be in user or application scope, which controls whether or not the user can change them or they are restricted to their default values. They are easily saved with the `Save()` method and loaded automatically into the static `Default` property.
> This class seems to be for application or user-based settings. I'm looking for per-run settings. Would you still recommend using this class in that case? – x97mdr
Yes. If you have both user/application based settings and per-run settings you should use two different classes - the normal (saved) settings and the per-run settings.
As long as you don't save the per-run settings, you should be safe and settings are still quite easy to use. These are static settings though. If the same application run needs several instances - this is the wrong approach. | I would use a single configuration object like the following:
```
using System;
using System.IO;
using System.Reflection;
public sealed class Setting {
public static int FrameMax { get; set; }
public static string VideoDir { get; set; }
static readonly string SETTINGS = "Settings.ini";
static readonly Setting instance = new Setting();
Setting() {}
static Setting() {
string property = "";
string[] settings = File.ReadAllLines(SETTINGS);
foreach (string s in settings)
try {
string[] split = s.Split(new char[] { ':' }, 2);
if (split.Length != 2)
continue;
property = split[0].Trim();
string value = split[1].Trim();
PropertyInfo propInfo = instance.GetType().GetProperty(property);
switch (propInfo.PropertyType.Name) {
case "Int32":
propInfo.SetValue(null, Convert.ToInt32(value), null);
break;
case "String":
propInfo.SetValue(null, value, null);
break;
}
} catch {
throw new Exception("Invalid setting '" + property + "'");
}
}
}
```
Since this is a [singleton](http://www.yoda.arachsys.com/csharp/singleton.html), it will create one and only one instance of itself the first time a `public static` property is referenced from the `Setting` object.
When the object is created, it reads from the `Settings.ini` file. The settings file is a plain-text file with a simple `key : value` structure that might look like this:
```
FrameMax : 12
VideoDir : C:\Videos\Best
```
The object uses reflection to discover each property and to store its initial value. In this example, two properties have been defined:
```
public static int FrameMax { get; set; }
public static string VideoDir { get; set; }
```
The code as written handles `Int32` and `String` types. By adding additional `case` statements to the `switch` statement, you could easily add support for types like `Float` and `Decimal`.
To change a setting, you would use something like:
```
Setting.FrameMax = 5;
```
To retrieve a setting, you would use something like:
```
if (Setting.FrameMax > 10) ...
```
You'll notice that all the properties are strongly-typed. Also, you don't have to pass the `Setting` object around, as all the `Setting` properties are `static` and always available everywhere.
I hope this idea is helpful. | Where to store configuration information | [
"",
"c#",
".net",
"configuration",
""
] |
I'm a big fan of dotTrace for my web application and I wanted to find a solid javascript profiler that functions about the same way. I've looked around and can't seem to find a JavaScript profiler like that.
Anyone know of a Javascript profiler like dotTrace? | A Javascript profiler is included with IE8: <http://blogs.msdn.com/ie/archive/2008/09/11/introducing-the-ie8-developer-tools-jscript-profiler.aspx> . It has reports and output that look somewhat like dotTrace. | [Firebug](http://getfirebug.com/) has a decent profiler built in, plus lots of other useful stuff. Please be more specific if there are particular features you're after. | JavaScript Profiler like JetBrains dotTrace? | [
"",
"javascript",
"profiler",
"dottrace",
""
] |
I am applying for a job as java developer. I programmed some hobby apps in java until 2001, after that I have mostly worked in c++ and other languages. Meanwhile, it feels like java has grown a lot, and there are all kinds of acronyms (EJB, spring, etc) unknown to me.
Where can I find a concise, clear explanation of the recent (5 years) development of java? What are key elements to understand? | 2001? Wow, times have changed. That was what? Java 1.3?
Firstly, language features:
* Generics: Java added generics in the 5.0 release in 2004, basically as syntactic sugar to stop you do all those casts from Objects out of collections;
* Annotations: also in Java 5. Used extensively in persistence frameworks, Spring and elsewhere;
* Typesafe enums: Java 5 added an enum type, which is basically a class (sort of);
* Concurrency: Java 5 added extensive concurrency utils so multithreading has changed a lot; and
* Asserts: a highly underused language feature added in Java 1.4. If enabled when you run your program, assets can check for various conditions and bomb out if they aren't true. The fact that you can turn them on or off when you run your program is great for diagnostics.
Thing is though, the above aren't even the big changes. In the early part of this decade, Java underwent radical architectural and philosophical changes.
Back in 2001 the big things were EJB, Swing and servlets/JSP. None of them really are anymore (at least not directly).
Proably the biggest thing to happen in Java (since its inception imho) is Spring and Spring really became big about 5 years ago. Spring is a lightweight container that also seeks to hide implementation differences between different providers and APIs. The biggest thing about Spring however is the principle of "inversion of control" or "dependency injection". The idea is that classes ("beans") are assembled from an external config ("application context").
A typical pattern in the earlier J2EE days was the Service Locator. It's now viewed largely as an anti-pattern. Basically you'd see code like this:
```
public MyClass() {
this.dataMember = ServiceLocator.locate("some service");
}
```
If you go around advocating this sort of approach these days you will be viewed as an anachronism, a rank amateur, a crackpot or some combination of the three.
Dependency injection, in its simplest form, will instead inject the necessary behaviour into classes without regard for the actual implementation. This kind of separation is deceptively powerful and a profound shift that Sun (still) hasn't really caugh tup with. It also greatly enhances unit testing.
Swing is still around but not so big anymore. Sun released JavaFX as a Flash competitor and applet replacement in recent months. I personally don't think it has much of a future (as Joel put it in his recent podcast, Java on the desktop is basically dead) but others will disagree.
EJB was big in 2001. Not so much anymore. It was (correctly) viewed as a nightmare of XML configuration, differences in application servers that made them largely non-portable (or non-trivially portable if you prefer) and they're such a heavyweight solution (pre-3.0) that they don't really have that many applications.
EJB 3.0 has taken a much more Spring-like approach of dependency injection (sort of) and annotations of POJOs (plain old Java objects).
Servlets and JSP were big in 2001. Struts began then or soon thereafter and was big until a few years ago. It's now been surpassed by other more modern Web frameworks (like Struts 2--no real relation to STruts 1 despite the name--Spring MVC, Seam and so on).
The big thing these days--not just in Java--is of coruse the Web and RIAs. Flash/Flex and Javascript/HTML/CSS (plus frameworks) rule the roost here these days (and yes theres GWT but it has a small following).
Weblogic and Websphere aren't as big as they were in 2001. JBoss still has a lot of momentum but my appserver of choice these days is Sun's Glassfish v2 or v3 Prelude.
IDEs have also changed. JBuilder was big in 2001. Now there are only really three: Eclipse, Netbeans and IntelliJ (probalby in that order of popularity but my preference is IntelliJ, which is also the only commercial one of the bunch). | I strongly encourage you to read blogs. That's usually the best way to get up to speed.
<https://stackoverflow.com/questions/48701/what-is-the-best-blog-for-java-development>
Plus look at this SO thread:
[Learning Java](https://stackoverflow.com/questions/255458/learning-java) | How do I best catch up with the latest developments in java? | [
"",
"java",
""
] |
Greetings,
I can't seem to find a way to create a function request with array as an argument.
For example, how do I make this kind of request using PHP SoapClient:
```
<GetResultList>
<GetResultListRequest>
<Filters>
<Filter>
<Name>string</Name>
<Value>string</Value>
</Filter>
<Filter>
<Name>string</Name>
<Value>string</Value>
</Filter>
</Filters>
</GetResultListRequest>
</GetResultList>
```
Is this possible to call this function without creating any extra classes (using arrays only)? If no, what is the most compact way of calling it? | You can use this **-v** function to convert a array to a object tree:
```
function array_to_objecttree($array) {
if (is_numeric(key($array))) { // Because Filters->Filter should be an array
foreach ($array as $key => $value) {
$array[$key] = array_to_objecttree($value);
}
return $array;
}
$Object = new stdClass;
foreach ($array as $key => $value) {
if (is_array($value)) {
$Object->$key = array_to_objecttree($value);
} else {
$Object->$key = $value;
}
}
return $Object;
}
```
Like so:
```
$data = array(
'GetResultListRequest' => array(
'Filters' => array(
'Filter' => array(
array('Name' => 'string', 'Value' => 'string'), // Has a numeric key
array('Name' => 'string', 'Value' => 'string'),
)
)
)
);
$Request = array_to_objecttree($data);
``` | I had similar problem and I had to post data in this structure.
**Accepted answer didn't work for me**
```
$data = array(
'GetResultListRequest' => array(
'Filters' => array(
array('Name' => 'string', 'Value' => 'string'),
array('Name' => 'string', 'Value' => 'string'),
)
)
);
```
maybe it might help somebody if accepted answear doesn't work for you | Passing array to SOAP function in PHP | [
"",
"php",
"soap",
"wsdl",
""
] |
I'm trying, but I'm stucked with the logic... so, I have this:
```
$max_items=10;
echo '<table>';
echo '<tr>';
foreach ($feed->get_items(0, $max_items) as $item):
echo '<td>';
echo $some_value;
echo '</td>';
endforeach;
echo '</tr>';
echo '</table>';
```
I want to show the results like this:
```
[1][2]
[3][4]
[5][6]
[7][8]
[9][10]
```
I have to use a while statement? A for loop? Inside or outside the foreach code?
I really don't get it...
Thanks for any kind of help | Here's a *very simple* example of how to do this sort of HTML building.
```
<?php
$data = range( 'a', 'z' );
$numCols = 2;
echo "<table>\n";
echo "\t<tr>\n";
foreach( $data as $i => $item )
{
if ( $i != 0 && $i++ % $numCols == 0 )
{
echo "\t</tr>\n\t<tr>\n";
}
echo "\t\t<td>$item</td>\n";
}
echo "\t</tr>\n";
echo '</table>';
```
This way, you can change $numCols to be 3 or 4 (or any number) and always see that number of columns in the output, and it does so *without* using an nested loop. | Take a look at this link to [Displaying Recent Posts On a Non-WordPress Page](http://w-shadow.com/blog/2008/11/15/displaying-recent-posts-on-a-non-wordpress-page). I think what you may be looking for is a way to loop over the objects get methods. For that you will need a nested loop and some sort of reflection. | dynamic rows and columns inside a foreach loop | [
"",
"php",
"simplepie",
""
] |
> **Possible Duplicate:**
> [Is there a good reason to use upper case for T-SQL keywords?](https://stackoverflow.com/questions/292026/is-there-a-good-reason-to-use-upper-case-for-t-sql-keywords)
I personally find a string of lowercase characters to be more readable than a string of uppercase characters. Is some old/popular flavor of SQL case-sensitive or something?
For reference:
```
select
this.Column1,
case when this.Column2 is null then 0 else this.Column2 end
from dbo.SomeTable this
inner join dbo.AnotherTable another on this.id = another.id
where
this.Price > 100
```
vs.
```
SELECT
this.Column1,
CASE WHEN this.Column2 IS NULL THEN 0 ELSE this.Column2 END
FROM dbo.SomeTable this
INNER JOIN dbo.AnotherTable another ON this.id = another.id
WHERE
this.Price > 100
```
The former just seems so much more readable to me, but I see the latter way more often. | I think the latter is more readable. You can easily separate the keywords from table and column names, etc. | I agree with you - to me, uppercase is just SHOUTING.
I let my IDE handle making keywords stand out, via syntax highlighting.
I don't know of a historical reason for it, but by now it's just a subjective preference.
**Edit to further make clear my reasoning:**
Would you uppercase your keywords in any other modern language? Made up example:
```
USING (EditForm form = NEW EditForm()) {
IF (form.ShowDialog() == DialogResult.OK) {
IF ( form.EditedThing == null ) {
THROW NEW Exception("No thing!");
}
RETURN form.EditedThing;
} ELSE {
RETURN null;
}
}
```
Ugh!
Anyway, it's pretty clear from the votes which style is more popular, but I think we all agree that it's just a personal preference. | Why should I capitalize my SQL keywords? Is there a good reason? | [
"",
"sql",
"formatting",
"readability",
""
] |
I want add a key up event to every text box element in a table excluding the last text box in each row. The table is dynamic on both axis.
The key up event will total the values in all but the last text box. The total is then placed in the last text box for the row.
The script for the totaling and setting the total all works fine.
I tired the following to select the target elements:
```
$("#Grid tr input:text:not(:last)").keyup(function(){
//do total stuff here
})
```
Unfortunately it works as documented and not as I wanted and selects all but the very last checkbox.
Ideally the solution will not involve any further markup to the table example below or involve any looping. However if that is what it takes, so be it.
```
<table id="Grid">
<tr id="r1">
<td>Row 1</td>
<td><input type="text" id="txt_a1_b1"></td>
<td><input type="text" id="txt_a1_b2"></td>
<td><input type="text" id="txt_a1_b3"></td>
<td><input type="text" id="txt_a1_b4"></td>
<td><input type="text" id="total_a1"></td>
</tr>
<tr id="r2">
<td>Row 2</td>
<td><input type="text" id="txt_a2_b1"></td>
<td><input type="text" id="txt_a2_b2"></td>
<td><input type="text" id="txt_a2_b3"></td>
<td><input type="text" id="txt_a2_b4"></td>
<td><input type="text" id="total_a2"></td>
</tr>
<tr id="r3">
<td>Row 3</td>
<td><input type="text" id="txt_a3_b1"></td>
<td><input type="text" id="txt_a3_b2"></td>
<td><input type="text" id="txt_a3_b3"></td>
<td><input type="text" id="txt_a3_b4"></td>
<td><input type="text" id="total_a3"></td>
</tr>
</table>
```
One final point, the total text box does need to be a text box as there is also a requirement to enter a total then split it across the row and I do not want a key up function in the total text box. | I'm surprised noones quite got this yet:
```
$("#Grid tr :not(:last-child) :text").keyup(function(){
//do total stuff here
})
``` | I would use the each function on the rows and find all but the last input in each row.
```
$('#Grid > tr').each( function() {
$(this).find('input:not(:last)).keyup( ... )
});
``` | How do I Select all text boxes in a table excluding the last one in the table row with JQuery | [
"",
"javascript",
"jquery",
""
] |
I'm working on a project where i find i'm checking for the following in many, many places:
```
if(item.Rate == 0 || item.Rate == null) { }
```
more as a curiousity than anything, what's the best way to check for both cases?
I've added a helper method which is:
```
public static bool nz(object obj)
{
var parsedInt = 0;
var parsed = int.TryParse(obj.ToString(), out parsedInt);
return IsNull(obj) || (parsed && parsedInt == 0);
}
```
Is there a better way? | I like `if ((item.Rate ?? 0) == 0) { }`
**Update 1:**
You could also define an extension method like:
```
public static bool IsNullOrValue(this double? value, double valueToCheck)
{
return (value??valueToCheck) == valueToCheck;
}
```
And use it like this:
`if(item.IsNullOrValue(0)){}` // but you don't get much from it | Although I quite like the accepted answer, I think that, for completeness, this option should be mentioned as well:
```
if (item.Rate.GetValueOrDefault() == 0) { }
```
This solution
* does not require an additional method,
* is faster than all the other options, since [GetValueOrDefault is a single field read operation](http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/)¹ and
* reads easier than `((item.Rate ?? 0) == 0)` (this might be a matter of taste, though).
---
¹ This should not influence your decision, though, since these kinds of micro-optimization are unlikely to make any difference. | Nullable types: better way to check for null or zero in c# | [
"",
"c#",
"null",
"zero",
""
] |
I've looked in the usual places (apache commons, google) and not been able to find one ...
It should be opensource.
Pretty much looking for one based on a linked list. The use case is 10'000's of maps, with not necessarily many values in. It does not need to scale up, as i can convert it when it gets too big.
Some numbers, sizes using some calculated jvm values (8bytes/java.lang.Object, 4bytes/ref) the HashMap is about 100+32n bytes, the theoretical best is 12+20\*n. <-- I want that, for small n. | Ok, implemented it myself in the end. I did a speed comparison, and found when compared to a HashMap that it was still slightly faster with 4 entries, but slower with 5 or more. I did the tests with a longish list of keys that I tried to give a similar makeup as a list of random english words.
```
import java.util.*;
// PUBLIC DOMAIN
public class SmallMap extends AbstractMap {
private Entry entry = null;
public void clear() { entry = null; }
public boolean isEmpty() { return entry==null; }
public int size() {
int r = 0;
for(Entry e = entry; e!=null; e = e.next) r++;
return r;
}
public boolean containsKey(Object key) {
for(Entry e = entry; e!=null; e = e.next){
if(e.key.equals(key)){
return true;
}
}
return false;
}
public boolean containsValue(Object value) {
for(Entry e = entry; e!=null; e = e.next){
if(e.value==null){
if(value==null) return true;
}else if(e.value.equals(value)){
return true;
}
}
return false;
}
public Object get(Object key) {
for(Entry e = entry; e!=null; e = e.next){
if(e.key.equals(key)){
return e.value;
}
}
return null;
}
public Object put(Object key, Object value) {
for(Entry e = entry; e!=null; e = e.next){
if(e.key.equals(key)){
Object r = e.value;
e.value = value;
return r;
}
}
entry = new Entry(key, value, entry);
return null;
}
public Object remove(Object key) {
if(entry!=null){
if(entry.key.equals(key)){
Object r = entry.value;
entry = entry.next;
return r;
}
for(Entry e = entry; e.next!=null; e = e.next){
if(key.equals(e.next.key)){
Object r = e.next.value;
e.next = e.next.next;
return r;
}
}
}
return null;
}
public Set entrySet() { return new EntrySet(); }
class EntrySet extends AbstractSet{
public Iterator iterator() {
return new Iterator(){
Entry last = null;
Entry e = entry;
public boolean hasNext() { return e!=null; }
public Object next() {
last = e;
e = e.next;
return last;
}
public void remove() {
if(last == null) throw new IllegalStateException();
SmallMap.this.remove(last.key);
}
};
}
public int size() { return SmallMap.this.size();}
}
static private class Entry implements java.util.Map.Entry {
final Object key;
Object value;
Entry next;
Entry(Object key, Object value, Entry next){
if(key==null) throw new NullPointerException();
this.key = key;
this.value = value;
this.next = next;
}
public Object getKey() { return key; }
public Object getValue() { return value; }
public Object setValue(Object value) {
Object r = this.value;
this.value = value;
return r;
}
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^
(value == null ? 0 : value.hashCode());
}
}
}
``` | Could have a look at commons-collections [Flat3Map](http://commons.apache.org/collections/api-release/org/apache/commons/collections/map/Flat3Map.html), it's optimised to store 3 values in 3 fields and overflows to another map at 4.
I haven't looked at the implementation but it may be worth thinking about. Only trouble is that since commons-collections is 1.3 compatible there are no generic's. | Anyone know of a java.util.Map implementation optimized for low memory use? | [
"",
"java",
"optimization",
"collections",
""
] |
Qt documentation states that signals and slots can be `direct`, `queued` and `auto`.
It also stated that if object that owns slot 'lives' in a thread different from object that owns signal, emitting such signal will be like posting message - signal emit will return instantly and slot method will be called in target thread's event loop.
Unfortunately, documentation do not specify that 'lives' stands for and no examples is available. I have tried the following code:
**`main.h:`**
```
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
msleep( 200 );
std::cout << "thread 1 started" << std::endl;
MySignal();
exec();
}
signals:
void MySignal( void );
};
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 2 started" << std::endl;
exec();
}
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
}
};
```
**`main.cpp:`**
```
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CThread1 oThread1;
CThread2 oThread2;
QObject::connect( & oThread1, SIGNAL( MySignal() ),
& oThread2, SLOT( MySlot() ) );
oThread1.start();
oThread2.start();
oThread1.wait();
oThread2.wait();
return a.exec();
}
```
Output is:
```
thread 2 started
thread 1 started
```
`MySlot()` is never called :(. What I'm doing wrong? | There are quite a few problems with your code :
* like said by Evan the emit keyword is missing
* all your objects live in the main thread, only the code in the run methods live in other threads, which means that the MySlot slot would be called in the main thread and I'm not sure that's what you want
* your slot will never be called since the main event loop will never been launched : your two calls to wait() will only timeout after a very long time (and you'll probably kill your application before that happens) and I don't think that's what you want either, anyway they really have no use in your code.
This code would most likely work (though I have not tested it) and I think it does what you want it to do :
```
class MyObject : public QObject
{
Q_OBJECT
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
}
};
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 1 started" << std::endl;
int i = 0;
while(1)
{
msleep( 200 );
i++;
if(i==1000)
emit MySignal();
}
}
signals:
void MySignal( void );
};
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 2 started" << std::endl;
exec();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CThread1 oThread1;
CThread2 oThread2;
MyObject myObject;
QObject::connect( & oThread1, SIGNAL( MySignal() ),
& myObject, SLOT( MySlot() ) );
oThread2.start();
myObject.moveToThread(&oThread2)
oThread1.start();
return a.exec();
}
```
Now MyObject will live in thread2 (thanks to moveToThread).
MySignal should be sent from thread1 (thought I'm not sure on that one, it might be sent from main thread, it doesn't really matter).
No event loop is needed in thread1 since emitting a signal doesn't need an event loop. An event loop is needed in thread2 (lanched by exec()) to receive the signal.
MySlot will be called in thread2. | ## Do not subclass QThread for Qt 4.4+
While Aiua's answer is good, I want to point out some issues with QThread and Qt 4.6 or 4.7.
This article sums it up: <http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/>
## Lack of Documentation on Qt's part
Unfortunately the problem stems from a lack of updates to documentation. Prior to Qt 4.4 QThread had no default run() implementation, which meant that you had to subclass QThread in order to use it.
If you're using Qt 4.6 or 4.7 then you almost certainly should *not* subclass QThread.
## Use moveToThread
The key to getting slots to execute in a worker thread is to use the moveToThread method as Aiua pointed out. | How to emit cross-thread signal in Qt? | [
"",
"c++",
"qt",
"signals-slots",
"qt-signals",
""
] |
My team need the "Sobol quasi-random number generator" - a common RNG which is famous for good quality results and speed of operation. I found [what looks like a simple C implementation on the web](http://people.scs.fsu.edu/~burkardt/cpp_src/sobol/sobol_old.C). At home I was able to compile it almost instantaneously using my Linux GCC compiler.
The following day I tried it at work: If I compile in Visual Studio in debug mode it takes about 1 minute. If I were to compile it in release mode **it takes about 40 minutes.**
Why?
I know that "release" mode triggers some compiler optimization... but how on earth could a file this small take so long to optimize? It's mostly comments and static-data. There's hardly anything worth optimizing.
None of these PCs are particularly slow, and in any case I know that the compile time is consistent across a range of Windows computers. I've also heard that newer versions of Visual Studio have a faster compile time, however for now we are stuck with Visual Studio.Net 2003. Compiling on GCC (the one bundled with Ubuntu 8.04) always takes microseconds. | To be honest, I'm not really sure the codes that good. It's got a nasty smell in it. Namely, this function:
```
unsigned int i4_xor ( unsigned int i, unsigned int j )
//****************************************************************************80
//
// Purpose:
//
// I4_XOR calculates the exclusive OR of two integers.
//
// Modified:
//
// 16 February 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, unsigned int I, J, two values whose exclusive OR is needed.
//
// Output, unsigned int I4_XOR, the exclusive OR of I and J.
//
{
unsigned int i2;
unsigned int j2;
unsigned int k;
unsigned int l;
k = 0;
l = 1;
while ( i != 0 || j != 0 )
{
i2 = i / 2;
j2 = j / 2;
if (
( ( i == 2 * i2 ) && ( j != 2 * j2 ) ) ||
( ( i != 2 * i2 ) && ( j == 2 * j2 ) ) )
{
k = k + l;
}
i = i2;
j = j2;
l = 2 * l;
}
return k;
}
```
There's an i8\_xor too. And a couple of abs functions.
I think a post to the [DailyWTF](http://www.thedailywtf.com/) is in order.
EDIT: For the non-c programmers, here's a quick guide to what the above does:
```
function xor i:unsigned, j:unsigned
answer = 0
bit_position = 1
while i <> 0 or j <> 0
if least significant bit of i <> least significant bit of j
answer = answer + bit_position
end if
bit_position = bit_position * 2
i = i / 2
j = j / 2
end while
return answer
end function
```
To determine if the least significant bit is set or cleared, the following is used:
```
bit set if i <> (i / 2) * 2
bit clear if i == (i / 2) * 2
```
What makes the code extra WTFy is that C defines an XOR operator, namely '^'. So, instead of:
```
result = i4_xor (a, b);
```
you can have:
```
result = a ^ b; // no function call at all!
```
The original programmer really should have know about the xor operator. But even if they didn't (and granted, it's another obfuscated C symbol), their implementation of an XOR function is unbelievably poor. | I'm using VC++ 2003 and it compiled instantly in both debug/release modes.
**Edit:**
Do you have the latest service pack installed on your systems? | Why does this take so long to compile in VCC 2003? | [
"",
"c++",
"windows",
"visual-studio",
"visual-c++",
""
] |
I've asked a couple questions ([here](http://stackoverflow.com/questions/580053/when-should-i-use-a-vector-of-objects-instead-of-a-vector-of-pointers) and [here](http://stackoverflow.com/questions/589076/when-is-it-not-a-good-idea-to-pass-by-reference)) about memory management, and invariably someone suggests that I use boost::shared\_ptrs.
Given how useful they seem to be, I'm seriously considering switching over my entire application to use boost::shared\_ptrs.
However, before I jump in with both feet and do this, I wanted to ask -- Has anyone had any bad experiences with boost::shared\_ptrs? Is there some pitfall to using them that I need to watch out for?
Right now, they seem almost too good to be true - taking care of most of my garbage collection concerns automatically. What's the downside? | The downside is they're not free. You especially shouldn't use `shared_ptr`/`shared_array` when `scoped_ptr`/`scoped_array` (or plain old stack allocation) will do. You'll need to manually break cycles with `weak_ptr` if you have any. The vector question you link to is one case where I might reach for a `shared_ptr`, the second question I would not. Not copying is a premature optimization, especially if the string class does it for you already. If the string class is reference counted, it will also be able to implement COW properly, which can't really be done with the `shared_ptr<string>` approach. Using `shared_ptr` willy-nilly will also introduce "interface friction" with external libraries/apis. | Boost shared pointers or any other technique of memory management in C++ is not a panacea. There is no substitution for careful coding. If you dive into using boost::shared\_ptr be aware of object ownership and avoid circular references. You are going to need to explicitly break cycles or use boost::weak\_ptr where necessary.
Also be careful to always use boost::shared\_ptr for an instance from the moment it is allocated. That way you are sure you won't have dangling references. One way you can ensure that is to use factory methods that return your newly created object in a shared\_ptr.
```
typedef boost::shared_ptr<Widget> WidgetPtr;
WidgetPtr myWidget = Widget::Create();
``` | Are there any reasons not to use Boost::shared_ptrs? | [
"",
"c++",
"memory-management",
""
] |
As the question says, I want to load a DLL from a location in memory instead of a file, similarly to LoadLibrary(Ex). I'm no expert in WinAPI, so googled a little and found [this article](http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/) together with MemoryModule library that pretty much meets my needs.
On the other hand the info there is quite old and the library hasn't been updated for a while too. So I wanted to know if there are different, newer and better ways to do it. Also if somebody has used the library mentioned in the article, could they provide insight on what I might be facing when using it?
Just for the curious ones, I'm exploring the concept of encrypting some plug-ins for applications without storing the decrypted version on disk. | Well, you can create a RAM Drive according to [these instructions](http://www.picobay.com/projects/2006/06/how-to-make-windows-xp-ram-disk-drive.html), then copy the DLL you can in memory to a file there and the use LoadLibrary().
Of course this is not very practical if you plan to deploy this as some kind of product because people are going to notice a driver being installed, a reboot after the installation and a new drive letter under My Computer. Also, this does nothing to actually hide the DLL since its just sitting there in the RAM Drive for everybody to watch.
Another thing I'm interested about is Why you actually want to do this? Perhaps your end result can be achieved by some other means other than Loading the DLL from memory. For instance when using a binary packer such as [UPX](http://en.wikipedia.org/wiki/UPX), the DLL that you have on disk is different from the one that is eventually executed. Immediately after the DLL is loaded normally with LoadLibrary, The unpacker kicks in and rewrites the memory which the DLL is loaded to with the uncompressed binary (the DLL header makes sure that there is enough space allocated) | Implementing your own DLL loader can get really hairy really fast. Reading this article it's easy to miss what kind of crazy edge cases you can get yourself into. I strongly recommend against it.
Just for a taste - consider you can't use any conventional debugging tools for the code in the DLL you're loading since the code you're executing is not listed in the region of any DLL known by the OS.
Another serious issue is dealing with [DEP](http://en.wikipedia.org/wiki/Data_Execution_Prevention) in windows. | Loading DLL from a location in memory | [
"",
"c++",
"c",
"winapi",
"dll",
""
] |
Suppose I have some code like this:
```
class Visitor {
public:
Visitor(callBackFunction) {}
void visit() {
//do something useful
invokeCallback();
}
}
class ClassThatCanBeVisited {
Visitor &visitor;
public:
ClassThatCanBeVisited(Visitor &_visitor) : visitor(_visitor){}
void someUsefulMethod() {
int data= 42;
visitor.visit(data);
}
};
void callBackFunction() {
//do something useful in the context of the Main file
}
int main() {
Visitor visitor;
ClassThatCanBeVisited foo(visitor);
foo.someUsefulMethod();
}
```
I need to create a simple callback that will be called whenever the Visitor::visit() is called. I know that I probably should put the code of the callback inside my Visitor, but it is in a different context, so I would like to pass the callBackFunction() to the Visitor so he could invoke my callback function.
I looked for things on the web and saw boost::function, but c++ already has the basic functors.
Which one should I use for better clarity of the code? The callback is going to be a simple void() function, but it might grow, you never know the future :)
What is the recommended way to do this? | You can use callback interface and its hierarchy if you don't want to use boost::function.
```
class VisitorCallback
{
public:
virtual void handle( const Visitor& ) = 0;
};
```
If you have or can use boost::function - use it, it is a good way to get rid of all those callback classes.
**Edit:**
@edisongustavo:
boost::function and boost::bind won't probably make your code more readable. But it will give you an opportunity to pass free functions ( I mean functions out of class and static class functions ) as callback as well as existing functions of any class.
With boost functions you can pass functions with for example 2 parameters as callback which expect only one parameter.
```
typedef boost::function< void ( int ) > IntExpectingCallback;
void TwoIntFunction( int, int );
{
}
...
IntExpectingCallback callback = boost::bind( TwoIntFunction, 5, _1 );
```
But again, this won't make your code more readable unless all your team knows and favor boost. | Yes boost::function would do this well. That's a very common usage of it. You will need to use boost::bind to bind the instance to the member function.
```
func = boost::bind( &MyClass::CallbackFunc, this);
```
Would be how you would do that from within the class.
Be sure the "this" doesn't dissapear or your boost function will crash in the middle of some boost header somewhere. | I need to create a simple callback in c++? Should I use boost::function? | [
"",
"c++",
"boost",
"callback",
"functor",
""
] |
I am interested in knowing if there is any alternative to rrdtool for logging time series data. I am looking at something that can scale for a large number of devices to monitor.
From what I read on this subject, rrdtool is I/O bound when you hit it with large amounts of data. Since I envision this to scale to a very large number of devices to monitor, I am curious if there's any alternative that would not choke on I/O. Preferable SQL based, but not necessarily.
Thanks | If I/O performance is the main worry then you want to look into something like [rrdcached](http://oss.oetiker.ch/rrdtool/doc/rrdcached.en.html) which is available in the current version (1.4) of the RRDTools.
The I/O overhead is not a function of the data being written, after all each value 8 bytes per data source. The I/O bandwidth comes from the fact a whole sector (typically 4k) needs to be read in before being written out. Suddenly to write 8 bytes you have read/written 8k bytes.
The rrdcached coalesces all these write together so when an RRD is updated the ratio of useful data (actual DS values) to wasted data (the spare bytes in the sector) is reduced.
All the RRDTools will automatically work with rrdcached when they detect it running (via an environment variable). This allows them to trigger flushes when needed, for example when generating a graph from the data.
While switching to an SQL based solution may help consider the extra I/O that will be required to support SQL. Considering you don't tend to use RRD data in that sort of random access pattern a database is a bit of a sledgehammer for the problem. While sticking with RRDTool will keep access to all the eco-system of tools that understand and can work with the files, which is useful especially if you are already familiar with it. | There are some time series databases which have high availability and/or scalability as goals.
Maybe have a look at
* [rrdcached](http://oss.oetiker.ch/rrdtool/doc/rrdcached.en.html), a caching layer on top of rrd
* [whisper](http://graphite.wikidot.com/whisper), the database engine behind [graphite](http://graphite.wikidot.com/start)
* [opentsdb](http://opentsdb.net/) is a distributed, scalable Time Series Database (TSDB) written on top of HBase
* [reconnoiter](https://labs.omniti.com/labs/reconnoiter) although its focus is more on monitoring | rrd tool alternative for high volume | [
"",
"sql",
"time-series",
"rrdtool",
"opentsdb",
""
] |
This hangs in Php (5.2.6-Win32 + Oracle10g) is it a bug, or I'm doing something fundamentally wrong?
```
try {
$conn = new PDO($DB,$USER,$PASSWORD);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//connected
try {
$conn->exec("DELETE FROM MY_TABLE");
echo "done";
...
```
**Note:** I don't know if this is a bug or not, I'm guessing it is. However as I couldn't find a bug report for this after a quick search. I might be doing something wrong, so I figured I'd ask here first, and for posterity in case someone else has a similar issue. | Are there other activities going on in the database at the same time? If yes, I'd suspect deadlocks. Some uncommitted DML transaction(s) might be locking some rows of the `MY_TABLE`.
If you don't need rollback capability, consider using `TRUNCATE` instead of `DELETE`. | A DELETE without a WHERE will (most likely) a full scan of the table.
That means it reads every block under the 'high-water mark' - that is every block that has ever been used by the table. So if the table was, at one time, very big, then it can take a very long time to delete just a handful of records. [Because it doesn't 'know' there are only four records until it reads all that space.]
A truncate doesn't do this. It simply moves the high-water mark of the table so that any blocks that were in use quickly become unused. | Does PHP's Oracle PDO hang on DELETE? | [
"",
"php",
"oracle",
"pdo",
""
] |
I want to convert a money datatype to a decimal, because I want to record the results to 8 decimal places.
For example, in a currency rate table I see the rate stored as 2871047428.20 as a money datatype; using Microsoft SQL Management Studio, I want to divide that by 10000000 in order to achieve the result 287.10474282; however the result I am actually getting is 287.1047.
I believe the reason I am getting only the 4 decimal places is because it is money datatype, and therefore I think the way forward is to convert this to a decimal datatype.... | Here a comparison left column the decimal value, right column the calculated money value:
```
DECLARE @money AS money
SET @money = 2871047428.20
SELECT CAST(@money AS decimal(34,4)) / 10000000, @money / 10000000
```
See also here on Stack Overflow:
* [How do I convert from a money datatype in SQL server?](https://stackoverflow.com/questions/532351/how-do-i-convert-from-a-money-datatype-in-sql-server)
* [SQL Server 2005 varchar loses decimal places converting to a decimal](https://stackoverflow.com/questions/391117/sql-server-2005-varchar-loses-decimal-places-converting-to-a-decimal) | ```
SELECT CAST(currency_rate AS decimal) / 10000000 FROM ...
``` | In SQL how can I convert a money datatype to a decimal? | [
"",
"sql",
"types",
"decimal",
"currency",
""
] |
I'm learning regex and need to get all possible matches for a pattern out of a string.
If my input is:
```
case a
when cond1
then stmt1;
when cond2
then stmt2;
end case;
```
I need to get the matches which have groups as follows
Group1:
1. `"cond1"`
2. `"stmt1;"`
and Group2:
1. `"cond2"`
2. `"stmt2;"`
Is it possible to get such groups using any regex? | It's possible to use regex for this provided that you don't nest your statements. For example if your stmt1 is another case statment then all bets are off (you can't use regex for something like that, you need a regular parser).
**Edit**: If you really want to try it you can do it with something like (not tested, but you get the idea):
```
Regex t = new Regex(@"when\s+(.*?)\s+then\s+(.*?;)", RegexOptions.Singleline)
allMatches = t.Matches(input_string)
```
But as I said this will work only for not nested statements.
**Edit 2**: Changed a little the regex to include the semicolon in the last group. This will not work as you wanted - instead it will give you multiple matches and each match will represent one *when* condition, with the first group the condition and the second *group* the statement.
I don't think you can build a regex that does exactly what you want, but this should be close enough (I hope).
**Edit 3**: New regex - should handle multiple statements
```
Regex t = new Regex(@"when\s+(.*?)\s+then\s+(.*?)(?=(when|end))", RegexOptions.Singleline)
```
It contains a positive lookahead so that the second group matches from *then* to the next 'when' or 'end'. In my test it worked with this:
```
case a
when cond1
then stmt1;
stm1;
stm2;stm3
when cond2
then stmt2;
aaa;
bbb;
end case;
```
It's case sensitive for now, so if you need case insensitivity you need to add the corresponding regex flag. | I don't think this is possible, primarily because any group that matches when...then... is going to match all of them, creating multiple captures within the same group.
I'd suggest using this regex:
```
(?:when(.*)\nthen(.*)\n)+?
```
which results in:
Match 1:
\* Group 1: cond1
\* Group 2: stmt1;
Match 2:
\* Group 1: cond2
\* Group 2: stmt2; | Regex to get all possible matches for a pattern in C# | [
"",
"c#",
"regex",
"parsing",
"plsql",
""
] |
I want to set the JAVA\_HOME variable from a batch script | This snippet will search the current PATH for java.exe, and print out where it was found:
```
for /f %%j in ("java.exe") do @echo.%%~dp$PATH:j
```
On my system this gives me
> C:\WINDOWS\system32\
Using this you can set JAVA\_HOME as follows:
```
@echo off
for /f %%j in ("java.exe") do (
set JAVA_HOME=%%~dp$PATH:j
)
if %JAVA_HOME%.==. (
@echo java.exe not found
) else (
@echo JAVA_HOME = %JAVA_HOME%
)
``` | This solution depends on the JDK being installed under %ProgramFiles%\Java, for example C:\Program Files\Java\jdk1.6.0\_18. You can change the line "set JDK\_Version=1.6" to the version you want to use such as "set JDK\_Version=1.5".
Assuming that the latest version of JDK would be at the bottom of the list (jdk%jdk\_Version%\*) the latest version available should be set as JAVA\_HOME. If the JDK could not be found JAVA\_HOME will not be changed. If the JDK could not be found and JAVA\_HOME doesn't have a value the script will display an error message.
```
@echo off
rem set the version of jdk you would like to use (1.4, 1.5, 1.6, etc)
set JDK_Version=1.6
echo.
echo Locating JDK %JDK_Version%
for /d %%i in ("%ProgramFiles%\Java\jdk%jdk_Version%*") do (set Located=%%i)
rem check if JDK was located
if "%Located%"=="" goto else
rem if JDK located display message to user
rem update %JAVA_HOME%
set JAVA_HOME=%Located%
echo Located JDK %jdk_Version%
echo JAVA_HOME has been set to:
echo %JAVA_HOME%
goto endif
:else
rem if JDK was not located
rem if %JAVA_HOME% has been defined then use the existing value
echo Could not locate JDK %JDK_Version%
if "%JAVA_HOME%"=="" goto NoExistingJavaHome
echo Existing value of JAVA_HOME will be used:
echo %JAVA_HOME%
goto endif
:NoExistingJavaHome
rem display message to the user that %JAVA_HOME% is not available
echo No Existing value of JAVA_HOME is available
goto endif
:endif
rem clear the variables used by this script
set JDK_Version=
set Located=
``` | Discover from a batch file where is Java installed? | [
"",
"java",
"windows",
"batch-file",
"java-home",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.