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 simple console application (80x24) in Java.
Is there a `gotoxy(x,y)` equivalent for the console? | If by gotoxy(x,y), you want to reposition your cursor somewhere specific on the console, you can usually use VT100 control codes to do this. See <http://www.termsys.demon.co.uk/vtansi.htm>.
Do something like
```
char escCode = 0x1B;
int row = 10; int column = 10;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
```
Which should move the cursor to position 10,10 on the console. | I don't think there's a built-in function to do that in Java. There's a Java curses library called [JCurses](http://sourceforge.net/projects/javacurses/) that you can use though. | Move console cursor to specified position | [
"",
"java",
"console-application",
""
] |
What I'm trying to do would look like this in the command line:
```
>>> import mymodule
>>> names = dir(mymodule)
```
How can I get a reference to all the names defined in `mymodule` from within `mymodule` itself?
Something like this:
```
# mymodule.py
names = dir(__thismodule__)
``` | Just use globals()
> globals() — Return a dictionary
> representing the current global symbol
> table. This is always the dictionary
> of the current module (inside a
> function or method, this is the module
> where it is defined, not the module
> from which it is called).
<http://docs.python.org/library/functions.html#globals> | As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module. The way I typically see this done is like this:
```
import sys
dir(sys.modules[__name__])
``` | How to get a reference to current module's attributes in Python | [
"",
"python",
""
] |
Where should `DATETIME_FORMAT` be placed for it to have effect
on the display of date-time in the Django admin site
(Django’s automatic admin interface)?
Documentation for `DATETIME_FORMAT`, on page
<http://docs.djangoproject.com/en/1.0/ref/settings/>, says:
```
"The default formatting to use for datetime fields on
Django admin change-list pages -- and, possibly, by
other parts of the system."
```
**Update 1**: `DATETIME_FORMAT` is broken (the value of it is
ignored), despite the documentation. Many years ago it
worked, but since then the Django implementations have been
broken wrt. this feature. It seems the Django community
can't decide how to fix it (but in the meantime I think they
should remove `DATETIME_FORMAT` from the documentation or add
a note about this problem to it).
I have put these lines into file "settings.py" of the
website/project (not the app), but it does not seem to have
any effect (after restarting the development server):
> DATETIME\_FORMAT = 'Y-m-d H:i:sO'
>
> DATE\_FORMAT = 'Y-m-d'
As an example "June 29, 2009, 7:30 p.m." is displayed when
using Django admin site.
Django version is 1.0.2 final and Python version is 2.6.2
(64 bit). Platform: Windows XP 64 bit.
Stack Overflow question *[European date input in Django Admin](https://stackoverflow.com/questions/907351)* seems to be about the exact opposite problem (and thus an apparent
contradiction).
The full path to file "settings.py" is
"D:\dproj\MSQall\website\GoogleCodeHost\settings.py". I now
start the development server this way (in a Windows command
line window):
> cd D:\dproj\MSQall\website\GoogleCodeHost
>
> set DJANGO\_SETTINGS\_MODULE=GoogleCodeHost.settings
>
> python manage.py runserver 6800
There is no difference. Besides these are positively read
from file "settings.py":
> DATABASE\_NAME
>
> INSTALLED\_APPS
>
> TEMPLATE\_DIRS
>
> MIDDLEWARE\_CLASSES
"django-admin.py startproject XYZ" does not create file
"settings.py" containing `DATETIME_FORMAT` or `DATE_FORMAT`.
Perhaps there is a reason for that?
The sequence "d:", "cd D:\dproj\MSQall\website\GoogleCodeHost",
"python manage.py
shell", "from django.conf import settings",
"settings.DATE\_FORMAT", "settings.DATETIME\_FORMAT" outputs
(as expected):
```
'Y-m-d H:i:sO'
'Y-m-d'
```
So the content of file "settings.py" is being read, but does
not take effect in the Django Admin interface. | This will solve the particular problem that is not possible
with DATETIME\_FORMAT (as it is ignored in the current Django
implementations despite the documentation), is dirty too and
is similar to ayaz's answer (less global - will only affect
the admin site list view):
Right after the line
> (date\_format, datetime\_format,time\_format) = get\_date\_formats()
in file (Django is usually in folder Lib/site-packages in
the Python installation)
> django/contrib/admin/templatetags/admin\_list.py
overwrite the value of datetime\_format (for a
models.DateTimeField in the model):
> datetime\_format = 'Y-m-d H:i:sO'
And for date-only fields:
> date\_format = 'Y-m-d'
Restart of the web-server (e.g. development server) or
logging out of the admin interface is **NOT** necessary for
this change to take effect. A simple refresh in the web-browser
is all what is required. | With:
```
USE_L10N = False
```
`DATE_TIME` takes effect, since the localization of l10n overrides `DATETIME_FORMAT` and `DATE_FORMAT` as documented at: <https://docs.djangoproject.com/en/1.9/ref/settings/#date-format> | How to make Django's "DATETIME_FORMAT" active? | [
"",
"python",
"django",
"django-admin",
"datetime-format",
"django-settings",
""
] |
In my database I have a table holding some subscription information. I have among others a StartDate and an EndDate as DateTime.
What I need is to make a Linq query getting all rows due for payment. The payment is supposed to take place each month on the same day they registered (StartDate) and stop on the EndDate. So if they registered on the 23. May, I need to invoice them again 23. June, 23. July and so on.
```
var query = from c in db.Subscription
where c.StartDate.Value.Day == DateTime.Now.Day
// What if today is Feb. 28 and a customer registered January 31.
// What if....
```
I am lost...please help!
Best,
Jon 2H | Why don't you create a seperate table for all due payments.
When a new subscription is taken out, you would calculate all future payment dates for that subscription, and add a number of rows into the DuePayments table with the SubscriptionID, PaymentDate & Amount.
The number of rows would equate to the number of months between the subscription start date and end date, and the payment dates could be easily calculated using DateTime.AddMonths(1) while less than end date. | One way to handle month rollover days is (assuming you want to bill them on the last day of the month in the odd case):
```
var Tomorrow = DateTime.Today.AddDays(1);
var query = from c in db.Subscription
where c.EndDate.Value > DateTime.Today &&
(c.StartDate.Value.Day == DateTime.Today.Day ||
(Tomorrow.Month > DateTime.Today.Month &&
c.StartDate.Value.Day > DateTime.Today.Day))
select c;
```
You might want to create a new table for due payments and calculate the dates upfront instead, though. That way you can keep track of when payments are made as well as make life easier in the future. | Has a month gone by? | [
"",
"c#",
".net",
"linq-to-sql",
""
] |
I'm new to C++ and I have a question...
I tried answering the question myself by making a test application... in debug, the class B initialization generates less assembly code, but in release mode, I can't really say... it optimizes the initializations away :(
Let's say I have two classes:
```
class A
{
public:
int a, b, c, d;
A(int _a, int _b, int _c, int _d) : a(_a), b(_b), c(_c), d(_d)
{
}
};
class B
{
public:
int a, b, c, d;
};
```
Is there any advantage of using
```
B b = {1, 2, 3, 4}
```
instead of
```
A a = A(1, 2, 3, 4);
```
? | I don't know about performance advantages, but in general using the constructor is preferred.
This is because with A, members a,b,c,d can be made private. Thus, you get encapsulation with your A approach, which you don't have in B.
As a class designer, you can enforce strict usage and assignment of member variables via a constructor. In your B, class scenario, you can't.
So while you may get a small boost in perf, for using B, I would wager it to be negligible, and would be negated by the potential headache of having unprotected class members. | For a global objects and static class members, the initializer list doesn't invoke any code on run time. (Initialization data is stored directly in the binary).
If you are initializing a lot of objects, or if the constructor code is expensive / large, this can make a notable difference at load time.
As said, this is true only for plain old data, i.e. everything that can be initialized with an initializer list in C++ < 0x | Advantage using an aggregate initialization list over a constructor? | [
"",
"c++",
"constructor",
"aggregate",
""
] |
Is there a way to integrate background unit tests with the Pydev Eclipse environment?
My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and trace log view).
No, a command prompt running nose on the side does not count.
I have had this Eclipse integration when developing RoR stuff.
Thanks,
Tal.
**EDIT:** Check out the new Pydev (1.6.4) <http://pydev.org/manual_adv_pyunit.html> | This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass a final launch for the whole suite is done (then you can move on to another task).
The current nightly build has this feature incorporated.
 | Pydev does have some unit-test integration, but that's only as a run configuration...so...
This is not a very elegant way, but if you:
1. Enable Project->Build Automatically
2. In your project properties, add a new builder of type Program
3. Configure it to run your tests and select 'during auto builds'
Then at least you will get something that outputs the test results to the console on resource saves. | Continuous unit testing with Pydev (Python and Eclipse) | [
"",
"python",
"unit-testing",
"pydev",
""
] |
I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.
I'm considering implementing a while loop that essentially does
```
ps -ef | grep process name
```
and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already. | Why implement it yourself? An existing utility like [daemon](http://libslack.org/daemon/) or Debian's `start-stop-daemon` is more likely to get the other difficult stuff right about running long-living server processes.
Anyway, when you start the service, put its pid in `/var/run/<name>.pid` and then make your `ps` command just look for that process ID, and check that it is the right process. On Linux you can simply look at `/proc/<pid>/exe` to check that it points to the right executable. | Please don't reinvent init. Your OS has capabilities to do this that require nearly no system resources and will definitely do it better and more reliably than anything you can reproduce.
Classic Linux has /etc/inittab
Ubuntu has /etc/event.d (upstart)
OS X has launchd
Solaris has smf | Auto-restart system in Python | [
"",
"python",
"linux",
"restart",
"pid",
""
] |
I have been developing (for the last 3 hours) a small project I'm doing in C# to help me choose a home.
Specifically, I am putting crime statistics in an overlay on Google maps, to find a nice neighborhood.
Here is an example:
<http://otac0n.com/Demos/prospects.html>
Now, I manually found the Lat and Lng to match the corners of the map displated in the example, but I have a few more maps to overlay.
My new application allows me to choose a landmark and point at the image to tie the Pixel to a LatLng. Something like:
```
locations.Add(new LocationPoint(37.6790f, -97.3125f, "Kellogg and I-135"));
// and later...
targetPoint.Pixel = FindPixel(mouseEvent.Location);
```
So, I've gathered a list of pixel/latlng combinations, and now would like to transform the image (using affine or non-affine transformations).
The goal here is to make every street line up. Given a good map, the only necessary transformation would be a rotation to line the map up north-to-south (and for now I would be happy with that). But I'm not sure where to start.
**Does anybody have any experience doing image transformations in C#? How would I find the proper rotation to make the map level?**
After the case of well-made maps is resolved, I would eventually like to be able to overlay hand drawn maps. This would obviously entail heavy distortion of the final image, and may be beyond the scope of this first iteration. However, I would not like to develop a system that would be un-expandable to this system in the future. | I'm unsure of what exactly do you want to accomplish, but if you want to fit more than three points on one map to more than three points on another one, there are basically two ways you can go:
1. You could try to create a triangular mesh over your points, and then apply a different affine transformation within each triangle, and get a piecewise linear transformation. To get the meshing right, you'll probably need to do something like a [Delaunay triangulation](http://en.wikipedia.org/wiki/Delaunay_triangulation) of the points, for which [qhull](http://www.qhull.org/) should probably be your preferred option.
2. You can go for a higher order transform, such as [quad distortion](https://stackoverflow.com/questions/534297/non-affine-image-transformations-in-net), but it will probably be hard to find a solution that works for any number of points in a generic position. Find yourself a good finite element method book, and read the chapter(s) on higher order isoparametric elements, either lagrangian or serendipity ones, which will provide you with well-behaved mappings of many point to many points. Here are a couple of links([1](http://books.google.es/books?id=nBgZqyepUGwC&pg=PA113&lpg=PA113&dq=isoparametric+elements+higher+order&source=bl&ots=GzZ_gHeSsw&sig=W99aBRA-nDgGlyn5KKlFaKnyPJw&hl=es&ei=8n4uSt-cNcKntgeWk8z6Cw&sa=X&oi=book_result&ct=result&resnum=2) and [2](http://www.jadhavresearch.info/COEP_FEM/ME319_L24.pdf)) to set you on your way. But be aware that the math content is intensive... | In 2D space affine transformation can be specified by two sets of three nonlinear 2D points. In C# you can use the following routine to compute appropriate Matrix:
```
public static Matrix fit(PointF[] src, PointF[] dst) {
Matrix m1 = new Matrix(new RectangleF(0, 0, 1, 1), src);
m1.Invert();
Matrix m2 = new Matrix(new RectangleF(0, 0, 1, 1), dst);
m2.Multiply(m1);
return m2;
}
```
It works for both array arguments having 3 elements.
If you only need rotation and translation, then you can use the following routine:
```
public static Matrix fitOrt(PointF src1, PointF src2, PointF dst1, PointF dst2) {
return fit(new PointF[] { src1, src2, ort(src1, src2) },
new PointF[] { dst1, dst2, ort(dst1, dst2) });
}
public static PointF ort(PointF p, PointF q) {
return new PointF(p.X + q.Y - p.Y, p.Y - q.X + p.X);
}
```
If you would like to find the best approximation between two sets of multiple points then you can start with this <http://elonen.iki.fi/code/misc-notes/affine-fit/> | Image Remapping Algorithm | [
"",
"c#",
"math",
"google-maps",
"image-processing",
"image-manipulation",
""
] |
Is there a quick way in java to get the nest/recurse level?
I'm writing a function to make a list of Groups and their members. The members can be groups as well. It's possible that we could end up with a circular set of groups/member.
I would like to stop at some arbitrary level.
I know I could just keep a variable in a higher scope or pass an incremented parameter but am wondering if there is any stack level information immediately available in Java.
I suppose even if there is, the trick would be to know at which level of nesting you would like to start counting at. So, the point may be moot, however I am still interested if there is any quick info on it. | No need for a Throwable
It won't be fast, but you can use this: <http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace()>
```
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
```
You'll have to traverse the stack in a meaninful way, but that should get you started | You can make a throwable at where you want it and and call [getStackTrace()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()) | Java Stack/Nest Count | [
"",
"java",
"recursion",
""
] |
I need to wrap the Unix command "tail -f" in a BufferedInputStream. I don't want to simulate or mimic tail as stated by [this question](https://stackoverflow.com/questions/557844/java-io-implementation-of-unix-linux-tail-f). Rather, I want to use tail, waiting for it to give me a new line. | Your best bet is to use the `Process` class and read with a `Scanner`:
```
Runtime r = Runtime.getRuntime()
Process p = r.exec("tail -f")
Scanner s = new Scanner(p.getInputStream())
while (s.hasNextLine()) {
String line = s.nextLine()
// Do whatever you want with the output.
}
```
`hasNextLine()` should block as it's waiting for more input from the input stream, so you will not be busy-waiting as data comes in. | Look at Runtime.exec(String command). Returns a **Process** object that has Input and Output Streams. | Java "tail -f" wrapper | [
"",
"java",
"unix",
"tail",
""
] |
Why can't I perform an action like the following:
```
class Test(object):
def __init__(self):
self = 5
t = Test()
print t
```
I would expect it to print `5` since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment.
I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't.
**Update:** I now understand *why* it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance. | *Any* simple assignment to *any* argument of *any* function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. "No special case is special enough to break the rules", as the Zen of Python says!-)
So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly *astonishing* if this specific case worked in any other way, just because of the names of the function and argument in question.
Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible -- but it's obtained by overriding the special method `__new__`, **not** `__init__`:
```
class Test(object):
def __new__(cls):
return 5
t = Test()
print t
```
This *does* emit `5`. The `__new__` / `__init__` behavior in Python is an example of the "two-step construction" design pattern: the "constructor" proper is `__new__` (it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question); `__init__` is the "initializer" which properly initializes the new object.
This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in `__new__`, before the immutable object is constructed, since, given that the object is immutable, `__init__` cannot mutate it in order to initialize it. | It doesnt "ignore" the assignment. The assignment works just fine, you created a local name that points to the data 5.
If you *really* want to do what you are doing...
```
class Test(object):
def __new__(*args):
return 5
``` | Why is `self` in Python objects immutable? | [
"",
"python",
"object",
""
] |
I’m trying to create a FULLTEXT index on an attribute of a table. Mysql returns
> ERROR 1214: The used table type doesn’t support FULLTEXT indexes.
Any idea what I’m doing wrong? | You’re using the wrong type of table. Mysql supports a few different types of tables, but the most commonly used are MyISAM and InnoDB. [MyISAM (in MySQL 5.6+also InnoDB tables) are the types of tables that Mysql supports for Full-text indexes.](http://dev.mysql.com/doc/refman/5.1/en/fulltext-restrictions.html)
To check your table’s type issue the following sql query:
```
SHOW TABLE STATUS
```
Looking at the result returned by the query, find your table and corresponding value in the Engine column. If this value is anything except MyISAM or InnoDB then Mysql will throw an error if your trying to add FULLTEXT indexes.
To correct this, you can use the sql query below to change the engine type:
```
ALTER TABLE <table name> ENGINE = [MYISAM | INNODB]
```
Additional information (thought it might be useful):
Mysql using different engine storage types to optimize for the needed functionality of specific tables. Example MyISAM is the default type for operating systems (besides windows), preforms SELECTs and INSERTs quickly; but does not handle transactions. InnoDB is the default for windows, can be used for transactions. But InnoDB does require more disk space on the server. | Up until MySQL 5.6, MyISAM was the only storage engine with support for full-text search (FTS) but it is true that InnoDB FTS in MySQL 5.6 is syntactically identical to MyISAM FTS. Please read below for more details.
[InnoDB Full-text Search in MySQL 5.6](http://www.mysqlperformanceblog.com/2013/02/26/myisam-vs-innodb-full-text-search-in-mysql-5-6-part-1/) | MySQL FULLTEXT indexes issue | [
"",
"mysql",
"sql",
"mysql-error-1214",
""
] |
When I start my application I get: ***The ConnectionString property has not been initialized.***
Web.config:
```
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User Id=myuser;Password=mypassword;" />
</connectionStrings>
```
The stack being:
```
System.Data.SqlClient.SqlConnection.PermissionDemand() +4876643
System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
```
I'm fairly new to .NET and I don't get this one. I found a lot of answers on Google, but none really fixed my issue.
What does that mean? Is my web.config bad? Is my function bad? Is my SQL configuration not working correctly (I'm using sqlexpress)?
My main problem here is that I'm not sure where to start to debug this... anything would help.
EDIT:
Failling code:
```
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.AppSettings["ConnectionString"],
CommandType.Text,
sqlQuery,
sqlParams);
```
sqlQuery is a query like "select \* from table". sqlParams is not relevant here.
The other problem here is that my company uses MySQLHelper, and I have no visibility over it (only have a dll for a helper lib). It has been working fine in other projects, so I'm 99% that the error doesn't come from here.
I guess if there's no way of debuging it without seeing the code I'll have to wait to get in touch with the person who created this helper in order to get the code. | Referencing the connection string should be done as such:
```
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
```
`ConfigurationManager.AppSettings["ConnectionString"]` would be looking in the `AppSettings` for something named `ConnectionString`, which it would not find. This is why your error message indicated the `"ConnectionString" property has not been initialized`, because it is looking for an initialized property of `AppSettings` named `ConnectionString`.
`ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString` instructs to look for the connection string named "MyDB".
[Here is someone talking about using web.config connection strings](http://weblogs.asp.net/owscott/archive/2005/08/26/Using-connection-strings-from-web.config-in-ASP.NET-v2.0.aspx) | You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).
If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.
```
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);
```
If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.
Post your code (for the databound element and the web.config to be safe) and we can take a look at it.
**EDIT:** I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with `ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString` (if ConnectionString is the name of your connection string.) | How to fix "The ConnectionString property has not been initialized" | [
"",
"c#",
"asp.net",
"connection-string",
"database-connection",
""
] |
I’m writing text to a binary file in C# and see a difference in quantity written between writing a string and a character array. I’m using System.IO.BinaryWriter and watching BinaryWriter.BaseStream.Length as the writes occur. These are my results:
```
using(BinaryWriter bw = new BinaryWriter(File.Open(“data.dat”), Encoding.ASCII))
{
string value = “Foo”;
// Writes 4 bytes
bw.Write(value);
// Writes 3 bytes
bw.Write(value.ToCharArray());
}
```
I don’t understand why the string overload writes 4 bytes when I’m writing only 3 ASCII characters. Can anyone explain this? | The documentation for [`BinaryWriter.Write(string)`](http://msdn.microsoft.com/en-us/library/yzxa6408.aspx) states that it writes a length-prefixed string to this stream. The overload for [`Write(char[])`](http://msdn.microsoft.com/en-us/library/k13xbf58.aspx) has no such prefixing.
It would seem to me that the extra data is the length.
EDIT:
Just to be a bit more explicit, use Reflector. You will see that it has this piece of code in there as part of the `Write(string)` method:
```
this.Write7BitEncodedInt(byteCount);
```
It is a way to encode an integer using the least possible number of bytes. For short strings (that we would use day to day that are less than 128 characters), it can be represented using one byte. For longer strings, it starts to use more bytes.
Here is the code for that function just in case you are interested:
```
protected void Write7BitEncodedInt(int value)
{
uint num = (uint) value;
while (num >= 0x80)
{
this.Write((byte) (num | 0x80));
num = num >> 7;
}
this.Write((byte) num);
}
```
After prefixing the the length using this encoding, it writes the bytes for the characters in the desired encoding. | From the `BinaryWriter.Write(string)` [docs](http://tinyurl.com/n5fsap):
Writes a **length-prefixed** string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
This behavior is probably so that when reading the file back in using a `BinaryReader` the string can be identified. (e.g. `3Foo3Bar6Foobar` can be parsed into the string "Foo", "Bar" and "Foobar" but `FooBarFoobar` could not be.) In fact, `BinaryReader.ReadString` uses exactly this information to read a `string` from a binary file.
From the `BinaryWriter.Write(char[])` [docs](http://tinyurl.com/klk2ud):
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
It is hard to overstate how comprehensive and useful the docs on MSDN are. Always check them first. | Difference in writing string vs. char array with System.IO.BinaryWriter | [
"",
"c#",
"string",
"encoding",
"file",
"binaryfiles",
""
] |
Have a long running set of discrete tasks: parsing 10s of thousands of lines from a text file, hydrating into objects, manipulating, and persisting.
If I were implementing this in Java, I suppose I might add a new task to an Executor for each line in the file or task per X lines (i.e. chunks).
For .Net, which is what I am using, I'm not so sure. I have a suspicion maybe CCR might be appropriate here, but I'm not familiar enough with it, which is why I pose this question.
Can CCR function in an equivalent fashion to Java Executors, or is there something else available?
Thanks | You may want to look at the [Task Parallel Library](https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx).
As of C# 5 this is built into the language using the `async` and `await` keywords. | Maybe this is related: [Design: Task Parallel Library explored](http://blogs.msdn.com/salvapatuel/archive/2007/11/11/task-parallel-library-explored.aspx).
See [10-4 Episode 6: Parallel Extensions](http://channel9.msdn.com/shows/10-4/10-4-Episode-6-Parallel-Extensions/) as a quick intro.
For older thread-based approach, there's [ThreadPool](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx) for pooling. | Is there a .Net equivalent to java.util.concurrent.Executor? | [
"",
"java",
".net",
"multithreading",
"concurrency",
"ccr",
""
] |
I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle file when the application called for it. The parameters supplied by the user will be used to lookup the needed output.
I selected this structure because I have gotten pretty comfortable with dictionaries and pickle files and I see this going out the door with the smallest learning curve on my part. There might be as many as two million keys in the dictionary. I have been satisfied with the performance on my machine with a reasonable subset. I have already thought through about how to break the dictionary apart if I have any performance concerns when the whole thing is put together. I am not really that worried about the amount of disk space on their machine as we are working with terabyte storage values.
Having said all of that I have been poking around in the docs and am wondering if I need to invest some time to learn and implement an alternative data storage file. The only reason I can think of is if there is an alternative that could increase the lookup speed by a factor of three to five or more. | The standard `shelve` module will give you a persistent dictionary that is stored in a dbm style database. Providing that your keys are strings and your values are picklable (since you're using pickle already, this must be true), this could be a better solution that simply storing the entire dictionary in a single pickle.
Example:
```
>>> import shelve
>>> d = shelve.open('mydb')
>>> d['key1'] = 12345
>>> d['key2'] = value2
>>> print d['key1']
12345
>>> d.close()
```
I'd also recommend [Durus](http://www.mems-exchange.org/software/durus/), but that requires some extra learning on your part. It'll let you create a PersistentDictionary. From memory, keys can be any pickleable object. | To get fast lookups, use the standard Python `dbm` module (see <http://docs.python.org/library/dbm.html>) to build your database file, and do lookups in it. The dbm file format may not be cross-platform, so you may want to to distrubute your data in Pickle or repr or JSON or YAML or XML format, and build the `dbm` database the user runs your program. | What is the least resource intense data structure to distribute with a Python Application | [
"",
"python",
"database",
"dictionary",
""
] |
I have a `for`-loop which runs for 1000+ times over a string array.
I want to have my app break when one of the strings matches a certain term.
So I can walk through my code from that point.
Now, I know I can add a piece of code that looks for this and a breakpoint when it hits, but is there not a way to do this in the debugger? | Go to your code
1. create a breakpoint
2. right click on the red dot on the left
3. select *condition*
4. put something like *i == 1000*
or
at the middle of your loop
write
```
if (i == 1000){
int a = 1;
}
```
and break over int a = 1;
The second method looks more like garbage, but I find it easier and faster to do | Yes, you can in the debugger. It's called a "conditional breakpoint." Basically, right click on the red breakpoint and go to the "condition" option.
A quick google turned [this](http://msdn.microsoft.com/en-us/library/7sye83ce.aspx) and [this](http://support.microsoft.com/kb/308469) up:
P.S. The last one is VS 2005, but it's the same in 2008. | How to break a loop at a certain point in Visual Studio debugger? | [
"",
"c#",
"visual-studio",
"debugging",
"visual-studio-2008",
"breakpoints",
""
] |
My goal is assign a global hotkey (JIntellitype, JXGrabKey) that would pass an arbitrary selected text to a java app.
The initial plan is to utilize the java.awt.Robot to emulate Ctrl-C keypress and then get the value from clipboard.
Probably there's a more elegant solution?
EXAMPLE: Open Notepad, type in some text, select that text. Now, that text needs to be copied into a Java app. | I've gone with with Robot and that works just fine. | I guess you want to implement a global input monitor, Java is not so straightforward to do the job. You may have to write an API hook and pack it in a DLL, then invoke it via JNI. | Copying selected text to a Swing Java app? | [
"",
"java",
"swing",
"clipboard",
"hotkeys",
""
] |
In my course, I am told:
> Continuous values are represented approximately in memory, and therefore computing with floats involves rounding errors. These are tiny discrepancies in bit patterns; thus the test `e==f` is unsafe if `e` and `f` are floats.
Referring to Java.
Is this true? I've used comparison statements with `double`s and `float`s and have never had rounding issues. Never have I read in a textbook something similar. Surely the virtual machine accounts for this? | It is true.
It is an inherent limitation of how floating point values are represented in memory in a finite number of bits.
This program, for instance, prints "false":
```
public class Main {
public static void main(String[] args) {
double a = 0.7;
double b = 0.9;
double x = a + 0.1;
double y = b - 0.1;
System.out.println(x == y);
}
}
```
Instead of exact comparison with '==' you usually decide on some level of precision and ask if the numbers are "close enough":
```
System.out.println(Math.abs(x - y) < 0.0001);
``` | This applies to Java just as much as to any other language using floating point. It's inherent in the design of the representation of floating point values in hardware.
More info on floating point values:
[What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) | Rounding Errors? | [
"",
"java",
"memory",
"floating-accuracy",
""
] |
I have the followng code:
```
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = bDisabled;
}
```
I need to now add some logic to only disable the the inputs that have and Id of the form "bib\*" where bib can be any character. Ive seen other questions where this is done with jquery but I cant use jquery just simple javascript. Any help would be appreciated.
Thanks | This is pretty basic stuff.
```
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("bib") == 0)
inputs[i].disabled = bDisabled;
}
``` | ```
function CheckDynamicValue(partialid, value) {
var re = new RegExp(partialid, 'g');
var elems = document.getElementsByTagName('*'), i = 0, el;
while (el = elems[i++]) {
if (el.id.match(re)) {
el.disabled = value;
}
}
}
``` | Getting elements by a partial id string in javascript | [
"",
"javascript",
""
] |
I haven't touch C++ in more then 8 years. I recently had to do fix some C++ code, and although I still can code, I feel like I no more belongs to the camp of C++ programmers. I don't know any libraries, didn't pay attention to the new language features / improvements / best practices.
Qt Creator and Qt seems like a nice toolset for what I need now, since I'm interested mostly in cross platform development.
What would be good resources for someone like me to quickly re-learn C++ and best practices in shortest period of time?
I have been doing mostly java and common lisp in the meantime, with a short strides to C, flex, Scala and Haskell. | Get to know the S.tandard T.emplate L.ibrary.
Get to know boost, if you are really on the cutting edge.
Read the books "effective c++", and "effective STL" by scott meyers.
Read the "[C++ faq lite](http://www.parashift.com/c++-faq-lite/)".
(not necsissarily in that order) | Read :
* [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0201924889)
* [More effective C++](https://rads.stackoverflow.com/amzn/click/com/020163371X)
* [Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629)
* [Exceptional C++](https://rads.stackoverflow.com/amzn/click/com/0201615622)
* [C++ coding standards](https://rads.stackoverflow.com/amzn/click/com/0321113586)
Those are references books on C++ that resume all the modern effective pratices, philosophies and knowledge on C++ (without going into Meta-Programmation stuff).
Then if you want to go farther, read :
* [Modern C++ Design](https://rads.stackoverflow.com/amzn/click/com/0201704315) - this one is known to blow minds...
* [C++ Template Metaprogramming](https://rads.stackoverflow.com/amzn/click/com/0321227255)
About libraries: first learn about the STL and learn to use [Boost](http://boost.org) as a "standard" STL extension. | Re-learn modern C++ resources? | [
"",
"c++",
"resources",
""
] |
I am using PdfBox in Java to extract text from PDF files. Some of the input files provided are not valid and PDFTextStripper halts on these files. Is there a clean way to check if the provided file is indeed a valid PDF? | you can find out the mime type of a file (or byte array), so you dont dumbly rely on the extension. I do it with aperture's MimeExtractor (<http://aperture.sourceforge.net/>) or I saw some days ago a library just for that (<http://sourceforge.net/projects/mime-util>)
I use aperture to extract text from a variety of files, not only pdf, but have to tweak thinks for pdfs for example (aperture uses pdfbox, but i added another library as fallback when pdfbox fails) | Here is what I use into my NUnit tests, that must validate against multiple versions of PDF generated using Crystal Reports:
```
public static void CheckIsPDF(byte[] data)
{
Assert.IsNotNull(data);
Assert.Greater(data.Length,4);
// header
Assert.AreEqual(data[0],0x25); // %
Assert.AreEqual(data[1],0x50); // P
Assert.AreEqual(data[2],0x44); // D
Assert.AreEqual(data[3],0x46); // F
Assert.AreEqual(data[4],0x2D); // -
if(data[5]==0x31 && data[6]==0x2E && data[7]==0x33) // version is 1.3 ?
{
// file terminator
Assert.AreEqual(data[data.Length-7],0x25); // %
Assert.AreEqual(data[data.Length-6],0x25); // %
Assert.AreEqual(data[data.Length-5],0x45); // E
Assert.AreEqual(data[data.Length-4],0x4F); // O
Assert.AreEqual(data[data.Length-3],0x46); // F
Assert.AreEqual(data[data.Length-2],0x20); // SPACE
Assert.AreEqual(data[data.Length-1],0x0A); // EOL
return;
}
if(data[5]==0x31 && data[6]==0x2E && data[7]==0x34) // version is 1.4 ?
{
// file terminator
Assert.AreEqual(data[data.Length-6],0x25); // %
Assert.AreEqual(data[data.Length-5],0x25); // %
Assert.AreEqual(data[data.Length-4],0x45); // E
Assert.AreEqual(data[data.Length-3],0x4F); // O
Assert.AreEqual(data[data.Length-2],0x46); // F
Assert.AreEqual(data[data.Length-1],0x0A); // EOL
return;
}
Assert.Fail("Unsupported file format");
}
``` | How can I determine if a file is a PDF file? | [
"",
"java",
"validation",
"pdf",
"text",
""
] |
I have a memory leak in my C# program and cannot determine who is holding the reference to my object. Is there a way at runtime to determine which objects are holding a reference to a specific object?
In this economy my budget is zero, so a native or free solution is my only choice. | Check out [.NET Memory Profiler](http://memprofiler.com/). They have a 14 day free trial (so your budget is safe). Excerpt from the features page ...
> For a managed type instance the
> following additional information is
> presented:
>
> * References from and to the instance
Per comments: Agree 100% ... well worth the very reasonable license fee. | For a free tool take a look [here](http://blogs.msdn.com/ricom/archive/2004/12/10/279612.aspx). This article discusses how to use the free tools from MS (windbg/sos) to find memory leaks in managed code. The interface is not pretty, but it gets the job done. Here is a link to [windbg](http://www.microsoft.com/whdc/DevTools/Debugging/debugstart.mspx). | Is it possible to determine if an object is being referenced by another object? | [
"",
"c#",
""
] |
What I have is basically a problem which is easily solved with multiple tables, but I have only a single table to do it.
Consider the following database table
```
UserID UserName EmailAddress Source
3K3S9 Ben ben@myisp.com user
SF13F Harry lharry_x@hotbail.com 3rd_party
SF13F Harry reside@domain.com user
76DSA Lisa cake@insider.com user
OL39F Nick stick@whatever.com 3rd_party
8F66S Stan myman@lol.com user
```
I need to select all fields, but only who each user once along with one of their email addresses (the "biggest" one as determined by the MAX() function). This is the result I am after ...
```
UserID UserName EmailAddress Source
3K3S9 Ben ben@myisp.com user
SF13F Harry lharry_x@hotbail.com 3rd_party
76DSA Lisa cake@insider.com user
OL39F Nick stick@whatever.com 3rd_party
8F66S Stan myman@lol.com user
```
As you can see, "Harry" is only shown once with his "highest" email address the correcponding "source"
Currently what is happening is that we are grouping on the UserID, UserName, and using MAX() for the EmailAddress and Source, but the max of those two fields dont always match up, they need to be from the same record.
I have tried another process by joining the table with itself, but I have only managed to get the correct email address but not the corresponding "source" for that address.
Any help would be appreciated as I have spent way too long trying to solve this already :) | If you're on SQL Server 2005 or higher,
```
SELECT UserID, UserName, EmailAddress, Source
FROM (SELECT UserID, UserName, EmailAddress, Source,
ROW_NUMBER() OVER (PARTITION BY UserID
ORDER BY EmailAddress DESC)
AS RowNumber
FROM MyTable) AS a
WHERE a.RowNumber = 1
```
Of course there are ways to do the same task without the (SQL-Standard) ranking functions such as `ROW_NUMBER`, which SQL Server implemented only since 2005 -- including nested dependent queries and self left joins with an `ON` including a '>' and a `WHERE ... IS NULL` trick -- but the ranking functions make for code that's readable and (in theory) well optimizable by the SQL Server Engine.
Edit: [this article](http://weblogs.sqlteam.com/jeffs/archive/2007/03/28/60146.aspx) is a nice tutorial on ranking, but it uses `RANK` in the examples instead of `ROW_NUMBER` (or the other ranking function, `DENSE_RANK`) -- the distinction matters when there are "ties" among grouped rows in the same partition according to the ordering criteria. [this post](http://thehobt.blogspot.com/2009/02/rownumber-rank-and-denserank.html) does a good job explaining the difference. | ```
select distinct * from table t1
where EmailAddress =
(select max(EmailAddress) from table t2
where t1.userId = t2.userId)
``` | SQL - SELECT MAX() and accompanying field | [
"",
"sql",
"database",
"join",
""
] |
I have two tables, "splits" and "dividends" that describe events in the stock market.
The splits table has "day", "ratio", and "ticker".
The dividends table has "day", "amount", and "ticker".
I would like to get a resulting joined table that has both tables' information, AND sorted by date and ticker. So something like this: (sorry about the formatting)
```
splits.day splits.ratio splits.ticker dividends.day dividends.amount dividends.ticker
1990-01-03 2 QQQQ null null null
null null null 1995-05-05 15.55 SPY
2000-09-15 3 DIA null null null
null null null 2005-03-15 3 DIA
```
I looked up full outer joins on wikipedia (using unions on mysql) but I couldn't figure out how to get it to be sorted by the day... Any help would be greatly appreciated!
EDIT: here's an example of what splits and dividends contain in the above example
```
splits.day splits.ratio splits.ticker
1990-01-03 2 QQQQ
2000-09-15 3 DIA
dividends.day dividends.amount dividends.ticker
1995-05-05 15.55 SPY
2005-03-15 3.55 QQQQ
``` | OK, based on your edits, it looks to me like you don't really want a join at all. You probably want to do this:
```
select *
from
(
select day, ticker, ratio, null as amount
from splits
union
select day, ticker, null as ratio, amount
from dividends
) as q
order by day, ticker
``` | to do Full Outer Join :
```
select splits.day splits.ratio splits.ticker dividends.day dividends.amount dividends.ticker from splits , dividends where splits.ticker = dividends.ticker order by splits.day
``` | Join Statement in SQL | [
"",
"mysql",
"sql",
"join",
""
] |
I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH? | I just realized CopSSH is based on Cygwin which I think means paths would have to be specified differently. Try using, for example,
`/cygdrive/c/Program\ Files/My\ Program/myprog.exe`
instead of
`"C:\Program Files\My Program\myprog.exe"`.
BTW, the following CopSSH FAQ might be applicable as well: <http://www.itefix.no/i2/node/31>. | I suspect CopSSH is giving you different environment vars to a normal GUI login. I'd suggest you type 'set' and see if perl is in the path with any other environment vars it might need.
Here is some explanation of [setting up the CopSSH user environment](http://apps.sourceforge.net/mediawiki/controltier/index.php?title=OpenSSH_on_Windows). It may be of use. | Perl and CopSSH | [
"",
"python",
"perl",
"ssh",
"openssh",
""
] |
I am working in Eclipse on a Google AppEngine Java code. Every time I save a java file, the DataNucleus Enchancer starts off "Enhancement of Classes". Its quite irritating since it takes away focus when you are in full screen mode. Anybody knows how I can turn it off?
If I turn it off, will it affect my ability to deploy my application to App Engine from within Eclipse? | You can restrict which classes DataNucleus watches for changes so that it only re-runs the enhancement when your model classes actually change.
Go to the Project's properties, and select Google->App Engine->Orm. There you can specify patterns for the files to watch.
For example, I put all my model beans in a model/ subdirectory, so a pattern of src/\*\*/model works for me. There are also example patterns under the 'Add' dialogue. | The Enhancer is setup as a Builder in your project properties. I suspect you could safely disable it while you are editing, and then when you want to run it you would have to re-enable and build again to ensure that any changes you made to persistent classes are reflected correctly before you try to run or test your application locally. Then, you could upload to app engine. | How to turn off DataNucleus Enhancer while working with Google App Engine | [
"",
"java",
"eclipse",
"google-app-engine",
"datanucleus",
""
] |
In Java 5, is there a default way to pass a URL to the system and have it launch the application associated with it?
For example http:// links would usually open IE or Firefox, but things like itms:// should open iTunes.
If possible I would rather not use Runtime.exec() to start some external process directly, because this would be platform specific. If there is no other way, what would I call for Windows/OS X and Linux to cover the most popular ones? | I agree with ivan that Java Desktop API would work, but it's 6 only.
I know how to do it on Windows (it involves executing rundll32.dll), but I did some quick Googling and [this link](http://www.java2s.com/Code/Java/Development-Class/LaunchBrowserinMacLinuxUnix.htm) seems like your best shot.
Hope that helps. | Use the [Java Desktop API](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/)
```
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(uri);
}
``` | Java: How to launch system's registered application for a URL | [
"",
"java",
"url",
"desktop",
""
] |
I'm not sure if I have the jargon for asking this question not being a web developer but please bear with me.
I want to send parameters to a client side HTML page (just a file on a disk no web server involved). My initial attempt was to use a query string and then parse it from `window.location.href` but instead of the query string being passed to the page I get a **file not found** error.
Is it possible to do what I'm attempting? | You might want to pass parameters using the # instead of ? on local files. | Firefox and Chrome will let you do this. But IE won't. IE returns file not found like you said.
```
file:///D:/tmp/test.htm?blah=1
<script language='javascript'>
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
alert(getUrlVars());
</script>
``` | Can I pass parameters to a client-side HTML page? | [
"",
"javascript",
"html",
"parameters",
"query-string",
"client-side",
""
] |
Yesterday I ran into an Issue while developing a Web Part (This question is not about webpart but about C#). Little background about the Issue. I have a code that load the WebPart using the Reflection, In which I got the AmbiguousMatchException. To reproduce it try the below code
```
public class TypeA
{
public virtual int Height { get; set; }
}
public class TypeB : TypeA
{
public String Height { get; set; }
}
public class Class1 : TypeB
{
}
Assembly oAssemblyCurrent = Assembly.GetExecutingAssembly();
Type oType2 = oAssemblyCurrent.GetType("AmbigousMatchReflection.Class1");
PropertyInfo oPropertyInfo2 = oType2.GetProperty("Height");//Throws AmbiguousMatchException
oPropertyInfo2 = oType2.GetProperty("Height",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); // I tried this code Neither these BindingFlags or any other didnt help
```
I wanted to know the BindingFlag to Fetch the Height Property. You will have the question of why I wanted to create another Height Property that is already there in the Base class. That is how the `Microsoft.SharePoint.WebPartPages.PageViewerWebPart` was designed check the Height property of the PageViewerWebPart class. | There are two `Height` properties there, and *neither* of them are declared by Class1 which you're calling `GetProperty` on.
Now, would it be fair to say you're looking for "the Height property declared as far down the type hiearchy as possible"? If so, here's some code to find it:
```
using System;
using System.Diagnostics;
using System.Reflection;
public class TypeA
{
public virtual int Height { get; set; }
}
public class TypeB : TypeA
{
public new String Height { get; set; }
}
public class Class1 : TypeB
{
}
class Test
{
static void Main()
{
Type type = typeof(Class1);
Console.WriteLine(GetLowestProperty(type, "Height").DeclaringType);
}
static PropertyInfo GetLowestProperty(Type type, string name)
{
while (type != null)
{
var property = type.GetProperty(name, BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance);
if (property != null)
{
return property;
}
type = type.BaseType;
}
return null;
}
}
```
Note that if you *know* the return types will be different, it *may* be worth simplifying the code as shown in [sambo99's answer](https://stackoverflow.com/questions/994698/ambiguousmatchexception-type-getproperty-c-reflection/994717#994717). That would make it quite brittle though - changing the return type later could then cause bugs which would only be found at execution time. Ouch. I'd say that by the time you've done this you're in a brittle situation anyway :) | See the following example:
```
class Foo {
public float Height { get; set; }
}
class Bar : Foo {
public int Height { get; set; }
}
class BarBar : Bar { }
class Foo2 : Foo{
public float Height { get; set; }
}
class BarBar2 : Foo2 { }
static void Main(string[] args) {
// works
var p = typeof(BarBar).GetProperty("Height", typeof(float), Type.EmptyTypes);
// works
var p2 = typeof(BarBar).BaseType.GetProperty("Height", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
// works
var p3 = typeof(BarBar2).GetProperty("Height");
// fails
var p4 = typeof(BarBar).GetProperty("Height");
Console.WriteLine(p);
}
```
* You get an AmbiguousMatchException if a two or more properties with the **differing** return types and the **same name** live in your inheritance chain.
* Stuff resolves just fine if you override an implementation (using new or override) and maintain the return type.
* You can force reflection only to look at the properties for a particular type. | AmbiguousMatchException - Type.GetProperty - C# Reflection | [
"",
"c#",
""
] |
I get a seg fault for the simple program below. It seems to be related to the destructor match\_results.
```
#include <iostream>
#include <vector>
#include <string>
#include <boost/regex.hpp>
using namespace std;
int main(int argc, char *argv)
{
boost::regex re;
boost::cmatch matches;
boost::regex_match("abc", matches, re.assign("(a)bc"));
return 0;
}
```
edit: I am using boost 1.39 | boost::regex is one of the few components of boost that doesn't exist solely in header files...there is a library module.
It is likely that the library you are using was built with different settings than your application.
**Edit:** Found an example scenario with [this known boost bug](https://svn.boost.org/trac/boost/ticket/2535), where boost must be built with the same `-malign-double` flag as your application.
This is one of several possible scenarios where your boost library will not have binary compatibility with your application. | Which version of boost are you using?
I compiled the above example with boost 1.36 and I don't get any seg faults.
If you have multiple boost libraries make sure that at runtime you're picking up the correct version.
Boost regex requires to be compiled against library `-lboost_regex-gcc_whatever-is-your- version`
In my case:
```
g++ -c -Wall -I /include/boost-1_36_0 -o main.o main.cpp
g++ -Wall -I /include/boost-1_36_0 -L/lib/boost-1_36_0 -lboost_regex-gcc33-mt main.o -o x
```
to execute:
```
LD_LIBRARY_PATH=/lib/boost-1_36_0 ./x
```
You would point to the location of boost include/libs on your system, note the version of gcc and m(ulti) t(hreaded) in library name - it depends on what you have compiled, just look in your boost lib directory and pick one version of regex library from there. | boost::regex segfaults when using capture | [
"",
"c++",
"boost-regex",
""
] |
What is the difference between two, if any (with respect to .Net)? | Depends on the platform. On Windows it is actually "\r\n".
From MSDN:
> A string containing "\r\n" for
> non-Unix platforms, or a string
> containing "\n" for Unix platforms. | Exact implementation of `Environment.NewLine` from the source code:
The implementation in .NET 4.6.1:
```
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
** platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result<String>() != null);
return "\r\n";
}
}
```
[source](http://referencesource.microsoft.com/#mscorlib/system/environment.cs#63a04833d43dd9d3)
---
The implementation in .NET Core:
```
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
** given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
get {
Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
return "\r\n";
#else
return "\n";
#endif // !PLATFORM_UNIX
}
}
```
[source](https://source.dot.net/#System.Private.CoreLib/src/System/Environment.cs,63a04833d43dd9d3) (in `System.Private.CoreLib`)
```
public static string NewLine => "\r\n";
```
[source](https://source.dot.net/#System.Runtime.Extensions/System/Environment.Windows.cs,63a04833d43dd9d3) (in `System.Runtime.Extensions`) | Difference between "\n" and Environment.NewLine | [
"",
"c#",
".net",
"cross-platform",
""
] |
Where can I find a library with collections of fluent methods as in Rails
I found some [here](http://fluentdatetime.codeplex.com/) | here
<http://ayende.com/projects/rhino-mocks.aspx>
<http://flimflan.com/blog/ReadableRegularExpressions.aspx> | [CuttingEdge.Conditions](http://conditions.codeplex.com/) is another one. | Fluent methods library for C# | [
"",
"c#",
".net",
""
] |
I think I understand the basic concepts of MVC - the Model contains the data and behaviour of the application, the View is responsible for displaying it to the user and the Controller deals with user input. What I'm uncertain about is exactly *what* goes in the Controller.
Lets say for example I have a fairly simple application (I'm specifically thinking Java, but I suppose the same principles apply elsewhere). I organise my code into 3 packages called `app.model`, `app.view` and `app.controller`.
Within the `app.model` package, I have a few classes that reflect the actual behaviour of the application. These `extends Observable` and use `setChanged()` and `notifyObservers()` to trigger the views to update when appropriate.
The `app.view` package has a class (or several classes for different types of display) that uses `javax.swing` components to handle the display. Some of these components need to feed back into the Model. If I understand correctly, the View shouldn't have anything to do with the feedback - that should be dealt with by the Controller.
So what do I actually put in the Controller? Do I put the `public void actionPerformed(ActionEvent e)` in the View with just a call to a method in the Controller? If so, should any validation etc be done in the Controller? If so, how do I feedback error messages back to the View - should that go through the Model again, or should the Controller just send it straight back to View?
If the validation is done in the View, what do I put in the Controller?
Sorry for the long question, I just wanted to document my understanding of the process and hopefully someone can clarify this issue for me! | In the example you suggested, you're right: "user clicked the 'delete this item' button" in the interface should basically just call the controller's "delete" function. The controller, however, has no idea what the view looks like, and so your view must collect some information such as, "which item was clicked?"
In a conversation form:
**View**: "Hey, controller, the user just told me he wants item 4 deleted."
**Controller**: "Hmm, having checked his credentials, he is allowed to do that... Hey, model, I want you to get item 4 and do whatever you do to delete it."
**Model**: "Item 4... got it. It's deleted. Back to you, Controller."
**Controller**: "Here, I'll collect the new set of data. Back to you, view."
**View**: "Cool, I'll show the new set to the user now."
In the end of that section, you have an option: either the view can make a separate request, "give me the most recent data set", and thus be more pure, or the controller implicitly returns the new data set with the "delete" operation. | The problem with `MVC` is that people think the view, the controller, and the model have to be as independent as possible from each other. They do not - a view and controller are often intertwined - think of it as `M(VC)`.
The controller is the input mechanism of the user interface, which is often tangled up in the view, particularly with GUIs. Nevertheless, view is output and controller is input. A view can often work without a corresponding controller, but a controller is usually far less useful without a view. User-friendly controllers use the view to interpret the user's input in a more meaningful, intuitive fashion. This is what it makes it hard separate the controller concept from the view.
Think of an radio-controlled robot on a detection field in a sealed box as the model.
The model is all about state and state transitions with no concept of output (display) or what is triggering the state transitions. I can get the robot's position on the field and the robot knows how to transition position (take a step forward/back/left/right. Easy to envision without a view or a controller, but does nothing useful
Think of a view without a controller, e.g. someone in a another room on the network in another room watching the robot position as (x,y) coordinates streaming down a scrolling console. This view is just displaying the state of the model, but this guy has no controller. Again, easy to envision this view without a controller.
Think of a controller without a view, e.g. someone locked in a closet with the radio controller tuned to the robot's frequency. This controller is sending input and causing state transitions with no idea of what they are doing to the model (if anything). Easy to envision, but not really useful without some sort of feedback from the view.
Most user-friendly UI's coordinate the view with the controller to provide a more intuitive user interface. For example, imagine a view/controller with a touch-screen showing the robot's current position in 2-D and allows the user to touch the point on the screen that just happens to be in front of the robot. The controller needs details about the view, e.g. the position and scale of the viewport, and the pixel position of the spot touched relative to the pixel position of the robot on the screen) to interpret this correctly (unlike the guy locked in the closet with the radio controller).
Have I answered your question yet? :-)
The controller is anything that takes input from the user that is used to cause the model to transition state. Try to keep the view and controller a separated, but realize they are often interdependent on each other, so it is okay if the boundary between them is fuzzy, i.e. having the view and controller as separate packages may not be as cleanly separated as you would like, but that is okay. You may have to accept the controller won't be cleanly separated from the view as the view is from the model.
> ... should any validation etc be
> done in the Controller? If so, how do
> I feedback error messages back to the
> View - should that go through the
> Model again, or should the Controller
> just send it straight back to View?
>
> If the validation is done in the View,
> what do I put in the Controller?
I say a linked view and controller should interact freely without going through the model. The controller take the user's input and should do the validation (perhaps using information from the model and/or the view), but if validation fails, the controller should be able to update its related view directly (e.g. error message).
The acid test for this is to ask yourself is whether an independent view (i.e. the guy in the other room watching the robot position via the network) should see anything or not as a result of someone else's validation error (e.g. the guy in the closet tried to tell the robot to step off the field). Generally, the answer is no - the validation error prevented the state transition. If there was no state tranistion (the robot did not move), there is no need to tell the other views. The guy in the closet just didn't get any feedback that he tried to cause an illegal transition (no view - bad user interface), and no one else needs to know that.
If the guy with the touchscreen tried to send the robot off the field, he got a nice user friendly message asking that he not kill the robot by sending it off the detection field, but again, no one else needs to know this.
If other views *do* need to know about these errors, then you are effectively saying that the inputs from the user and any resulting errors are *part of the model* and the whole thing is a little more complicated ... | What goes into the "Controller" in "MVC"? | [
"",
"java",
"model-view-controller",
""
] |
```
Dictionary <string, List <SaleItem>> saleItemNew = new Dictionary<string, List< SaleItem>> ();
saleItems = new List <SaleItem> ();
saleItemNew.Add("1", saleItems);
```
**At this point the list in the Dictionary has values.**
```
saleItems.Clear();
```
**However, when I clear out the list previously assigned to it, the dictionary's value List is now empty...why?** | The dictionary contains the same reference to the list, so modifying the list will change both references.
Microsoft documentation about reference types: <http://msdn.microsoft.com/en-us/library/490f96s2.aspx> | The reason is that Dictionary is a reference and not a value type. When you assign a Dictionary to another variable it does not perform a deep copy. Instead it just points another reference at the same object. Since there is only one object, clearing via either reference will be visible to both references.
This in contrast to value types in the .Net Framework. Assignment of a value type essentially performs a shallow copy of the data and creates two independent objects. Note, that if the value type has a reference field, the two field in the two value types will still point to the same object. | C# dictionary value clearing out when I clear list previously assigned to it....why? | [
"",
"c#",
"dictionary",
""
] |
I want to redefine the ToString() function in one of my classes.
I wrote
```
public string ToString()
```
... and it's working fine. But ReSharper is telling me to change this to either
```
public new string ToString()
```
or
```
public override string ToString()
```
What's the difference? Why does C# requires something like this? | If you use `public string ToString()` it is unclear what you **intended** to do. If you mean to change the behaviour of `ToString` via polymorphism, then `override`. You **could** add a `new ToString()`, but that would be silly. Don't do that!
The difference is what happens when you do:
```
MyType t = new MyType();
object o = t;
Console.WriteLine(t.ToString());
Console.WriteLine(o.ToString());
```
If you `override`, both will output your new version. If you `new`, only the first will use your new version; the second will use the original implementation.
I don't think I've **ever** seen anybody use method hiding (aka `new`) on `ToString()`. | The problem is that ToString is a virtual method. In order to override a virtual method in C# you need to specify the override keyword.
You almost certainly do not want the "new" version. . | C#: public new string ToString() VS public override string ToString() | [
"",
"c#",
"oop",
""
] |
So here's my problem:
```
struct A
{
enum A_enum
{
E0,
E1,
E2
};
};
struct B
{
typedef A::A_enum B_enum;
bool test(B_enum val)
{
return (val == E1); // error: "E1" undeclared identifier
}
};
```
I specifically do not want to say `A::E1`. If I try `B_enum::E1` I receive a warning that it is nonstandard. Is there a good way to do something like this? | I reckon that A should be a namespace instead of a struct. | Putting enum in global scope is too exposed, putting them in a class can introduced undesired dependency. For enum not tightly link to a class, this is what I use:
```
#define CLEANENUMS_BEGIN(name) namespace name { typedef enum {
#define CLEANENUMS_END(name) } internal_ ## name ## _e;} typedef name::internal_ ## name ## _e name ## _e;
```
Then you can use, at global scope:
```
CLEANENUMS_BEGIN(myEnum)
horizontal,
vertical,
CLEANENUMS_END(myEnum)
```
That is more or less emulating C# way of handling enums scope. The preprocessor will produce this code:
```
namespace myEnum
{
enum internal_myEnum_e
{
horizontal,
vertical,
}
}
typedef internal_myEnum_e myEnum_e;
```
Then a given enum is referenced as
```
myEnum_e val = myEnum::horizontal;
```
Hopefully there's a better way of doing this but so far, that's the only solution I found. | c++ typedef another class's enum? | [
"",
"c++",
"enums",
"typedef",
""
] |
I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html:
```
import dns.resolver
answers = dns.resolver.query('dnspython.org', 'MX')
for rdata in answers:
print 'Host', rdata.exchange, 'has preference', rdata.preference
```
In the python CLI, a dir(answers) gives me:
```
['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset']
```
Two things are confusing to me (which are related):- Iteration over the answers object. What is rdata in the example?
- None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from. | I haven't looked at `dns.resolver` as of yet - I just added it to the ever-growing list of things to check out. I would guess that `rdata` refers to the resource record type specific data as described in [Section 4.1.3 of RFC1035](https://www.rfc-editor.org/rfc/rfc1035#section-4.1.3). The response of a DNS request contains three data sections in addition to the query and headers:
1. Answers
2. Authoritative Name Server records
3. Additional Resource records
From the looks of it `dns.resolver.query()` is returning the first section. In this case, each resource record in the answer section is going to have different attributes based on the record type. In this case, you asked for `MX` records so the records should have exactly the attributes that you have - `exchange` and `preference`. These are described in [Section 3.3.9 of RFC1035](https://www.rfc-editor.org/rfc/rfc1035#section-3.3.9).
I suspect that `dns.resolver` is overriding `__getattr__` or something similar to perform the magic that you are seeing so you won't see the fields directly in a `dir()`. Chances are that you are safe using the attributes as defined in RFC1035. I will definitely have to check this out tomorrow since I have need of a decent DNS subsystem for Python.
Thanks for mentioning this module and have fun with DNS. It is really pretty interesting stuff if you really dig into how it works. I still think that it is one of the earlier expressions of that ReSTful thing that is all the rage these days ;) | In the example code, `answers` is an iterable object containing zero or more items, which are each assigned to `rdata` in turn. To see the properties of the individual responses, try:
```
dir(answers[0])
``` | dnspython and python objects | [
"",
"python",
"dns",
"dnspython",
""
] |
How do I compare values of one data set from another.
**1st dataset** ["proper records"] is coming from SQL Server with column names
```
[id], [subsNumber]
```
**2nd dataset** ["proper and inproper records"] is coming from progress database, with different columns except 1 which is `subsNumber`
How do I go and make another dataset which has all the `[subsNumber]` from ["proper records"] with matching records from 2nd datset ["proper inproper records"] ?
or
delete all the records in 2nd dataset["proper and inproper records"] which don't match the "subsNumber" column in the 1st dataset
or any other idea
basically How do I get all records from 2nd dataset which has same "subsNumber" as the 1st dataset | The key is using System.Data.DataRelation to join your 2 datatables on a common column (or columns).
Here's some code derived from a post at [KC's See Sharp Blog](http://kseesharp.blogspot.com/2007/12/compare-2-datatables-and-return-3rd.html)
```
public DataTable GetImproperRecords(DataTable ProperRecords, DataTable ImproperRecords) {
DataTable relatedTable = new DataTable("Difference");
try {
using (DataSet dataSet = new DataSet()) {
dataSet.Tables.AddRange(new DataTable[] { ProperRecords.Copy(), ImproperRecords.Copy() });
DataColumn properColumn = new DataColumn();
properColumn = dataSet.Tables[0].Columns[1]; // Assuming subsNumber is at index 1
DataColumn improperColumn = new DataColumn();
improperColumn = dataSet.Tables[1].Columns[0]; // Assuming subsNumber is at index 0
//Create DataRelation
DataRelation relation = new DataRelation(string.Empty, properColumn, improperColumn, false);
dataSet.Relations.Add(relation);
//Create columns for return relatedTable
for (int i = 0; i < ImproperRecords.Columns.Count; i++) {
relatedTable.Columns.Add(ImproperRecords.Columns[i].ColumnName, ImproperRecords.Columns[i].DataType);
}
relatedTable.BeginLoadData();
foreach (DataRow parentrow in dataSet.Tables[1].Rows) {
DataRow[] childrows = parentrow.GetChildRows(relation);
if (childrows != null && childrows.Length > 0)
relatedTable.LoadDataRow(parentrow.ItemArray, true);
}
relatedTable.EndLoadData();
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
return relatedTable;
}
``` | I solved the problem:
1st dataset--> loop throuhg and get the subsNumber
Call function and pass subsNumber and 2nd dataset--> to it
Then start another loop for new dataset
Continue if subsnumber don't match
If subsNumber match work on that data like add columns to sqlserver table etc.
code:
```
foreach (DataRow row in ecommDS.Tables["EcommData"].Rows)
{
//string statCode = ""
string prdCode = ""; //declaring var for getting string format from ecomm
string checking = "";
prdCode = row["PRD-CDE"].ToString();
checking = row["SUBS-NUM"].ToString();
if(checking != subsNum)
{
continue;
}
``` | Compare dataset or a better idea | [
"",
"c#",
"linq",
"ado.net",
".net-2.0",
"dataset",
""
] |
I would like to implement Latent Semantic Analysis (LSA) in PHP in order to find out topics/tags for texts.
Here is what I think I have to do. **Is this correct? How can I code it in PHP? How do I determine which words to chose?**
I don't want to use any external libraries. [I've already an implementation for the Singular Value Decomposition (SVD)](https://stackoverflow.com/questions/960060/singular-value-decomposition-svd-in-php).
1. Extract all words from the given text.
2. Weight the words/phrases, e.g. with [tf–idf](http://en.wikipedia.org/wiki/Tf%E2%80%93idf). If weighting is too complex, just take the number of occurrences.
3. Build up a matrix: The columns are some documents from the database (the more the better?), the rows are all unique words, the values are the numbers of occurrences or the weight.
4. Do the Singular Value Decomposition (SVD).
5. Use the values in the matrix S (SVD) to do the dimension reduction (how?).
I hope you can help me. Thank you very much in advance! | LSA links:
* [Landauer (co-creator) article on LSA](http://www.scholarpedia.org/article/Latent_semantic_analysis)
* [the R-project lsa user guide](http://cran.r-project.org/web/packages/lsa/lsa.pdf)
Here is the complete algorithm. If you have SVD, you are most of the way there. The papers above explain it better than I do.
Assumptions:
* *your SVD function will give the singular values and singular vectors in descending order.* If not, you have to do more acrobatics.
**M**: corpus matrix, w (words) by d (documents) (w rows, d columns). These can be raw counts, or tfidf or whatever. Stopwords may or may not be eliminated, and stemming may happen (Landauer says keep stopwords and don't stem, but yes to tfidf).
```
U,Sigma,V = singular_value_decomposition(M)
U: w x w
Sigma: min(w,d) length vector, or w * d matrix with diagonal filled in the first min(w,d) spots with the singular values
V: d x d matrix
Thus U * Sigma * V = M
# you might have to do some transposes depending on how your SVD code
# returns U and V. verify this so that you don't go crazy :)
```
Then the reductionality.... the actual LSA paper suggests a good approximation for the basis is to keep enough vectors such that their singular values are more than 50% of the total of the singular values.
More succintly... (pseudocode)
```
Let s1 = sum(Sigma).
total = 0
for ii in range(len(Sigma)):
val = Sigma[ii]
total += val
if total > .5 * s1:
return ii
```
This will return the rank of the new basis, which was min(d,w) before, and we'll now approximate with {ii}.
(here, ' -> prime, not transpose)
We create new matrices: U',Sigma', V', with sizes w x ii, ii x ii, and ii x d.
That's the essence of the LSA algorithm.
This resultant matrix U' \* Sigma' \* V' can be used for 'improved' cosine similarity searching, or you can pick the top 3 words for each document in it, for example. Whether this yeilds more than a simple tf-idf is a matter of some debate.
To me, LSA performs poorly in real world data sets because of polysemy, and data sets with too many topics. It's mathematical / probabilistic basis is unsound (it assumes normal-ish (Gaussian) distributions, which don't makes sense for word counts).
Your mileage will definitely vary.
**Tagging using LSA (one method!)**
1. Construct the U' Sigma' V' dimensionally reduced matrices using SVD and a reduction heuristic
2. By hand, look over the U' matrix, and come up with terms that describe each "topic". For example, if the the biggest parts of that vector were "Bronx, Yankees, Manhattan," then "New York City" might be a good term for it. Keep these in a associative array, or list. This step should be reasonable since the number of vectors will be finite.
3. Assuming you have a vector (v1) of words for a document, then v1 \* t(U') will give the strongest 'topics' for that document. Select the 3 highest, then give their "topics" as computed in the previous step. | This answer isn't directly to the posters' question, but to the meta question of how to autotag news items. The OP mentions Named Entity Recognition, but I believe they mean something more along the line of autotagging. If they really mean NER, then this response is hogwash :)
Given these constraints (600 items / day, 100-200 characters / item) with divergent sources, here are some tagging options:
1. By hand. An analyst could easily do 600 of these per day, probably in a couple of hours. Something like Amazon's Mechanical Turk, or making users do it, might also be feasible. Having some number of "hand-tagged", even if it's only 50 or 100, will be a good basis for comparing whatever the autogenerated methods below get you.
2. Dimentionality reductions, using LSA, Topic-Models (Latent Dirichlet Allocation), and the like.... I've had really poor luck with LSA on real-world data sets and I'm unsatisfied with its statistical basis. LDA I find much better, and has an [incredible mailing list](https://lists.cs.princeton.edu/mailman/listinfo/topic-models) that has the best thinking on how to assign topics to texts.
3. Simple heuristics... if you have actual news items, then **exploit the structure of the news item**. Focus on the first sentence, toss out all the common words (stop words) and select the best 3 nouns from the first two sentences. Or heck, take all the nouns in the first sentence, and see where that gets you. If the texts are all in english, then do part of speech analysis on the whole shebang, and see what that gets you. With structured items, like news reports, LSA and other order independent methods (tf-idf) throws out a lot of information.
Good luck!
(if you like this answer, maybe retag the question to fit it) | LSA - Latent Semantic Analysis - How to code it in PHP? | [
"",
"php",
"tagging",
"semantics",
"linguistics",
"lsa",
""
] |
I'm trying to convert an ASP.Net web service to WCF application. The client is on the .Net Compact Framework which does not support WCF so I need to make sure the WCF keeps supporting ASP style webservices. When I add the web service reference in Visual Studio the generated proxy class' methods have extra arguments.
For example if a method is defined as:
```
public void GetEmpInfo(int empNo)
```
That method will appear in the proxy class as:
```
public void GetEmpInfo(int empNo, bool empNoSpecified)
```
What causes this, and how do I get it to stop? | Check out this [blog post](http://blogs.msdn.com/eugeneos/archive/2007/02/05/solving-the-disappearing-data-issue-when-using-add-web-reference-or-wsdl-exe-with-wcf-services.aspx) ...
> Where did these extra boolean
> “specified” members come from and what
> do they do? The answer is the schema
> that the WCF data contract serializer
> generates by default. Because of the
> way its versioning model works, the
> serializer generates all data members
> as optional elements. The older web
> services stack, ASP.NET Web Services
> (“ASMX”), uses a different serializer,
> the XmlSerializer, which maintains
> full schema and XML fidelity. The
> XmlSerializer maps all optional
> elements to two members: one
> represents the data itself, and one
> specifies whether or not the data is
> actually present – this is the
> “xxxSpecified” member. These
> xxxSpecified members must be set to
> true to enable the serialization of
> the corresponding “actual data”
> members. | The .NET Compact Framework does support a subset of WCF. You can review this support on [MSDN](http://msdn.microsoft.com/en-us/library/bb397803.aspx). Take a look, it may support enough for you to remove your legacy Web Services support. | Why are there extra arguments in my wcf web service reference? | [
"",
"c#",
"wcf",
"web-services",
""
] |
In class B below I wanted the `__set__` function in class A to be called whenever you assign a value to `B().a` . Instead, setting a value to `B().a` overwrites `B().a` with the value. Class C assigning to `C().a` works correctly, but I wanted to have a separate instance of A for each user class, i.e. I don't want changing 'a' in one instance of C() to change 'a' in all other instances. I wrote a couple of tests to help illustrate the problem. Can you help me define a class that will pass both test1 and test2?
```
class A(object):
def __set__(self, instance, value):
print "__set__ called: ", value
class B(object):
def __init__(self):
self.a = A()
class C(object):
a = A()
def test1( class_in ):
o = class_in()
o.a = "test"
if isinstance(o.a, A):
print "pass"
else:
print "fail"
def test2( class_in ):
o1, o2 = class_in(), class_in()
if o1.a is o2.a:
print "fail"
else:
print "pass"
``` | Accordingly to the [documentation](http://docs.python.org/reference/datamodel.html#implementing-descriptors):
> *The following methods **only apply** when an instance of the class containing
> the method (a so-called descriptor
> class) **appears in the class dictionary
> of another new-style class**, known as
> the owner class. In the examples
> below, “the attribute” refers to the
> attribute whose name is the key of the
> property in the owner class’ `__dict__`.
> Descriptors can only be implemented as
> new-style classes themselves.*
So you can't have descriptors on instances.
However, since the descriptor gets a ref to the instance being used to access it, just use that as a key to storing state and you can have different behavior depending on the instance. | Here's a class that can pass the original tests, but don't try using it in most situations. it fails the isinstance test on itself!
```
class E(object):
def __new__(cls, state):
class E(object):
a = A(state)
def __init__(self, state):
self.state = state
return E(state)
#>>> isinstance(E(1), E)
#False
``` | Why does declaring a descriptor class in the __init__ function break the descriptor functionality? | [
"",
"python",
"descriptor",
""
] |
I've been playing around with reflection in Java... and I'm a little bit baffled.
I was hoping that the program below would allow me to change the value of a public member variable within a class. However, I receive an IllegalArgumentException. Any ideas?
```
public class ColinTest {
public String msg = "fail";
public ColinTest() { }
public static void main(String args[]) throws Exception {
ColinTest test = new ColinTest();
Class c = test.getClass();
Field[] decfields = c.getDeclaredFields();
decfields[0].set("msg", "success");
System.out.println(ColinTest.msg)
}
}
```
I receive this message -
```
Exception in thread "main" java.lang.IllegalArgumentException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:57)
at java.lang.reflect.Field.set(Field.java:656)
at ColinTest.main(ColinTest.java:44)
```
Thanks. | The first argument of the [`Field.set`](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html#set(java.lang.Object,%20java.lang.Object)) method should be the object which you are reflecting on.
```
decfields[0].set("msg", "success");
```
Should read:
```
decfields[0].set(test, "success");
```
Furthermore, the final `System.out.println` call should refer to the `test` object rather than the class `ColinTest`, as I presume the intention is to output the contents of the `test.msg` field.
**Update**
As pointed out by [toolkit](https://stackoverflow.com/questions/919962/illegalargumentexception-when-setting-public-member/919986#919986) and [Chris](https://stackoverflow.com/questions/919962/illegalargumentexception-when-setting-public-member/919985#919985), the [`Class.getDeclaredField`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaredField(java.lang.String)) method can be used to specify the name of the field in order to retrieve it:
```
Field msgField = test.getClass().getDeclaredField("msg");
// or alternatively:
Field msgField = ColinTest.class.getDeclaredField("msg");
```
Then, the `set` method of the `msgField` can be invoked as:
```
msgField.set(test, "success");
```
This way has its benefit, as already pointed out by toolkit, if there are more fields added to the object, the order of the fields that are returned by `Class.getDeclaredFields` may not necessarily return the field `msg` as the first element of the array. Depending on the order of the returned array to be a certain way may cause problems when changes are made to the class.
Therefore, it would probably be a better idea to use `getDeclaredField` and declare the name of the desired field. | The first arg to set() should be the object whose field you are changing... namely test. | IllegalArgumentException when setting public member | [
"",
"java",
"reflection",
""
] |
With twitter being down today I was thinking about how to best handle calls to an API when it is down. If I am using CURL to call their api how do I cause the script to fail quickly and handle the errors so as not to slow down the application? | Perhaps use a sort of cache of whether or not twitter is up or down. Log invalid responses from the api in a database or server-sided file. Once you get two/three/some other amount of invalid responses in a row, disable all requests to the api for x amount of time.
After x amount of time, attempt a request, if it's still down, disable for x minutes again.
If your server can run CRON jobs consider making a script that checks the api for a valid response every few minutes. If it finds out it's down, disable requests until it's back up. At least in this case the server would be doing the testing and users won't have to be the guinea pigs. | Use [curl\_setopt](http://us.php.net/manual/en/function.curl-setopt.php)
```
curl_setopt($yourCurlHandle, CURLOPT_CONNECTTIMEOUT, '1'); // 1 second
```
If you use curl >= 7.16.2 and PHP >= 5.2.3 there is **CURLOPT\_CONNECTTIMEOUT\_MS** | How to gracefully handle a downed API | [
"",
"php",
"api",
"curl",
""
] |
You can pass a boolean to json\_decode to return an array instead of an object
```
json_decode('{"foo", "bar", "baz"}', true); // array(0 => 'foo', 1 => 'bar', 2 => 'baz')
```
My question is this. When parsing object literals, does this guarantee that the ordering of the items will be preserved? I know JSON object properties aren't ordered, but PHP arrays are. I can't find anywhere in the PHP manual where this is addressed explicitly. It probably pays to err on the side of caution, but I would like to avoid including some kind of "index" sub-property if possible. | Wouldn't it make more sense in this case to use an array when you pass the JSON to PHP. If you don't have any object keys in the JSON (which become associative array keys in PHP), just send it as an array. That way you will be guaranteed they will be in the same order in PHP as in javascript.
```
json_decode('{["foo", "bar", "baz"]}');
json_decode('["foo", "bar", "baz"]'); //I think this would work
```
If you need associative arrays (which is why you are passing the second argument as `true`), you will have to come up with some way to maintain their order when passing. You will pry have to do some post-processing on the resulting array after you decode it to format it how you want it.
```
$json = '{[ {"key" : "val"}, {"key" : "val"} ]}';
json_decode($json, true);
``` | Personally, I've never trusted any system to return an exact order unless that order is specifically defined. If you really need an order, then use a dictionary aka 2dimension array and assigned a place value (0,1,2,3...) to each value in the list.
If you apply this rule to everything, you'll never have to worry about the delivery/storage of that array, be it XML, JSON or a database.
Remember, just because something happens to work a certain way, doesn't mean it does so intentionally. It's akin to thinking rows in a database have an order, when in fact they don't unless you use an ORDER BY clause. It's unsafe to think ID 1 always comes before ID 2 in a SELECT. | Is json_decode in PHP guaranteed to preserve ordering of elements when returning an array? | [
"",
"php",
"json",
"sorting",
""
] |
Suppose I have the following code:
```
void* my_alloc (size_t size)
{
return new char [size];
}
void my_free (void* ptr)
{
delete [] ptr;
}
```
Is this safe? Or must `ptr` be cast to `char*` prior to deletion? | It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)
However, as mentioned in other answers, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."
There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types.
As mentioned in other answers, this is [undefined behavior](https://en.cppreference.com/w/cpp/language/ub) in C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions. | Deleting via a void pointer is undefined by the C++ Standard - see section 5.3.5/3:
> In the first alternative (delete
> object), if the static type of the
> operand is different from its dynamic
> type, the static type shall be a base
> class of the operand’s dynamic type
> and the static type shall have a
> virtual destructor or the behavior is
> undefined. In the second alternative
> (delete array) if the dynamic type of
> the object to be deleted differs from
> its static type, the behavior is
> undefined.
And its footnote:
> This implies that an object cannot be
> deleted using a pointer of type void\*
> because there are no objects of type
> void
. | Is it safe to delete a void pointer? | [
"",
"c++",
"memory-management",
"casting",
"void-pointers",
""
] |
I just created this new class :
```
//------------------------------------------------------------------------------
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
//------------------------------------------------------------------------------
#include <vector>
#include <GL/GLFW.h>
//------------------------------------------------------------------------------
template<class T>
class MultithreadedVector {
public:
MultithreadedVector();
void push_back(T data);
void erase(typename std::vector<T>::iterator it);
std::vector<T> get_container();
private:
std::vector<T> container_;
GLFWmutex th_mutex_;
};
//------------------------------------------------------------------------------
#endif // MULTITHREADEDVECTOR_H_INCLUDED
//------------------------------------------------------------------------------
```
The definition of the class :
```
//------------------------------------------------------------------------------
#include "MultithreadedVector.h"
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
template<class T>
MultithreadedVector<T>::MultithreadedVector() {
th_mutex_ = glfwCreateMutex();
}
template<class T>
void MultithreadedVector<T>::push_back(T data) {
glfwLockMutex(th_mutex_);
container_.push_back(data);
glfwUnlockMutex(th_mutex_);
}
template<class T>
void MultithreadedVector<T>::erase(typename vector<T>::iterator it) {
glfwLockMutex(th_mutex_);
container_.erase(it);
glfwUnlockMutex(th_mutex_);
}
template<class T>
vector<T> MultithreadedVector<T>::get_container() {
return container_;
}
```
Now the problem is that when i try to use it in my code as a static member of another class :
```
// VehicleManager.h
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
#include "MultithreadedVector.h"
#include "Vehicle.h"
class Foo {
public:
// stuffs
private:
static MultithreadedVector<Vehicle> vehicles_;
...
}
#endif
```
Then inside : VehicleManager.cpp
```
#include "VehicleManager.h"
MultithreadedVector<Vehicle> VehicleManager::vehicles_;
void VehicleManager::Method() {
Vehicle vehicle;
VehicleManager::vehicles_.push_back(vehicle);
}
```
But it doesn't compile :(, i get this error msg everytime :
```
C:\***\VehicleManager.cpp|188|undefined reference to `MultithreadedVector<Vehicle>::push_back(Vehicle)'|
```
I really don't understand why, especially that i have defined the static class member at the global scope of VehicleManager.cpp.
PS: I'm using Code::Blocks.
Thanks ! | That's what will happen when blindly moving a class template implementation to a cpp file.
To make that work, you must know exactly for what types of T you will instantiate the class template and specify them in the cpp file.
In this case, put this in the cpp file:
```
template class MultithreadedVector<Vehicle>;
```
Note that the cpp file must know about `Vehicle` then. | Most C++ compilers to not allow you to separate template declarations and template definitiions. You need to put the complete definition of your template classes in a single .h file, not split them into .h and .cpp files. | C++ - Undefined reference to a class recently created ! | [
"",
"c++",
"codeblocks",
"undefined-reference",
""
] |
In a simple Guess-The-Number game I'm making, the user inputs a couple of numbers and hits a button. A second panel becomes enabled and the original one is disabled. The user now enters a number and hits another button, multiple times. Since the two panels will never be enabled at the same time, I'd like for both buttons to be "default", i.e., they will be pushed if Enter is pressed. Is this possible? Apparently, I can only set one of these per window. | A window in Windows by definition has only one default button. This is a functionality intended for dialog windows where you would never disable the default button.
What you can do instead is to switch the default button when you disable one panel.
Another option would be to throw out default buttons altogether and use KeyPreview on the form and handle the enter key yourself, sending it to the appropriate button that is currently active. | Nope, no way to accomplish that that I know of. You'll have to switch the default button when one button is pressed to the next button. | Windows Forms: Multiple default buttons? | [
"",
"c#",
"winforms",
"button",
"default",
""
] |
I'm trying to only return a few columns from a linq to sql query but if I do, it throws the exception:
**Explicit construction of entity type 'InVision.Data.Employee' in query is not allowed**
Here's the code:
```
return db.Employees.Select(e => new Employee()
{ EmployeeID = e.EmployeeID, FirstName = e.FirstName,
LastName = e.LastName }).ToList();
```
If I return everything then it will throw exceptions about circular references because it needs to be serialized to be used in javascript, so I really need to limit the columns... Thanks for any tips you can give me to solve this. | Basically, if you just want the columns, select those. If you want the employee entity, select it. There's not much of a middle ground here. I recommend against creating a new class just for this. Yuck!
Do this:
```
return db.Employees
.Select(e => new { e.EmployeeID, e.FirstName, e.LastName })
.ToList();
``` | Because I've had to fight with Linq2Sql and Serialization before I'd recommend using a View object to handle this scenario rather than a Linq2Sql Entity. Its a much easier solution:
```
return db.Employees
.Select( e => new EmployeeView()
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName
}).ToList();
```
The other alternative is to drag a new copy of your Employee table into the DBML designer, name it something different like SimpleEmployee, delete all the relationships and remove all the columns you don't need. | How to specify which columns can be returned from linq to sql query | [
"",
"sql",
"linq",
"explicit",
"construction",
""
] |
I can show my data in a `JTable` without a problem, but when I want to filter while my app is running, the `JTable` is not showing me data changes. I searched for it and found a class named TableModel but I can't write my AbstractTableModel. Can anyone show me how I can do this?
Personelz.Java
```
package deneme.persistence;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author İbrahim AKGÜN
*/
@Entity
@Table(name = "PERSONELZ", catalog = "tksDB", schema = "dbo")
@NamedQueries({@NamedQuery(name = "Personelz.findAll", query = "SELECT p FROM Personelz p"), @NamedQuery(name = "Personelz.findByPersonelıd", query = "SELECT p FROM Personelz p WHERE p.personelıd = :personelıd"), @NamedQuery(name = "Personelz.findByAd", query = "SELECT p FROM Personelz p WHERE p.ad = :ad"), @NamedQuery(name = "Personelz.findBySoyad", query = "SELECT p FROM Personelz p WHERE p.soyad = :soyad")})
public class Personelz implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Basic(optional = false)
@Column(name = "PERSONELID", nullable = false )
private Integer personelıd;
@Column(name = "AD", length = 50)
private String ad;
@Column(name = "SOYAD", length = 50)
private String soyad;
@Column(name = "YAS")
private Integer yas;
public Personelz() {
}
public Personelz(Integer personelıd) {
this.personelıd = personelıd;
}
public Integer getPersonelıd() {
return personelıd;
}
public void setPersonelıd(Integer personelıd) {
this.personelıd = personelıd;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
String oldAd = this.ad;
this.ad = ad;
changeSupport.firePropertyChange("ad", oldAd, ad);
}
public String getSoyad() {
return soyad;
}
public void setSoyad(String soyad) {
String oldSoyad = this.soyad;
this.soyad = soyad;
changeSupport.firePropertyChange("soyad", oldSoyad, soyad);
}
public Integer getYas() {
return yas;
}
public void setYas(Integer yas){
this.yas = yas;
}
```
TABLEMODEL
```
public class TableModel extends AbstractTableModel {
String[] headers;
List<Personelz> personel;
int row;
int column;
Object[][] per;
/** Creates a new instance of TableModel */
@SuppressWarnings("empty-statement")
public TableModel(List<Personelz> p) {
this.personel = p;
column=2;
row=this.personel.size();
headers=new String[column];
headers[0]="AD";
headers[1]="SOYAD";
per={p.toArray(),p.toArray()};
}
public int getColumnCount()
{
return column;
}
public int getRowCount()
{
return row;
}
public Object getValueAt(int rowIndex, int kolonindex)
{
return per[rowIndex][kolonindex];
}
public String getColumnName(int i)
{
return headers[i];
}
``` | I suggest reading this [How to Use Tables](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#fire) (from the Java Tutorials Using Swing Components)
Basically the TableModel has to notify the Table of changed data by firing the appropriate Events. See [here](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#fire) | There is a very good library called GlazedLists that makes it a lot simpler to work with lists and tables, including column sorting and row filtering.
Its definitely worth taking a look.
<http://publicobject.com/glazedlists/>
HTH | JTable TableModel problem in Java | [
"",
"java",
"swing",
"jtable",
""
] |
I have written a program that is sort of an unofficial, standalone plugin for an application. It allows customers to get a service that is a lower priced alternative then the vendor-owned one. My program is not illegal, against any kind of TOS, and is certainly not a virus, adware, or anything like that. That being said, the vendor of course is not happy about me taking his competition, and is trying to block my application from running.
He has already tried some tactics to stop people from running my app alongside his. He makes it so if it is detected, his app throws a fake error.
First, he checked to see if my program was running by looking for an open window with the right title. I countered this by randomizing the program title at startup.
Next, he looked for the running process name. I countered this by making the app copy itself when it is started as [random string].exe and then running that.
Anyways, my question is this: what else can he do to detect if my program running? I know that you can read window text (ie status bar, labels). I'm prepared to counter this by replacing the labels with images (ugh, any other way?).
But what else is there? Can you detect what .dlls a program has loaded? If so, could this be solved by randomizing the dll names before loading them?
I know that it's possible to get a program's signature in memory and track it that way (like a virus scanner), but the chances of him doing that probably aren't good because that sounds pretty advanced.
Even though this is kinda crappy of him to be doing, its kind of fun. It's like a nerdy fist fight.
**EDIT:**
When I said it's a plugin, that is just the (incorrect) term I used. It's a standalone EXE. The "API" between my program and the other is mine is simply entering data into the controls (like textboxes, etc). | I feel a little dirty answering this but it's late and I'm waiting for a drive copy to finish so....
He could use a checksum to identify your executable/dll. This gets around the renaming tricks.
You can get around this by randomly modifying bits in the program on start (e.g., change a resource, play with the embedded version, etc...).
If I were him I'd also start looking for patterns of network traffic; e.g., if you're directing customers to competitors you're looking that information up from somewhere so kill the process and/or unload the library if a plugin accesses a site that's on the blacklist.
If you take the cat and mouse game far enough (e.g., shell hooks to re-create your executable/library if it gets deleted) you'll probably get flagged as a virus by antivirus software. | Not very sporting of your competitor.
Deploy your project as uncompiled encrypted source code. Write a decryption and deployment program that can randomize, renames classes, re-arranges code to avoid any particular signature detection.
Then compile the code on the client machine using CSharpCodeProvider to compile your code. You can generate random assemblies, with totally random function signatures (I suggest using a large dictionary of real, common, words instead of being totally random. You can concatenate them together for more fun. e.g. Live, Virtual, Space, Office, Network, Utility. Space.Live.Network.dll, Utility.Virtual.Live.dll ).
Every version of your program on every client will be different. Make sure to cloak your deployment program. Maybe it should delete itself after it has installed your customized version. | How can a program be detected as running? | [
"",
"c#",
"detection",
""
] |
Behold the code:
```
using (var client = new WebClient())
{
try
{
var bytesReceived = client.UploadData("http://localhost", bytesToPost);
var response = client.Encoding.GetString(bytesReceived);
}
catch (Exception ex)
{
}
}
```
I am getting this HTTP 500 internal server error when the UploadData method is called. But I can't see the error description anywhere in the "ex" object while debugging. How do I rewrite this code so I can read the error description? | Web servers often return an error page with more details (either HTML or plain text depending on the server). You can grab this by catching `WebException` and reading the response stream from its `Response` property. | I found useful information for debugging this way:
```
catch (WebException ex)
{
HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
String details = "NONE";
String statusCode = "NONE";
if (httpWebResponse != null)
{
details = httpWebResponse.StatusDescription;
statusCode = httpWebResponse.StatusCode.ToString();
}
Response.Clear();
Response.Write(ex.Message);
Response.Write("<BR />");
Response.Write(ex.Status);
Response.Write("<BR />");
Response.Write(statusCode);
Response.Write("<BR />");
Response.Write(details);
Response.Write("<BR />");
Response.Write(ex);
Response.Write("<BR />");
}
``` | How to read an ASP.NET internal server error description with .NET? | [
"",
"c#",
".net",
"asp.net",
"iis",
"webclient",
""
] |
I was wondering if Javascript date/time functions will always return [correct, universal dates/times](http://www.google.com/search?hl=en&rlz=1C1GGLS_enUS291US305&q=current+time&aq=f&oq=&aqi=g10)
or whether, Javascript being a client-side language, they are dependent on what the client machine has its date set to.
If it is dependent on the client machine, what is the best way to get the correct universal time? | As thomasrutter has said javascript date functions are reliant on the client's machine. However if you want to get an authoritative date you could make and ajax request to your server that just returns the date string. You can then convert the date string into a date object with the following
```
var ds = ... // Some ajax call
var d = new Date(ds);
``` | Javascript only knows as much about the correct time as the environment it is currently running within, and Javascript is **[client-side](http://en.wikipedia.org/wiki/Client-side_scripting)**.
So, Javascript is at the mercy of the user having the correct time, AND timezone, settings on the PC on which they are browsing.
If the user has the incorrect time zone, but correct time, then functions depending on time zones like getUTCDate() will be incorrect.
If the user has the incorrect time, then all time-related functions in Javascript will be incorrect.
One could make the argument, however, that if the user wanted correct times on their PC they would have set the correct time. The counter to that is that the user may not know how to do that.
Edit Jun 2020: It is common now for operating systems to update the computer's system time automatically from a time server, significantly reducing the chances of incorrect time on the client. There is still a possibility of an incorrect time *zone*, but this too is often geo-detected somehow by systems during installation and/or is tied to the user's supplied country of residence in their relevant online account. | Are Javascript date/time functions dependent on the client machine? | [
"",
"javascript",
"jquery",
"datetime",
""
] |
What is the best way to tune a server application written in Java that uses a native C++ library?
The environment is a 32-bit Windows machine with 4GB of RAM. The JDK is Sun 1.5.0\_12.
The Java process is given 1024MB of memory (-Xmx) at startup but I often see OutOfMemoryErrors due to lack of heap space. If the memory is increased to 1200MB, the OutOfMemoryErrors occur due to lack of swap space. How is the memory shared between the JVM and the native process?
Does the Windows /3GB switch have any effect with native processes and Sun JVM? | I had lots of trouble with that setting (Java on 32-bit systems - msw and others) and they were all solved by reserving just \*under 1GB of RAM to the JVM.
Otherwise, as stated, the actual occupied memory in the system for that process would be over 2GB; at that point I was having 'silent deaths' of the process - no errors, no warnings, just the process terminating very quietly.
I got more stability and performance running several JVM (each with under 1GB RAM) on the same system. | I found some info on [JNI memory management here](https://stackoverflow.com/questions/214699/jni-memory-management-using-the-invocation-api), and here's the JVM JNI [section on memory management](http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp16785).
Well having a 3GB user space over a 2GB user space should help, but if your having problems running out of swap space at 2GB, I think 3GB is just going to make it worse. How big is your pagefile? Is it maxed out?
You can get a better idea on you heap allocation by hooking up jconsole to your jvm. | Java memory usage with native processes | [
"",
"java",
"windows",
"memory-management",
""
] |
I am curious how delete[] figures out the size of the allocated memory. When I do something like:
```
int* table = new int[5];
delete[] table;
```
I understand that the memory of the table is freed. But what would happen if I reassigned the pointer to some different table.
```
int* table = new [5];
int* table2 = new [9];
table = table2;
delete[] table;
```
Will I free a table of the size 5 or 9? I am interested in how new[] and delete[] share information about their size. Or maybe I am missing something essential here. | It would delete an array of size 9.
It deletes the array pointed to by the pointer.
It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this:
```
int* table = new int[5];
```
it actually allocates an array of 6 integers, and stores the array size in the first element. Then it returns a pointer to the second element. So to find the size, delete[] just has to read table[-1], basically.
That's one common way to do it, but the language standard doesn't specify that it *must* be done in this way. Just that it has to *work*.
Another approach might be to use the address of the array as a key into some global hash table. Any method is valid, as long as it produces the correct results. | [Section 16.14](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.14) of the C++ FAQ lite answers this:
> There are two popular techniques that
> do this. Both these techniques are in
> use by commercial-grade compilers,
> both have tradeoffs, and neither is
> perfect. These techniques are:
>
> ```
> * Over-allocate the array and put n just to the left
> of the first Fred object.
> * Use an associative array with p as the key and n as the value.
> ``` | How does delete[] know the size of an array? | [
"",
"c++",
""
] |
I want to write a GUI seating application that allows users to draw and annotate simple "maps" of seating areas.
The end result would probably look something a little like Visio, but specifically for manipulating my "seating" data model rather than producing files.
In Java-land, there's the Graphical Editing Framework (GEF) -- is there anything like this in the .NET space? Should I just use System.Drawing.Drawing2D primitives and handle it all myself? | Here is product from [Nevron](http://www.nevron.com/Products.DiagramFor.NET.Overview.aspx). It is paid but doing it all yourself will take lot of time and effort.
[Open Diagram](https://github.com/prepare/opendiagram) and [EasyDiagram.net](http://easydiagram.codeplex.com/) are available at [Codeplex](http://www.codeplex.com). Be sure to download and look into their code. | There is [Netron Library](http://www.orbifold.net/default/?page_id=1272) for diagramming. It is open source and uses GDI+. | How do I build a diagramming application in .NET? | [
"",
"c#",
".net",
"user-interface",
"drawing",
"diagram",
""
] |
I have an XSD and I have to generate an XML document to send to the customers of the company I work with. The documents I send will be validated against this XSD schema.
What is the best way to create a XML document conforming to a XSD Schema? I mean, I'm searching for best practices and the like. I'm new to this and while "Googling" around here and there, I found people using XmlTextWriter, DataSet.WriteXml, and others.
1. DataSet.WriteXml seems to not work well for me. This is what I did:
```
var ds = new DataSet();
ds.ReadXmlSchema(schemaFile);
ds.Tables["TableName"].Rows.Add("", "", 78, true, DateTime.Now);
...
ds.WriteXml("C:\\xml.xml");
```
I found it generates a node with NewDataSet, and the nodes are not in the proper order.
2. XmlTextWriter, I find it a bit long to do... but I will if there is no other choice.
What do you think is the best way to do this? Are there other approaches to do it?
I would put the schema here if it wasn't so long, and if it were relevant to the question. | The mainstream practice in .NET is to use [XML Serialization](http://www.bing.com/search?q="XML+Serialization"++site:microsoft.com).
In your case, I would do this:
* run the xsd.exe too on .XSD to generate source code for classes (xsd /c)
* build your app that utilizes those generated classes. Keep in mind you can extend those classes via the "partial classes" technique
* in code, instantiate an XmlSerializer, and Serialize the class instances.
Example:
Given this schema:
```
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Foo" nillable="true" type="Foo" />
<xs:complexType name="Foo">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Bar" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="Baz" type="UntypedArray" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="UntypedArray">
<xs:choice minOccurs="1" maxOccurs="unbounded">
<xs:element name="Type1" type="Type1" minOccurs="1" maxOccurs="1"/>
<xs:any namespace="##other" processContents="lax" minOccurs="1" maxOccurs="1"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="Type1" mixed="true">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Child" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
```
xsd.exe generates this source code:
```
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)]
public partial class Foo {
private string barField;
private object[] bazField;
/// <remarks/>
public string Bar {
get {
return this.barField;
}
set {
this.barField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("", typeof(System.Xml.XmlElement), IsNullable=false)]
[System.Xml.Serialization.XmlArrayItemAttribute(typeof(Type1), IsNullable=false)]
public object[] Baz {
get {
return this.bazField;
}
set {
this.bazField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class Type1 {
private string childField;
private string[] textField;
/// <remarks/>
public string Child {
get {
return this.childField;
}
set {
this.childField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string[] Text {
get {
return this.textField;
}
set {
this.textField = value;
}
}
}
```
In your app you can instantiate a Foo and then serialize, like this:
```
Foo foo = new Foo();
// ...populate foo here...
var builder = new System.Text.StringBuilder();
XmlSerializer s = new XmlSerializer(typeof(Foo));
using ( var writer = System.Xml.XmlWriter.Create(builder))
{
s.Serialize(writer, foo, ns);
}
string rawXml = builder.ToString();
```
This example serializes into a string. Of course you can serialize to other XmlWriters, you can write out to a file, to any arbitrary stream, and so on.
Normally I tweak the serialization to omit the XML declaration, omit the default xml namespaces, and so on. Like this:
```
Foo foo = new Foo();
// ...populate foo here...
var builder = new System.Text.StringBuilder();
var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };
var ns = new XmlSerializerNamespaces();
ns.Add("","");
XmlSerializer s = new XmlSerializer(typeof(Foo));
using ( var writer = System.Xml.XmlWriter.Create(builder, settings))
{
s.Serialize(writer, foo, ns);
}
string rawXml = builder.ToString();
```
You can also do the reverse - map from an XML document to an in-memory object graph - using the XmlSerializer. Use the Deserialize method. | A post I wrote a while ago may be of interest to you. I had to work with BizTalk and found that generating my classes from an XSD and then serializing that class over the wire (wa-la XML) worked quite well!
<http://blog.andrewsiemer.com/archive/2008/04/30/accepting-xmldocuments-from-biztalk-de-serializing-them-to-xsd-generated-serializable.aspx>
This allows you to work with the data as a class and all the perks that go along with that. And it totally allows you to bypass the XML writers! | What is the best way to create an XML document conforming to an XSD Schema? | [
"",
"c#",
"xml",
"xml-serialization",
"xsd",
""
] |
I have a sub folder that has an aspx page and a web.config file that overrides a connection string in the web.config in the root directory. The problem is if the aspx page contains any user controls the user controls still get the connection string from the web.config in the root directory. Is there anyway to force them to use the web.config that the parent aspx page uses? | I suppose your user controls are at the root directory or in a directory that doesn't have a web.config, so they use the root web.config. Cause of the problem is this.
For solution, I think in your page you can set connection string to its user controls by a property. Or you can let your user controls to access connection string over page with a method. | I'm guessing that your user controls some where in the implementation of the user control reads directly from the web.config. That however binds information to the user control that does really have to do with the user control. (information being how to get the connection string, not the connection string it self). That binding violates the single resposibility principle and is (indirectly) what's causing your problem. Instead of reading the connection inside the user control. Expose the connection string as a property and have the page set it when instantiating the control.
To take it a step further into well behaved design. your user control should probably not even know of the connection string but should instead have a worker class or even better you might want to rewrite to have a control for display purposes, a worker for retriving data and a mechanism for binding the retrieved data to you control. | Web.config override doesn't affect user controls | [
"",
"c#",
"asp.net",
"web-config",
""
] |
I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.
My plan was to have a text editor in the character builder that let you write code similar to:
```
if key == K_a:
## Move left
pass
elif key == K_d:
## Move right
pass
```
I will retrieve the contents of the text editor as a string, and I want the code to be run in a method in this method of Character:
```
def keydown(self, key):
## Run code from text editor
```
What's the best way to do that? | You can use the [`eval(string)`](http://docs.python.org/library/functions.html#eval) method to do this.
## Definition
`eval(code, globals=None, locals=None)`
The code is just standard Python code - this means that it still needs to be properly indented.
The globals can have a custom `__builtins__` defined, which could be useful for security purposes.
## Example
```
eval("print('Hello')")
```
Would print `hello` to the console. You can also specify local and global variables for the code to use:
```
eval("print('Hello, %s'%name)", {}, {'name':'person-b'})
```
## Security Concerns
Be careful, though. Any user input will be executed. Consider:
```
eval("import os;os.system('sudo rm -rf /')")
```
There are a number of ways around that. The easiest is to do something like:
```
eval("import os;...", {'os':None})
```
Which will throw an exception, rather than erasing your hard drive. While your program is desktop, this could be a problem if people redistributed scripts, which I imagine is intended.
## Strange Example
Here's an example of using `eval` rather strangely:
```
def hello() : print('Hello')
def world() : print('world')
CURRENT_MOOD = 'happy'
eval(get_code(), {'contrivedExample':__main__}, {'hi':hello}.update(locals()))
```
What this does on the eval line is:
1. Gives the current module another name (it becomes `contrivedExample` to the script). The consumer can call `contrivedExample.hello()` now.)
2. It defines `hi` as pointing to `hello`
3. It combined that dictionary with the list of current globals in the executing module.
## FAIL
It turns out (thanks commenters!) that you actually need to use the `exec` statement. Big oops. The revised examples are as follows:
---
## `exec` Definition
(This looks familiar!)
Exec is a statement:
`exec "code" [in scope]`
Where scope is a dictionary of both local and global variables. If this is not specified, it executes in the current scope.
The code is just standard Python code - this means that it still needs to be properly indented.
## `exec` Example
```
exec "print('hello')"
```
Would print `hello` to the console. You can also specify local and global variables for the code to use:
```
eval "print('hello, '+name)" in {'name':'person-b'}
```
## `exec` Security Concerns
Be careful, though. Any user input will be executed. Consider:
```
exec "import os;os.system('sudo rm -rf /')"
```
---
## Print Statement
As also noted by commenters, `print` is a statement in all versions of Python prior to 3.0. In 2.6, the behaviour can be changed by typing `from __future__ import print_statement`. Otherwise, use:
```
print "hello"
```
Instead of :
```
print("hello")
``` | As others have pointed out, you can load the text into a string and use `exec "codestring"`. If contained in a file already, using [execfile](http://docs.python.org/library/functions.html#execfile) will avoid having to load it.
One performance note: You should avoid execing the code multiple times, as parsing and compiling the python source is a slow process. ie. don't have:
```
def keydown(self, key):
exec user_code
```
You can improve this a little by compiling the source into a code object (with `compile()` and exec that, or better, by constructing a function that you keep around, and only build once. Either require the user to write "def my\_handler(args...)", or prepend it yourself, and do something like:
```
user_source = "def user_func(args):\n" + '\n'.join(" "+line for line in user_source.splitlines())
d={}
exec user_source in d
user_func = d['user_func']
```
Then later:
```
if key == K_a:
user_func(args)
``` | Running Python code contained in a string | [
"",
"python",
"pygame",
"exec",
"eval",
""
] |
I have two modules, default and mojo.
After the initial bootstraping code which is the same for both of the modules, I want, for example, to use different layouts for each module (Or use different credentials check etc).
Where do I put this: IF(module=='mojo') do this ELSE do that | hmm i havent tried this
<http://www.nabble.com/Quick-Guide-How-to-use-different-Layouts-for-each-module-to23443422.html#a24002073>
the way i did that now was thru a front controller plugin
something like
```
switch ($request->getModuleName()) {
case "":
// set layout ...
}
``` | If you are using Zend\_Application (in ZF1.8) then you should be able to use the module specific configuration options to provide this functionality with a as explained in the [relevant section in the documentation](http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.modules).
This would require you to set the layout in the config so it looked something like
```
mojo.resources.layout.layout = "mojo"
anothermodule.resources.layout.layout = "anotherlayout"
```
The layout would then be set automatically by the bootstrap.
The other alternative is to use a front controller plug-in that implements the preDispatch() method to set the layout based on the module name. | How to use different bootstraping for different modules in zend framework | [
"",
"php",
"zend-framework",
""
] |
I have the Python modules a.py and b.py in the same directory.
How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.
I've been playing around with `__file__`, sys.path and os.chdir, but it feels messy. And `__file__` is not always available. | Put the directory that contains both in your python path... or vice versa. | Actually, `__file__` is available for an imported module, but only if it was imported from a .py/.pyc file. It won't be available if the module is built in. For example:
```
>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False
``` | python importing relative modules | [
"",
"python",
"python-import",
"relative-path",
"python-module",
""
] |
Is there a way to get all objects with a date less than a month ago in django.
Something like:
```
items = Item.objects.filter(less than a month old).order_by(...)
``` | What is your definition of a "month"? 30 days? 31 days? Past that, this should do it:
```
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)
```
Takes advantange of the [gte](http://docs.djangoproject.com/en/dev/ref/models/querysets/#gte) field lookup. | Do this:
```
from datetime import datetime, timedelta
def is_leap_year(year):
if year % 100 == 0:
return year % 100 == 0
return year % 4 == 0
def get_lapse():
last_month = datetime.today().month
current_year = datetime.today().year
#is last month a month with 30 days?
if last_month in [9, 4, 6, 11]:
lapse = 30
#is last month a month with 31 days?
elif last_month in [1, 3, 5, 7, 8, 10, 12]:
lapse = 31
#is last month February?
else:
if is_leap_year(current_year):
lapse = 29
else:
lapse = 30
return lapse
last_month_filter = datetime.today() - timedelta(days=get_lapse())
items = Item.objects.filter(date_created__gte=last_month_filter)
```
This will cater for all cases I can think of. | Getting all items less than a month old | [
"",
"python",
"django",
"django-views",
""
] |
How do I effectively use the "Scripting Engine" inside Java?
What are all the right use-cases to use the scripting engine?
Is there an open source project using "Scripting Engine"?
One thing comes to mind is "Closure, Functional programming" support is possible, but it is more of technical use than "Application Requirement".
Configurable plugins are OK. But still so many patterns (visitor, decorator) on high level can do the same.
I don't know the requirement well... how effectively it could be used in Java EE patterns... where it could complement with the existing patterns.
Moreover I would like to see more answers with some business usecases. Maybe like finding a complex discount for a product during sale based on membership or location. Finding ranking for a complex algorithm. Especially why not Java in some scenario? (or C# in .NET world) | In Java 6, scripting engine support is built in. For example,
```
// Create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// Create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// Evaluate JavaScript code from String
engine.eval("print('Hello, World')");
```
Why would you use one? Some reasons:
1. you have a library in a scripting language that you want to use in Java (e.g. a Python library that you could run via Jython)
2. You want to provide a configurable programming mechanism for customers, such that they can provide short code snippets. For example, I've done this in the past allowing customers to write filters using JavaScript (e.g. is x < 2 and y > 5 and z > 10 ?).
3. You can implement more complex logic in tools like Ant by scripting directly in the configuration file
4. You can implement solutions in a language more suited to that domain (e.g. using lambdas via Clojure), but maintain your reliance on the JVM.
Implementations include Rhino (a Java implementation of Javascript), Jython (a Java Python) and many more. | Here are some cases where I've used it.
**1) Java wants to call scripting language, example 1.** I have a Java app that accepts user comments via the WMD JavaScript widget. (Same widget that StackOverflow uses, actually.) User enters comments in the Markdown format and a JavaScript library called Showdown converts it to HTML in two places: (1) on the client, to support real-time previews; and (2) on the server, since I want the client to send pure Markdown to the server and store that there so the user can edit the Markdown later (instead of having to somehow reverse the HTML into Markdown). When storing the comment on the server, I do run the conversion there as well, and I store the HTML alongside the Markdown so I don't have to dynamically convert the Markdown when displaying comment lists. To ensure that the HTML on the server matches the HTML on the client, I want to use the exact same Showdown library. So I run Showdown server-side inside the Rhino JavaScript engine.
**2) Java wants to call scripting language, example 2.** I'm working on a deployment automation application that involves stakeholders across different roles, such as developers, sysadmins and release engineers. The overall app (workflow and UI) is a Java app, but at various locations it calls various scripts (e.g. Ruby, bash), such as for pushing packages, verifying configuration, installing packages, smoke testing, etc. This is partly because script is better/more economical for expressing directory creation, copying, moving, wgetting, etc., and partly because the people who own that particular piece of the pie know how to work with scripting languages but not Java. So we invoke scripts here using Java's Scripting API. Admittedly in this case we could just execute the scripts outside of Java but see #3 below.
**3) Scripting language wants to call Java.** In the aforementioned deployment application, we have web-based deployment logs, and we put a lot of effort into making the deployment logs as easy to read and understand as possible, because a large developer/SQA/release engineer population consumes the logs, and not everybody understands all the details of what exactly goes on with a deployment. Pretty-printing and color-coding are part of the approach. We implemented a pretty-printing deployment log API in Java but we want to be able to have the scripts call that. So for example when the Ruby push script runs, we want it to log its progress to the pretty-printer. Running Ruby inside JRuby allows the Ruby script to see the Java pretty-printer API. | Where is the Java scripting engine used? | [
"",
"java",
"scripting",
""
] |
I have a stupid java logging problem: I'm loading the logging configuration from my app configuration file - but it just doesn't log anything after reading the file (which looks pretty much like the examples you will find on the net except for the additional application configuration - removing this also doesn't help). The "initializing..." log line appears just fine, but the "starting app" and any further messages are neither logged to the console, nor is the logfile ever created. What am I missing here?
The Logger code looks like this:
```
...
Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");
Properties preferences = new Properties();
try {
FileInputStream configFile = new FileInputStream("/path/to/app.properties");
preferences.load(configFile);
LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
System.out.println("WARNING: Could not open configuration file");
System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");
...
```
And this is the configuration file:
```
appconfig1 = foo
appconfig2 = bar
# Logging
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
# File Logging
java.util.logging.FileHandler.pattern = %h/myApp.log
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.level = INFO
# Console Logging
java.util.logging.ConsoleHandler.level = ALL
``` | Okay, first intuition is here:
```
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
```
The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....
In the mean time, try:
```
handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL
```
# Update
No, duh, needed more coffee. Nevermind.
While I think more, note that you can use the methods in [Properties](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Properties.html) to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.
# Another update
This line:
```
FileInputStream configFile = new FileInputStream("/path/to/app.properties"));
```
has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are. | you can set your logging configuration file through command line:
> `$ java -Djava.util.logging.config.file=/path/to/app.properties MainClass`
this way seems cleaner and easier to maintain. | How to set up java logging using a properties file? (java.util.logging) | [
"",
"java",
"logging",
""
] |
Got table ABC with one column. A date column "created". So sample values are like;
```
created
2009-06-18 13:56:00
2009-06-18 12:56:00
2009-06-17 14:02:00
2009-06-17 13:12:23
2009-06-16 10:02:10
```
I want to write a query so that the results are:
```
count created
2 2009-06-18
2 2009-06-17
1 2009-06-16
```
Basically count how many entries belong to each date, but ignoring time.
This is in PL-SQL with Oracle.
Any ideas? | `select count(*), to_char('YYYY-MM-DD', created) from ABC group by to_char('YYYY-MM-DD', created)` | The TRUNC function returns the DATE of the DATETIME.
```
select trunc(created),count(*) from ABC group by trunc(created)
``` | group-by/aggregation over date ranges | [
"",
"sql",
"oracle",
""
] |
I have declared a generic event handler
```
public delegate void EventHandler();
```
to which I have added the extension method 'RaiseEvent':
```
public static void RaiseEvent(this EventHandler self) {
if (self != null) self.Invoke();
}
```
When I define the event using the typical syntax
```
public event EventHandler TypicalEvent;
```
then I can call use the extension method without problems:
```
TypicalEvent.RaiseEvent();
```
But when I define the event with explicit add/remove syntax
```
private EventHandler _explicitEvent;
public event EventHandler ExplicitEvent {
add { _explicitEvent += value; }
remove { _explicitEvent -= value; }
}
```
then the extension method does not exist on the event defined with explicit add/remove syntax:
```
ExplicitEvent.RaiseEvent(); //RaiseEvent() does not exist on the event for some reason
```
And when I hover over to event to see the reason it says:
> The event 'ExplicitEvent' can only
> appear on the left hand side of += or
> -=
**Why should an event defined using the typical syntax be different from an event defined using the explicit add/remove syntax and why extension methods do not work on the latter?**
**EDIT: I found I can work around it by using the private event handler directly:**
```
_explicitEvent.RaiseEvent();
```
But I still don't understand why I cannot use the event directly like the event defined using the typical syntax. Maybe someone can enlighten me. | Because you can do this (it's non-real-world sample, but it "works"):
```
private EventHandler _explicitEvent_A;
private EventHandler _explicitEvent_B;
private bool flag;
public event EventHandler ExplicitEvent {
add {
if ( flag = !flag ) { _explicitEvent_A += value; /* or do anything else */ }
else { _explicitEvent_B += value; /* or do anything else */ }
}
remove {
if ( flag = !flag ) { _explicitEvent_A -= value; /* or do anything else */ }
else { _explicitEvent_B -= value; /* or do anything else */ }
}
}
```
How can the compiler know what it should do with "ExplicitEvent.RaiseEvent();"?
Answer: It can't.
The "ExplicitEvent.RaiseEvent();" is only syntax sugar, which can be predicated only if the event is implicitly implemented. | When you create a "field-like" event, like this:
```
public event EventHandler Foo;
```
the compiler generates a field *and* an event. Within the source code of the class which declares the event, any time you refer to `Foo` the compiler understand that you're referring to the *field*. However, the field is private, so any time you refer to `Foo` from *other* classes, it refers to the event (and therefore the add/remove code).
If you declare your own explicit add/remove code, you don't get an auto-generated field. So, you've only got an event, and you can't raise an event directly in C# - you can only invoke a delegate instance. An event isn't a delegate instance, it's just an add/remove pair.
Now, your code contained this:
```
public EventHandler TypicalEvent;
```
This is slightly different still - it wasn't declaring an *event* at all - it was declaring a public *field* of the delegate type `EventHandler`. *Anyone* can invoke that, because the value is just a delegate instance. It's important to understand the difference between a field and an event. You should never write this kind of code, just as I'm sure you don't normally have public fields of other types such as `string` and `int`. Unfortunately it's an easy typo to make, and a relatively hard one to stop. You'd only spot it by noticing that the compiler was allowing you to assign or use the value from another class.
See my [article on events and delegates](http://pobox.com/~skeet/csharp/events.html) for more information. | C#: event with explicity add/remove != typical event? | [
"",
"c#",
".net",
"events",
""
] |
I've looked around a little and haven't found an equivalent question.
Is this bad coding practice? I can read it easily, but is it too cryptic for someone reading the code?
```
bool? testBool = null;
string result;
result = (testBool ?? false ? "Yes" : "No");
```
**Edit:** My apologies to everyone for some horrible code! Here is a working example..
I'm a little overwhelmed by the speed of the replies. I was going to delete this and do it right, but already had 4 replies! | I'd add parens so clarify what's going on -- ie.
```
bool? testbool = null;
string result;
result = (testbool ?? false) ? "Yes" : "No";
```
With that, I'd be fine with it. Without it, I had to study it for a bit to figure out what was going on (if it even compiles -- I don't know the order of operations off the top of my head for ?: vs. ??) | EDIT: The original question used an `int?`. It's now been fixed.
That code won't even compile, so yes, I'd say it's too cryptic.
Typos aside, the fact that you posted it without easily *spotting* that there's a problem (you're trying to use a `bool` on the RHS of the ??, when the LHS is an `int?`) suggests it's not a good idea even when you get it right.
I'd need to see a real-world example, but I think I'd *usually* split this into one statement using the null coalescing operator, and then another using the conditional operator. Another *option* is to use the behaviour of nullable types in relation to operators... but again, that's *reasonably* obscure. (I've just had to remind myself exactly what that behaviour is!)
I like the null coalescing operator in general, but I think combining it with the conditional operator just makes it a little bit to obscure. I think I'd probably accept it in a case where there was a significant benefit to it being a single expression (e.g. for initialization where the alternative is introducing an extra method) but in general I'd prefer to split it into two statements.
EDIT: One alternative in *this* particular case is to just compare against "true" - which looks redundant, but isn't in the case of `bool?`:
```
result = (testBool == true) ? "Yes" : "No";
```
The brackets aren't necessary, of course, but add clarity IMO.
I think this is simpler: the result is only "Yes" if `testBool` is actually true; otherwise it's "No". If you wanted to "default" to Yes, you'd write:
```
result = (testBool == false) ? "No" : "Yes";
``` | Is it bad to coalesce the evaluator in a ternary expression? (C#) | [
"",
"c#",
"ternary-operator",
"null-coalescing-operator",
""
] |
```
import math
t=raw_input()
k=[]
a=0
for i in range(0,int(t)):
s=raw_input()
b=1
c=1
a=int(s)
if a==0:
continue
else:
d=math.atan(float(1)/b) + math.atan(float(1)/c)
v=math.atan(float(1)/a)
print v
print d
print float(v)
print float(d)
while():
if float(v)== float(d):
break
b=b+1
c=c+1
d=math.atan(float(1)/float(b)) + math.atan(float(1)/float(c))
print d
k.append(int(b)+int(c))
for i in range(0,int(t)):
print k[i]
```
as it's very evident `float(v) != float(d)` till `b` becomes 2 and `c` becomes 3. | Your `while` loop tests on an empty tuple, which evaluates to `False`. Thus, the statements within the `while` loop will never execute:
If you want your `while` loop to run until it encounters a `break` statement, do this:
```
while True:
if (some_condition):
break
else:
# Do stuff...
``` | If is very dangerous to make comparsisons like float(a)==float(b) since float variables have no exact representation. Due to rounding errors you may not have identic values.
Even 2\*0.5 may not be equal 1. You may use the following:
```
if abs(float(a)-float(b)) < verySmallValue:
``` | why does this code break out of loop? | [
"",
"python",
"syntax-error",
""
] |
I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back.
For example I have some structure like
```
const BYTE Some_Idx[] = {
4,7,10,15,17,19,24,29,
31,32,35,45,49,51,52,54,
55,58,60,64,65,66,67,69,
70,72,76,77,81,82,83,85,
88,93,94,95,97,99,102,103,
105,106,113,115,122,124,125,126,
129,131,137,139,140,149,151,152,
153,155,158,159,160,163,165,169,
174,175,181,182,183,189,190,193,
197,201,204,206,208,210,211,212,
213,214,215,217,218,219,220,223,
225,228,230,234,236,237,240,241,
242,247,249};
```
Now, I need to read this and apply some operation on each of the member variable and create a new structure with different order, something like:
```
const BYTE Some_Idx_Mod_mul_2[] = {
8,14,20, ...
...
484,494,498};
```
Is there any Perl library already available for this? If not Perl, something else like Python is also OK.
Can somebody please help!!! | Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C is much easier than parsing C, it's trivial to write a script that parses a text file and makes a header for you, and such a script could even be invoked from your build system.
Assuming that you want to keep your data in a C header file, you will need one of two things to solve this problem:
* a quick one-off script to parse exactly (or close to exactly) the input you describe.
* a general, well-written script that can parse arbitrary C and work generally on to lots of different headers.
The first case seems more common than the second to me, but it's hard to tell from your question if this is better solved by a script that needs to parse arbitrary C or a script that needs to parse this specific file. For code that works on your specific case, the following works for me on your input:
```
#!/usr/bin/perl -w
use strict;
open FILE, "<header.h" or die $!;
my @file = <FILE>;
close FILE or die $!;
my $in_block = 0;
my $regex = 'Some_Idx\[\]';
my $byte_line = '';
my @byte_entries;
foreach my $line (@file) {
chomp $line;
if ( $line =~ /$regex.*\{(.*)/ ) {
$in_block = 1;
my @digits = @{ match_digits($1) };
push @digits, @byte_entries;
next;
}
if ( $in_block ) {
my @digits = @{ match_digits($line) };
push @byte_entries, @digits;
}
if ( $line =~ /\}/ ) {
$in_block = 0;
}
}
print "const BYTE Some_Idx_Mod_mul_2[] = {\n";
print join ",", map { $_ * 2 } @byte_entries;
print "};\n";
sub match_digits {
my $text = shift;
my @digits;
while ( $text =~ /(\d+),*/g ) {
push @digits, $1;
}
return \@digits;
}
```
Parsing arbitrary C is a little tricky and not worth it for many applications, but maybe you need to actually do this. One trick is to let GCC do the parsing for you and read in GCC's parse tree using a CPAN module named [GCC::TranslationUnit](http://search.cpan.org/~awin/GCC-TranslationUnit-1.00/TranslationUnit.pm).
Here's the GCC command to compile the code, assuming you have a single file named test.c:
gcc -fdump-translation-unit -c test.c
Here's the Perl code to read in the parse tree:
```
use GCC::TranslationUnit;
# echo '#include <stdio.h>' > stdio.c
# gcc -fdump-translation-unit -c stdio.c
$node = GCC::TranslationUnit::Parser->parsefile('stdio.c.tu')->root;
# list every function/variable name
while($node) {
if($node->isa('GCC::Node::function_decl') or
$node->isa('GCC::Node::var_decl')) {
printf "%s declared in %s\n",
$node->name->identifier, $node->source;
}
} continue {
$node = $node->chain;
}
``` | Sorry if this is a stupid question, but why worry about parsing the file at all? Why not write a C program that #includes the header, processes it as required and then spits out the source for the modified header. I'm sure this would be simpler than the Perl/Python solutions, and it would be much more reliable because the header would be being parsed by the C compilers parser. | How can I parse a C header file with Perl? | [
"",
"python",
"c",
"perl",
"parsing",
"header-files",
""
] |
How would I do something like this :
```
class Test
{
public function test($methodName) {
$this->$methodName;
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
```
Maybe I should just pass a parameter "TYPE" and use a "IF statement" but I'm just curious! :)
And what if the "dynamic function name" has one or more parameters?
UPDATE : Thanks everyone! :)
**UPDATE #2 - Answer :**
```
class Test
{
public function testOut($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->testOut("a");
$testObj->testOut("b");
```
The problem with the class is that there was a method named "Test" (the same as the class name)... I changed it and it worked. | ```
class Test
{
public function test($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a");
$testObj->test("b");
``` | Check out `call_user_func()` - it should do what you want.
[Documentation here](http://nz.php.net/manual/en/function.call-user-func.php) | Calling a changing function name on an object with PHP : how? | [
"",
"php",
""
] |
This is supposed to calculate the histogram of an 8-bit grayscale image. With a 1024x770 test bitmap, CreateTime ends up at around 890ms. How can I make this go (way, way) faster?
EDIT: I should mention that this doesn't actually compute the histogram yet, it only gets the values out of the bitmap. So I really should have asked, what is the fastest way to retrieve all pixel values from an 8-bit grayscale image?
```
public class Histogram {
private static int[,] values;
public Histogram(Bitmap b) {
var sw = Stopwatch.StartNew();
values = new int[b.Width, b.Height];
for (int w = 0; w < b.Width; ++w) {
for (int h = 0; h < b.Height; ++h) {
values[w, h] = b.GetPixel(w, h).R;
}
}
sw.Stop();
CreateTime = (sw.ElapsedTicks /
(double)Stopwatch.Frequency) * 1000;
}
public double CreateTime { get; set; }
}
``` | The basic histogram algorithm is something like:
```
int[] hist = new hist[256];
//at this point dont forget to initialize your vector with 0s.
for(int i = 0; i < height; ++i)
{
for(int j = 0 ; j < widthl ++j)
{
hist[ image[i,j] ]++;
}
}
```
The algorithm sums how many pixels with value 0 you have, how many with value=1 and so on.
The basic idea is to use the pixel value as the index to the position of the histogram where you will count.
I have one version of this algorithm written for C# using unmanaged code (which is fast) I dont know if is faster than your but feel free to take it and test, here is the code:
```
public void Histogram(double[] histogram, Rectangle roi)
{
BitmapData data = Util.SetImageToProcess(image, roi);
if (image.PixelFormat != PixelFormat.Format8bppIndexed)
return;
if (histogram.Length < Util.GrayLevels)
return;
histogram.Initialize();
int width = data.Width;
int height = data.Height;
int offset = data.Stride - width;
unsafe
{
byte* ptr = (byte*)data.Scan0;
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x, ++ptr)
histogram[ptr[0]]++;
ptr += offset;
}
}
image.UnlockBits(data);
}
static public BitmapData SetImageToProcess(Bitmap image, Rectangle roi)
{
if (image != null)
return image.LockBits(
roi,
ImageLockMode.ReadWrite,
image.PixelFormat);
return null;
}
```
I hope I could help you. | You'll want to use the Bitmap.LockBits method to access the pixel data. [This](https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx) is a good reference on the process. Essentially, you're going to need to use `unsafe` code to iterate over the bitmap data. | How can I speed up this histogram class? | [
"",
"c#",
"performance",
"image-processing",
"histogram",
""
] |
Basically I'm just looking for a 'SelectedItemTemplate' in the SL3 ComboBox. Unfortunately, that doesn't exist.
What I want is for the SelectedItem to look like this: Value
And the items in the dropdown box to look like this: Value + extra information
The latter is easily enough done by using the ItemTemplate, but the SelectedItem looks like that too. How can I prevent / fix that? | Are you looking for `.`[`SelectionBoxItemTemplate`](http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox.selectionboxitemtemplate.aspx)? | You can do it by creating your own SelectionBoxItemTemplate attached property and then defining a new style/control template for the ComboBox which uses that template in the content presenter for the selection box area.
Here's a suitable attached property:
```
public class ComboBoxExt
{
public static DataTemplate GetSelectionBoxItemTemplate(DependencyObject obj)
{
return (DataTemplate) obj.GetValue(SelectionBoxItemTemplateProperty);
}
public static void SetSelectionBoxItemTemplate(DependencyObject obj, DataTemplate value)
{
obj.SetValue(SelectionBoxItemTemplateProperty, value);
}
public static readonly DependencyProperty SelectionBoxItemTemplateProperty =
DependencyProperty.RegisterAttached("SelectionBoxItemTemplate", typeof (DataTemplate), typeof (ComboBoxExt),
new PropertyMetadata(null));
}
```
To update the ComboBox control template, look for the element named `ContentPresenter` inside one called `ContentPresenterBorder` (you can find the default style for ComboBox [here](http://msdn.microsoft.com/en-us/library/dd334408%28v=vs.95%29.aspx)). You need to remove the name of the ContentPresenter (otherwise the ComboBox will set values for its properties explicitly through code, ignoring the databindings that you set).
Here's what the ContentPresenter element in the adjusted control template should look like:
```
<ContentPresenter Margin="{TemplateBinding Padding}"
Content="{Binding Path=SelectedItem, RelativeSource={RelativeSource TemplatedParent}}"
ContentTemplate="{Binding (a:ComboBoxExt.SelectionBoxItemTemplate), RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
</ContentPresenter>
```
Finally, to use this, you would do something like:
```
<ComboBox
Style="{StaticResource MyAdjustedComboBoxStyle}"
ItemTemplate="{StaticResource MyDropDownAreaTemplate}"
Behaviors:ComboBoxExt.SelectionBoxItemTemplate="{StaticResource MySelectionAreaTemplate}">
``` | Different UI for the SelectedItem and the ItemTemplate for Silverlight ComboBox | [
"",
"c#",
"xaml",
"silverlight-3.0",
""
] |
I remember having once seen a list of properties that could be set on Swing components to make them look more native on Mac OS X.
This included ways to mark "dirty" documents with the "dot" in the window close button, open dialogs as sheets (not sure about that, but sure would be nice) etc.
I know Apple has let Java down as a "primary" programming language, but as they recently updated Java and even offer Java 6, I wonder if there is a comprehensive and current list - ideally with examples - on what you can do to make Swing apps look better without much effort on the Mac.
---
After receiving some answers, I put this into community wiki mode and started the following list to be expanded if need be:
---
* [Technical Notes: Java - User Experience](http://developer.apple.com/technicalnotes/Java/idxUserExperience-date.html): Overview page on Apple's developer connection reference library (index page).
* [New Control Styles available within J2SE 5.0 on Mac OS X 10.5](http://developer.apple.com/technotes/tn2007/tn2196.html#//apple_ref/doc/uid/DTS10004439): Examples for Button styles etc. specific to Mac OS X 10.5 Leopard.
* [Java Runtime System Properties](http://developer.apple.com/documentation/Java/Reference/Java_PropertiesRef/Articles/JavaSystemProperties.html#//apple_ref/doc/uid/TP40001975): Information on System properties that help you enable the Apple-style menubar at the top of the screen, give rendering hints for text anti-aliasing etc.
* [Mac OS X Integration for Java](http://developer.apple.com/documentation/Java/Conceptual/Java14Development/07-NativePlatformIntegration/NativePlatformIntegration.html): Information on Menubar and Application menu, context menus, keyboard shortcuts and AppleScript
* [PDF "Java 1.3.1 Development for Mac OS X (Legacy)"](http://developer.apple.com/documentation/Java/Conceptual/Java131Development/Java131Development.pdf): 80 pages of information on various topics such as packaging applications. This is somewhat outdated. | The Java Development Guide for Mac OS X has a [Mac OS X Integration for Java](http://developer.apple.com/documentation/Java/Conceptual/Java14Development/07-NativePlatformIntegration/NativePlatformIntegration.html) section that is probably what you're looking for. | The [Quaqua](http://www.randelshofer.ch/quaqua/) site may be interesting as well. From the site:
> "The Quaqua Look and Feel (Quaqua) is a user interface library for Java applications which wish to closely adhere to the Apple Human Interface Guidelines for Mac OS X. ... It runs on top of Apple's Aqua Look and Feel, and provides fixes and enhancements for it."
It has a fairly good user guide with examples as well. | Swing tweaks for Mac OS X | [
"",
"java",
"user-interface",
"swing",
"macos",
""
] |
I have an sql query with inner joins of four tables that takes more than 30 seconds with the current indexes and query structure. I would like to make it as fast as possible; at least faster than 5 seconds.
I first thought about denormalizing, but read [here](https://stackoverflow.com/questions/173726/when-and-why-are-database-joins-expensive/174047#174047) that generally it should be possible to optimize via correct indexes etc. I cannot figure it out in this case. The current query plan contains an index scan on the smallest table and a 'no join predicate' warning on one of the inner joins.
* How can I optimize the speed of the following?
* Which indexes?
* Which query structure?
* Other considerations?
We have the following tables (with number of rows and relevant fields indicated):
```
TableName Rows Fields
------------------- ----- ----------------------------------------------
ProjectType 150 ProjectTypeID, ProjectTypeName
Employee 200 EmployeeID, RefDepartmentID
Project 0.2M ProjectID, RefProjectTypeID
ProjectTransaction 3.5M Hours, RefEmployeeID, RefProjectID, Date, Type
```
The query should sum the hours for a given department, date range, etc. Currently I try:
```
SELECT E.RefDepartmentID, SUM(PTran.Hours)
FROM Employee E
JOIN ProjectTransaction PTran
ON E.EmployeeID = PTran.RefEmployeeID
JOIN Project P
ON PTran.RefProjectID = P.ProjectID
JOIN ProjectType PType
ON P.RefProjectTypeID = PType.ProjectTypeID
WHERE E.RefDepartmentID = @departmentID
AND @from <= PTran.Date AND PTran.Date <= @to
AND PTran.Type = 0
AND PType.ProjectTypeName NOT IN (N'1', N'2', N'3')
GROUP BY E.RefDepartmentID
```
---
Thanks for all the quick answers. (I already had indexes on 'foreign keys' and criteria in `WHERE` clause.) I reordered the query to have the two small tables first, then the medium sized, and the big one last. And voila takes around one second:
```
SELECT E.RefDepartmentID, SUM(PTran.Hours)
FROM Employee E
JOIN ProjectType PType
ON E.RefCustomerID = PType.RefCustomerID
JOIN Project P
ON PType.ProjectTypeID = P.RefProjectTypeID
JOIN ProjectTransaction PTran
ON E.EmployeeID = PTran.RefEmployeeID
AND P.ProjectID = PTran.RefProjectID
WHERE E.RefDepartmentID = @departmentID
AND @from <= PTran.Date AND PTran.Date <= @to
AND PTran.Type = 0
AND PType.ProjectTypeName NOT IN (N'1', N'2', N'3')
GROUP BY E.RefDepartmentID
``` | It not always work, but try to:
1. Reorder tables in joins from the smallest one to the biggest one.
2. Use subquery instead of `ProjectTransaction` table:
JOIN
(SELECT RefEmployeeID, RefProjectID FROM ProjectTransaction WHERE @from <= PTran.Date AND PTran.Date <= @to AND PTran.Type = 0) AS trans | Assuming that `P.ProjectID` and `PType.ProjectTypeID` are `PRIMARY KEY`'s, create this index:
```
CREATE INDEX ix_ptran_emloyee_type_date ON ProjectTransaction(RefEmployeeID, Type, Date)
```
, and get rid of `GROUP BY`:
```
SELECT @departmentID, SUM(PTran.Hours)
FROM Employee E
JOIN ProjectTransaction PTran
ON PTran.RefEmployeeID = E.EmployeeID
JOIN Project P
ON P.ProjectID = PTran.RefProjectID
JOIN ProjectType PType
ON PType.ProjectTypeID = P.RefProjectTypeID
WHERE E.RefDepartmentID = @departmentID
AND PTran.Date BETWEEN @from AND @to
AND PTran.Type = 0
AND PType.ProjectTypeName NOT IN (N'1', N'2', N'3')
``` | What indexes optimize this query with four joins? | [
"",
"sql",
"sql-server",
"join",
"indexing",
""
] |
I have a class which initiates another class, i'm not concerned with having a reference to the object i only need the method and have to pass in new parameters.
```
class A {
__set .....
}
class B extends A {
$anotherA = new A;
$anotherA->myName = 'stackoverflow';
}
```
in short i'd like to have class B extend A, init a new instance of A but i don't want to have to type "new" everytime, i've seen the following syntax:
```
B::A // something like that
```
but not sure if how to use it or if that would do what i'm trying to do? | I would create the instance of A in B's constructor, then you can instantiate B using either its constructor or static `B::create()`, which just acts as a shortcut. You could make the constructor private if you wanted all instantiation go through `create()`.
```
class A {
// __set .....
}
class B extends A {
public function __construct() {
parent::__construct();
$anotherA = new A;
$anotherA->myName = 'stackoverflow';
}
public static function create() {
return new self();
}
}
new B();
B::create();
``` | What you could do is define a static method on the class that returns the new instance. It's basically a 'shortcut', but it does exactly the same in the background.
```
class C {
public static function instance()
{
return new C();
}
public function instanceMethod()
{
echo 'Hello World!';
}
}
```
Now you can call it like:
```
C::instance()->instanceMethod();
``` | class initiation with php | [
"",
"php",
"oop",
""
] |
What is the maximum heap size that you can allocate on 32-bit Windows for a Java process using `-Xmx`?
I'm asking because I want to use the ETOPO1 data in [OpenMap](http://www.openmap.org) and the raw binary float file is about 910 MB. | There's nothing better than an empirical experiment to answer your question.
I've wrote a Java program and run it while specifying the XMX flag (also used XMS=XMX to force the JVM pre-allocate all of the memory).
To further protect against JVM optimizations, I've actively allocate X number of 10MB objects.
I run a number of test on a number of JVMs increasing the XMX value together with increasing the number of MB allocated, on a different 32bit operating systems using both Sun and IBM JVMs, here's a summary of the results:
OS:Windows XP SP2, JVM: Sun 1.6.0\_02, Max heap size: 1470 MB
OS: Windows XP SP2, JVM: IBM 1.5, Max heap size: 1810 MB
OS: Windows Server 2003 SE, JVM: IBM 1.5, Max heap size: 1850 MB
OS: Linux 2.6, JVM: IBM 1.5, Max heap size: 2750 MB
Here's the detailed run attempts together with the allocation class helper source code:
WinXP SP2, SUN JVM:
```
C:>java -version
java version "1.6.0_02"
Java(TM) SE Runtime Environment (build 1.6.0_02-b06)
Java HotSpot(TM) Client VM (build 1.6.0_02-b06, mixed mode)
```
java -Xms1470m -Xmx1470m Class1 142
...
about to create object 141
object 141 created
C:>java -Xms1480m -Xmx1480m Class1 145
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
WinXP SP2, IBM JVM
```
C:>c:\ibm\jdk\bin\java.exe -version
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build pwi32devifx-20070323 (if
ix 117674: SR4 + 116644 + 114941 + 116110 + 114881))
IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-2007
0323 (JIT enabled)
J9VM - 20070322_12058_lHdSMR
JIT - 20070109_1805ifx3_r8
GC - WASIFIX_2007)
JCL - 20070131
```
c:\ibm\jdk\bin\java.exe -Xms1810m -Xmx1810m Class1 178
...
about to create object 177
object 177 created
C:>c:\ibm\jdk\bin\java.exe -Xms1820m -Xmx1820m Class1 179
JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate he
ap. 1820M requested
Could not create the Java virtual machine.
Win2003 SE, IBM JVM
```
C:>"C:\IBM\java" -Xms1850m -Xmx1850m Class1
sleeping for 5 seconds.
Done.
```
C:>"C:\IBM\java" -Xms1880m -Xmx1880m
Class1
JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate he
ap. 1880M requested
Could not create the Java virtual machine.
Linux 2.6, IBM JVM
```
[root@myMachine ~]# /opt/ibm/java2-i386-50/bin/java -version
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build pxi32dev-20060511 (SR2))
IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Linux x86-32 j9vmxi3223-20060504 (JIT enabled)
J9VM - 20060501_06428_lHdSMR
JIT - 20060428_1800_r8
GC - 20060501_AA)
JCL - 20060511a
```
/opt/ibm/java2-i386-50/bin/java -Xms2750m -Xmx2750m Class1 270
[root@myMachine ~]# /opt/ibm/java2-i386-50/bin/java -Xms2800m -Xmx2800m Class1 270
JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate heap. 2800M requested
Could not create the Java virtual machine.
Here's the code:
```
import java.util.StringTokenizer;
public class Class1 {
public Class1() {}
private class BigObject {
byte _myArr[];
public BigObject() {
_myArr = new byte[10000000];
}
}
public static void main(String[] args) {
(new Class1()).perform(Integer.parseInt(args[0]));
}
public void perform(int numOfObjects) {
System.out.println("creating 10 MB arrays.");
BigObject arr[] = new BigObject[numOfObjects];
for (int i=0;i <numOfObjects; i++) {
System.out.println("about to create object "+i);
arr[i] = new BigObject();
System.out.println("object "+i+" created");
}
System.out.println("sleeping for 5 seconds.");
try {
Thread.sleep(5000);
}catch (Exception e) {e.printStackTrace();}
System.out.println("Done.");
}
}
``` | For a large file I suggest you use a memory mapped file. This doesn't use heap space (or very little) so maximum heap size shouldn't be a problem in this case. | Maximum amount of memory per Java process on Windows? | [
"",
"java",
"windows",
""
] |
I know how to make the download occur, when the download happens it appends the html from the web page that causes the download. How do I filter out the HTML? | I understand that you're trying to output some stream for download from PHP page?
If so, then don't output that content from the page that contains HTML, but redirect to separate php page that outputs only the download stream, with headers if necessary. | If I understand you correctly it's a common problem. I solved it by using ob\_start at the beginning of my index.php (start/root/entry file) before ANY output occures and for the download I do the following:
```
ob_end_clean();
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". filesize("thefileinquestion").";");
header("Content-disposition: attachment; filename=thefileinquestion");
$fp = fopen(thefileinquestion, "r");
while(!feof($fp)){
$buffer = fread($fp, 1024);
echo $buffer;
flush();
}
fclose($fp);
die();
```
**Update**
The `ob_start` command buffers any output (eg via echo, printf) and prevents anything being send to the user BEFORE your actual download. The `ob_end_clean` than stops this behavior and allows direct output again. HTH. | forcing a file download with php | [
"",
"php",
"download",
"content-disposition",
""
] |
I have downloaded the xml dump of the Stack Over Flow site. While transferring the dump into a mysql database I keep running into the following error: Got an Exception: Character reference "some character set like " is an invalid XML character.
I used UltraEdit (it is a 800 meg file) to remove some characters from the file, but if I remove an invalid charater set and run the parser I get error identifying more invalid characters. Any suggestions on how to solve this?
Cheers all,
j | Which dump are you using? There were problems from the first version (not just invalid characters, but also `<` appearing where it shouldn't) but they should have been fixed in the [second dump](https://blog.stackoverflow.com/wp-content/uploads/so-export-2009-06.7z.torrent).
For what it's worth, I fixed the invalid characters in the original using two regex replaces. Replace "�[12345678BCEF];" and "" each with "?" - treating them both as regular expressions, of course. | The set of characters permitted in XML is [here](http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char). As you can see, #x10 is not one of them. If these are present in the stackoverflow dump, then it's not XML compliant.
Alternatively, you're reading the XML using the wrong character encoding. | Sax invalid XML character exception | [
"",
"java",
"xml",
"sax",
""
] |
Ok, so everyone has decided (and for good reason) strait SQL is of the devil. This leaves us with many methods of placing a "middle-man" in our code to separate our code from the database. I am now going to spit out all the info I have gathered in the hope someone can set me strait and tell me what I built.
An ORM (Object-relational mapping) is a series of tools (loosely or tightly integrated depends) which maps database rows to objects in the application.
In an AR (Active-Record) is a type of ORM in which a database table or view is wrapped into a class, thus an object instance is tied to a single row in the table.
Data mapping (DM) is a type of ORM that is the process of creating data element mappings between two distinct data models.
All three claim to work like this:
```
$user = new User();
$user->name = 'Fred';
$user->save();
```
Usually with a User class something like this:
```
class User extends Model {
// Specify the database table
protected $table = "users";
// Define your fields
protected $fields = array(
'id' => array('type' => 'int', 'primary' => true),
'name' => array('type' => 'string', 'required' => true),
'email' => array('type' => 'text', 'required' => true)
);
}
```
With this setup you can easily fetch rows without the need to write SQL.
```
// users
$users = $user->fetch(array('id' => 3));
```
Some AR classes actually look more like this:
```
$db->where('id' => 3);
$db->join('posts', 'posts.user_id = users.id');
$results = $db->get('users');
```
Ok, now this is where it gets hairy. Everyone and his brother seems to have a different view on what type of code falls where. While most agree that an AR or DM is a type of ORM - but sometimes the lines that tell AR's from DM's seem to smear.
I wrote a class that uses a single object ($db) in which you make calls to this object and it handles SQL creation for result saving/fetching.
```
//Fetch the users
$results = $db->select('id, name')->where('id > 4')->get('users');
//Set them active
while($user = $results->fetch()) {
$user->active = TRUE;
$user->save();
}
```
So the question is "what is it?", and why don't people agree on these terms? | You might as well **make up the acronyms** ORM, RM DM whatever ... it is all just **state** transferred from one medium to another and wrapped in function/semantics.
**Sun Microsystems** and **Microsoft** do it all the time with Java and C#. Let's take something simple and give it a new name! What a great idea.
If you say ORM .. everyone knows what it is, in its many guises. Your code looks like the Linq stuff though.
No magic, but alot of buzzwords and fuss IMHO. | It's not that straight SQL is the devil - sometimes it's pretty much required to write raw SQL to get a query to perform the way you want it to. To me, ORMs are much more about eliminating manual work than anything else (like avoiding SQL at all costs). I just don't want to have to setup all my code objects with all hand-crafted queries for every project. That's just a ridiculous amount of work and thought. Instead, ORM tools provide a nice and automated way to create data objects that would have required a lot of manual work otherwise. Now I can have automatic individual row objects that I can extend and create custom functions for, without thinking about it. I can retrieve related rows from different tables without having to hand-code that query.
It looks like your User class example is from [phpDataMapper](http://phpdatamapper.com/), and if so, it also has some other built-in niceties like auto table migrations so you don't have to distribute an SQL file for your table structures as well as a few helper functions and other things. All features included intended to save you time - that's the main goal.
The most important distinction between AR and DM is that an ActiveRecord (AR) row knows about it's own data store, and thus has saving/updating functions on each row object - $user->save() - The "record" is "active". With DataMapper (DM), on the other hand, each individual row does NOT know about it's own data store, by definition. The row is more of a dumb value object that can be worked with in your code. The mapper is responsible for translating the changes to that row back to the datastore - $mapper->save($user). That's the most significant difference - you will find most of the core ORM features to be the same in almost any implementation. It's just mostly a matter of how it's put together at the core architectural level. | What is the difference between a ORM, AR, QB, & DM? | [
"",
"php",
"database",
"orm",
"activerecord",
"object",
""
] |
So...
I've been reading about [REST](http://www.infoq.com/articles/rest-introduction) a little bit, and the idea behind it sounds nice, but the question is, can it be easily integrated into the standard flow of a webpage?
For example, a user creates some sort of item, a blog post or what have you, and now he wants to delete it, so he clicks a 'delete' link on the page. Now what? How do we issue a DELETE request to, say, `http://mysite.com/posts/5`? And how do we handle that request? I have no experience with cURL or anything, but from the looks of it, I would have to `curl_init('http://mysite.com/posts/5')` and then work some magic. But where would I even put that script? That would have to be on another page, which would break the whole idea of REST. Then I would just be `GET`ing another page, which would in turn `DELETE` the page I originally intended?
Is this why people rarely use `REST` or is there actually a nice way to do this?
---
Looks like I need to clarify. People are suggesting I include words like "DELETE" and "POST" in the URL. I believe REST dictates that we have a unique URL for each *resource* but *not* for each action on that resource. I assume this also means that we only have *one* and only *one* URL for each resource. i.e. I want to be able to DELETE or VIEW the contents of a particular post from *one* URL (by sending either DELETE, PUT, POST, or GET), not different URLs with additional params | With a restful server, the same url (say /books/1) can respond to many different verbs. Those verbs, GET, POST, PUT, and DELETE, together with the path, indicate *what you want to do to the data on the server*. The response tells you the answer to your request.
REST is about accessing data in a predictable and sensible way.
If you come from a strong PHP background, where every url has to map to a particular file, you're right, it doesn't really make sense. The two most visible RESTful development environments, ASP.NET MVC and Rails, each have special servers (or server logic) which read the verbs and do that special routing for you. That's what lets the "normal flow" of the application go through as you'd expect. For PHP, there are frameworks that help with this, such as [WSO2's WSF](http://wso2.org/projects/wsf/php).
## How REST works with Web Browsers
Take, for instance, your example. We have posts, and we want to delete one.
1. We start by visiting a url like /posts/4. As we would expect, this shows post 4, its attributes, and some actions you could take on it. The request to render this url would look like `GET /posts/4`. The response contains HTML that describes the item.
2. The user clicks the "Delete Item 4" link, part of the HTML. This sends a request like `DELETE /posts/4` to the server. Notice, this has re-used the `/posts/4` url, but the logic must be different.
Of HTML forms and web browsers, many of them will change a link with method="delete" into a method="post" link by default. You will need to use Javascript (something like [this](https://stackoverflow.com/questions/523843/how-do-you-send-a-request-with-the-delete-http-verb/535312#535312)) to change the verb. Ruby on Rails uses a hidden input field (`_method`) to indicate which method is to be used on a form, as an alternative.
3. On the server side, the "delete an item" logic is executed. It knows to execute this because of the verb in the request (`DELETE`), which matches the action being performed. That's a key point of REST, that the HTTP verbs become meaningful.
4. After deleting the item, you could respond with a page like "yep, done," or "no, sorry, you can't do that," but for a browser it makes more sense to put you somewhere else. The item being deleted, responding with a redirect to `GET /posts` makes good sense.
If you look at the server log, it will be very clear what everybody did to the server, but that's not as important as...
## How REST works with Arbitrary Data
Another key point of REST is that it works well with multiple data formats. Suppose you were writing a program that wanted to read and interact with the blog programmatically. You might want all the posts given in XML, rather than having to scrape the HTML for information.
`GET /posts/4.xml` is intuitive: "Server, please give me xml describing post #4." The response will be that xml. A RESTful server makes it obvious how to get the information you want.
When you made the `DELETE /posts/4.xml` request, you're asking, "Server, please delete item #4." A response like, "Okay, sure," is usually sufficient to express what's happened. The program can then decide what else it wants and make another request. | Depending on what framework you use, there are models that determine how actions are handled for each resource.
Basically using another parameter, you want to send the resource what action to perform. That parameter may be sent through AJAX/JS for example.
If you want to do it **without** javascript/ajax (in case it's disabled), then a form POST method would work as well, sending the resource the extra ACTION parameter.
Of course, in both cases, you have to consider security, and make sure that they're not sending the resource an action they shouldn't be. Make sure to do your checking on the backend, and send an appropriate response or error message.
Client side scripting, whether through JS/Ajax or form POST or other methods require the extra security precaution.
Edited after clarification from poster. | The RESTful flow? | [
"",
"php",
"rest",
""
] |
I'm building a multi-threaded client side javascript application, and I would like to have a background thread pull binary data and pass it to the main thread. I know this can be done in other languages via serialization, but how do I accomplish this in javascript?
---
I might turn this application into a standalone XULrunner application down the line for even more efficiency, so I'd rather go the HTML5 "web workers" route versus using Gears. | The [Web Workers](http://www.whatwg.org/specs/web-workers/current-work/) postMessage API takes a JavaScript object. The Mozilla [Using web workers](https://developer.mozilla.org/En/Using_DOM_workers) documentations says:
> You can safely pass objects in and out
> of workers using the postMessage()
> method; objects are automatically
> converted to JSON internally.
So, you can use any JavaScript object that supports or can be converted to your binary data. Depending on other factors, maybe convert to a Base64 string (see [How can you encode to Base64 using Javascript?](https://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript)) or use an array on numbers. | You use postMessage as was otherwise indicated here, however, the object / data must be base64 encoded before being passed using atob() | how do you pass binary messages to/from a javascript web worker? | [
"",
"javascript",
"multithreading",
"serialization",
""
] |
If I have a class like this:
```
public class Name implements Serializable {
private final String firstName;
private final String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
```
Will its calculated serialVersionUID change if I add another method (and no additional fields)?
For example, adding the method:
```
public String getFullName() {
return firstName + " " + lastName;
}
```
Alternatively, is there a nice tool for figuring this out? | Yes, it will change the `serialVersionUID`.
You can use the `serialver` command line tool - at least in Sun's JDK to calculate the `serialVersionUID` for a given compiled class. | Yes, it will change. An easy way is Eclipse: If the class implements Serializable and you do not provide a serialVersionUID field, the IDE displays a warning symbol. You can click on the warning sign and select "Add generated serial version UID". This will calculate a serialVersionUID for you and insert it in your code. | Will adding a method change the java-calculated serialVersionUid on my class? | [
"",
"java",
"serialization",
"serializable",
"serialversionuid",
""
] |
If possible, using only standard PHP functions like substr(), strrpos(), strpos(), etc. | First, find the last position:
```
$last = strrpos($haystack, $needle);
if ($last === false) {
return false;
}
```
From there, find the 2nd last:
```
$next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);
``` | General solution for any number of backwards steps:
```
function strrpos_count($haystack, $needle, $count)
{
if($count <= 0)
return false;
$len = strlen($haystack);
$pos = $len;
for($i = 0; $i < $count && $pos; $i++)
$pos = strrpos($haystack, $needle, $pos - $len - 1);
return $pos;
}
``` | How to find the second-to-last occurrence of a character within a string? | [
"",
"php",
"string",
""
] |
I want to rewrite the contents of a file.
What I have thought of so far is this:
1. Save the file name
2. Delete the existing file
3. Create a new empty file with the same name
4. Write the desired content to the empty file
Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content? | To overwrite file foo.log with FileOutputStream:
```
File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
// false to overwrite.
byte[] myBytes = "New Contents\n".getBytes();
fooStream.write(myBytes);
fooStream.close();
```
or with FileWriter :
```
File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
// false to overwrite.
fooWriter.write("New Contents\n");
fooWriter.close();
``` | I would highly recommend using the Apache Common's FileUtil for this. I have found this package invaluable. It's easy to use and equally important it's easy to read/understand when you go back a while later.
```
//Create some files here
File sourceFile = new File("pathToYourFile");
File fileToCopy = new File("copyPath");
//Sample content
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");
//Now copy from source to copy, the delete source.
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);
```
More information can be found at:
<http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html> | Is this the best way to rewrite the content of a file in Java? | [
"",
"java",
"file-io",
"url-rewriting",
""
] |
I've created a [GWT](http://code.google.com/appengine/docs/) project using Eclipse which was working perfectly (I was able to run it in both Hosted Mode and on Google App Engine) until I tried to import the [Gears API for Google Web Toolkit](http://code.google.com/docreader/#p=gwt-google-apis&s=gwt-google-apis&t=GearsGettingStarted). After adding the following line to my java source file:
```
import com.google.gwt.gears.client.geolocation.Geolocation;
```
I get the following error when I try to compile:
```
19-Jun-2009 3:36:09 AM com.google.apphosting.utils.jetty.JettyLogger warn
WARNING: failed com.google.apphosting.utils.jetty.DevAppEngineWebAppContext@1c7d682{/,C:\Documents and Settings\Geoff Denning\workspace\TaskPath\war}
javax.xml.parsers.FactoryConfigurationError: Provider org.apache.xerces.jaxp.SAXParserFactoryImpl not found
```
I've already added the gwt-gears.jar file to my \war\WEB-INF\lib directory, and I've referenced it in Eclipse as follows:
[](https://i.stack.imgur.com/CkEA7.png)
I've even opened the gwt-gears.jar file and confirmed that org/apache/xerces/jaxp/SAXParserFactoryImpl.class does exist. Can anyone give me any pointers as to why I'm getting the above error? | Apparently this is a bug in jre 1.5. I was able to resolve the problem by switching my default JRE in Eclipse from 1.5.0\_06 to 1.6.0\_03, as shown below:
[](https://i.stack.imgur.com/8YdWE.png)
Thanks to [Jon](https://stackoverflow.com/users/82865/jon) and [Rahul](https://stackoverflow.com/users/24424/rahul) for pointing me in the right direction. | Check that Xerces exists in:
```
$JAVA_HOME/lib/endorsed
```
Sounds like a Java 5 issue. Also check the Java system property for:
```
javax.xml.parsers.SAXParserFactory
```
It should be:
```
org.apache.xerces.jaxp.SAXParserFactoryImpl
```
If not then that's your issue, make sure you set the system property. | org.apache.xerces.jaxp.SAXParserFactoryImpl not found when importing Gears API in GWT | [
"",
"java",
"gwt",
"xerces",
""
] |
I'm using `Prototype` and trying to dynamically access a variable in a loop.
Code speaks better than me:
```
for (var i=0;i<5;i++) {
$('parent' + i).insert(
'<input type="button" value="Cancel" onclick="$('parent' + i).remove()" />',
{position: 'after'}
);
}
```
The problem is that `i is not defined` when I click on any of the `Cancel` buttons.
How do I change the variable scope so that `i` keeps the proper value for each button?
I'm not interested in any work-around. | I think you were putting `i` into the quoted string instead of `parent` so it was at the wrong level of scope (conceptually speaking).
```
for (var i=0;i<5;i++)
{
$('parent' + i).insert(
'<input type="button" value="Cancel" onclick="$(\'parent' + i +
'\').remove()" />', {position: 'after'});
}
``` | You can do it like this -
```
for (var i = 0; i < 5; i++) {
$('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'});
}
```
It will be rendered like this -
```
<input type="button" value="Cancel" onclick="$('parent1').remove()" />
<input type="button" value="Cancel" onclick="$('parent2').remove()" />
<input type="button" value="Cancel" onclick="$('parent3').remove()" />
...
```
and so on. | Variable scope in onclick attribute with JavaScript | [
"",
"javascript",
"variables",
"prototype",
""
] |
I am learning Python because it appeals to me as a mathematician but also has many useful libraries for scientific computing, image processing, web apps, etc etc.
It is frustrating to me that for certain of my interests (eletronic music or installation art) there are very specific programming languages which seem better suited to these purposes, such as Max/MSP, PureData, and ChucK -- all quite fascinating.
My question is, how should one approach these different languages? Should I simply learn Python and manage the others by using plugins and Python interpreters in them? Are there good tools for integrating the languages, or is the proper way simply to learn all of them? | I would say learn them all. While it's true that many languages can do many things, specialised languages are usually more expressive and easier to use for a particular task. Case-in-point is while most languages allow shell interaction and process control very few are as well suited to the task as bash scripts.
Plugins and libraries can bridge the gap between general and specialised languages but in my experience this is not always without drawbacks - be they speed, stability or complexity. It isn't uncommon to have to compile additional libraries or apply patches or use untrusted and poorly supported modules. It also isn't uncommon that the resulting interface is still harder to use than the original language.
I know about 15 languages well and a few of those very well. I do not use my prefered languages when another is more suitable. | This thread is a little old, but I wanted to point out that the majority of the mature audio development environments e.g. supercollider/max-msp/pure data can be controlled via open sound control. You can google up a better description of OSC, but suffice it to say that it allows you to send control data to synths built in these environments similar to how MIDI works, but way more extensive. This does not solve the problem of actually building synths in python per se but it allows you to "drive" these other environments without having to know the ins and outs of the language. | Synthesis of general programming language (Python) with tailored language (PureData/MaxMSP/ChucK) | [
"",
"python",
"chuck",
"puredata",
""
] |
I have a list iterator that goes through a list and removes all the even numbers. I can use the list iterator to print out the numbers fine but I cannot use the list's remove() and pass in the dereferenced iterator.
I noticed that when the remove() statement is in effect, \*itr gets corrupted? Can somebody explain this?
```
#include <iostream>
#include <list>
#define MAX 100
using namespace std;
int main()
{
list<int> listA;
list<int>::iterator itr;
//create list of 0 to 100
for(int i=0; i<=MAX; i++)
listA.push_back(i);
//remove even numbers
for(itr = listA.begin(); itr != listA.end(); ++itr)
{
if ( *itr % 2 == 0 )
{
cout << *itr << endl;
listA.remove(*itr); //comment this line out and it will print properly
}
}
}
``` | There are a few issues with your code above. Firstly, the `remove` will invalidate any iterators that are pointing at the removed elements. You then go on to continue using the iterator. It is difficult to tell which element(s) `remove` would erase in the general case (although not in yours) since it can remove more than one.
Secondly, you are probably using the wrong method. Remove will iterate through all of the items in the list looking for any matching elements - this will be inefficient in your case because there is only one. It looks like you should use the `erase` method, you probably only want to erase the item at the position of the iterator. The good thing about `erase` is it returns an iterator which is at the next valid position. The idiomatic way to use it is something like this:
```
//remove even numbers
for(itr = listA.begin(); itr != listA.end();)
{
if ( *itr % 2 == 0 )
{
cout << *itr << endl;
itr=listA.erase(itr);
}
else
++itr;
}
```
Finally, you could also use `remove_if` to do the same as you are doing:
```
bool even(int i) { return i % 2 == 0; }
listA.remove_if(even);
``` | You can't use an iterator after you delete the element it referred to.
However, list iterators which refer to non-deleted items after a `remove()` should remain valid. | List Iterator Remove() | [
"",
"c++",
"list",
"stl",
""
] |
Is there an efficient way to programatically generate a list of supported devices based on a set of required capabilities using the [WURFL](http://wurfl.com) APIs?
For example I have two versions of an application; one that runs on Nokia Series60 version 2 handsets (Symbian 7/8) and a different version that runs on Nokia Series60 version 3 handsets (Symbian 9). I need to get all such handset from the WURFL to present as on a 'supported handsets' page as well as check UAs of users who attempt to download so I can pass them the correct version of the application.
Conceptually I think I am looking for something like this:
```
return all devices that have capabilities :=
device_os == Symbian OS
&& nokia_series == 60
&& (nokia_edition == 2 || nokia_edition == 3)
```
I am looking to do this in Java. | I suggest using the [new Java WURFL API](http://wurfl.sourceforge.net/njava/) to load and trawl through the capabilities database. It's pretty flexible that way, you should be able to implement your pseudo-code pretty quickly. | All the other answers talked about how to use the Java WURFL API. However, to speed up the search at runtime, I'd recommend storing a hashmap or dictionary in memory mapping the user agent string (or a trimmed down version of the original string) to its corresponding device info. The total amount of data should not be that big - merely on the order of megabytes. Also, the WURFL data is fairly static, so one can preprocess the entire dataset offline to build the hashmap. I usually preprocess and update the hashmap periodically, serialize the object, and load it during runtime. | Generating a list of supported devices by WURFL capabilities | [
"",
"java",
"mobile",
"wurfl",
""
] |
How can I programmatically tell in C# if an *unmanaged* DLL file is x86 or x64? | Refer to [the specifications](http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx). Here's a basic implementation:
```
public static MachineType GetDllMachineType (string dllPath)
{
// See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
// Offset to PE header is always at 0x3C.
// The PE header starts with "PE\0\0" = 0x50 0x45 0x00 0x00,
// followed by a 2-byte machine type field (see the document above for the enum).
//
using (var fs = new FileStream (dllPath, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader (fs))
{
fs.Seek (0x3c, SeekOrigin.Begin);
Int32 peOffset = br.ReadInt32();
fs.Seek (peOffset, SeekOrigin.Begin);
UInt32 peHead = br.ReadUInt32();
if (peHead != 0x00004550) // "PE\0\0", little-endian
throw new Exception ("Can't find PE header");
return (MachineType)br.ReadUInt16();
}
}
```
The `MachineType` enum is defined as:
```
public enum MachineType : ushort
{
IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
IMAGE_FILE_MACHINE_AM33 = 0x1d3,
IMAGE_FILE_MACHINE_AMD64 = 0x8664,
IMAGE_FILE_MACHINE_ARM = 0x1c0,
IMAGE_FILE_MACHINE_EBC = 0xebc,
IMAGE_FILE_MACHINE_I386 = 0x14c,
IMAGE_FILE_MACHINE_IA64 = 0x200,
IMAGE_FILE_MACHINE_M32R = 0x9041,
IMAGE_FILE_MACHINE_MIPS16 = 0x266,
IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
IMAGE_FILE_MACHINE_R4000 = 0x166,
IMAGE_FILE_MACHINE_SH3 = 0x1a2,
IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
IMAGE_FILE_MACHINE_SH4 = 0x1a6,
IMAGE_FILE_MACHINE_SH5 = 0x1a8,
IMAGE_FILE_MACHINE_THUMB = 0x1c2,
IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
IMAGE_FILE_MACHINE_ARM64 = 0xaa64
}
```
I only needed three of these, but I included them all for completeness. Final 64-bit check:
```
// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
switch (GetDllMachineType(dllPath))
{
case MachineType.IMAGE_FILE_MACHINE_AMD64:
case MachineType.IMAGE_FILE_MACHINE_IA64:
return true;
case MachineType.IMAGE_FILE_MACHINE_I386:
return false;
default:
return null;
}
}
``` | Using a Visual Studio command prompt, dumpbin /headers dllname.dll works too. On my machine the beginning of the output stated:
```
FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007
``` | Check if unmanaged DLL is 32-bit or 64-bit? | [
"",
"c#",
"dll",
"64-bit",
"32-bit",
""
] |
I thought the query was quite trivial, but it's raising a FormatException ("Input string was not in a correct format") nonetheless:
```
Submissions.Where(s => (false && s.Status == Convert.ToInt16("")))
```
(of course, in my code, another expression that evaluates to 'false' is located before '&&')
So why is the part after '&&' evaluated, since the first part is always false and the total expression can never evaluate to `true`?
The situation is particularly strange because only the `Convert.ToInt16("")` part seems to raise an exception - other parts of my original query of more or less the same structure, like
```
Submissions.Where(s => (false && s.SubmissionDate <= DateTime.Now))
```
are evaluated correctly. | As the others have pointed out, LINQ to SQL code gets pulled apart into an expression tree before being run as SQL code against the database. Since SQL does not necessarily follow the same short-circuit boolean rules as C#, the right side of your expression code might get parsed so that the SQL can be constructed.
From [MSDN](http://msdn.microsoft.com/en-us/library/bb386909.aspx):
> C# specifies short circuit semantics
> based on lexical order of operands for
> logical operators && and ||. SQL on
> the other hand is targeted for
> set-based queries and therefore
> provides more freedom for the
> optimizer to decide the order of
> execution.
As for why you're getting an exception with this code, `Convert.ToInt16("")` will always throw precisely that exception because there's no way to convert an empty string into an integer. Your other example doesn't attempt an invalid conversion, hence it runs without a problem. | If `Submissions` is an `IQueryable<T>`, then this isn't a regular C# delegate, but is an expression tree. Some code (the LINQ provider) has to pull this tree apart and understand it - so if you have oddities in the expressions, then expect odd output. | Why does 'Submissions.Where(s => (false && s.Status == Convert.ToInt16("")))' raise an FormatException? | [
"",
"c#",
"linq",
""
] |
**I want to make a perfect custom DAL (data abstraction layer) class to use with all my projects.**
I've searched the internet and found some samples for this but I never know which is the best approach.
**Is it to make `[Attributes]`? Or use `<Generics>` or something else?**
So please just give me a head line and I'll go on from there.
Thanks again and forgive my language. | Best approach is:
**Don't do it yourself** unless its for an academic research project or you intend to build a business shipping ORMs.
Try out the dozens of existing ORM solutions first. (Entity framework, subsonic, nhibernate etc etc...). They all have their quirks and limitations mixed in with tons of awesomeness.
ORMs are incredibly hard to get right and a huge undertaking.
Slightly related and on the money: <http://wekeroad.com/2009/06/11/youre-not-your-data-access/> | Just make sure you:
* Always use stored procedures
* Never use stored procedures
* Sometimes use stored procedures
* Use nHibernate
* Use SubSonic
* Use Entity Framework
* Write your own
* Never write you own
* Use POCO
* Use ActiveRecord
* Use IRepository
* Always do what Fowler says
* Never do what Fowler says
* Don't use Linq to SQL, it's dead
* Use Linq to SQL, it's no longer dead
Do all that and you will be fine. | What is the best approach to make DAL? | [
"",
"c#",
".net",
"asp.net",
"data-access-layer",
""
] |
this is a follow up on my question on paypal integration. I'm working ona membership site for racing fans. My membership site has 3 membership levels - free, gold and premium. When a user signs up he/she can gets a free membership on the spot but has the option to upgrade to a gold membership for 4 Dollars a month or a premium membership for 10 Dollars a month.
I've gone through the paypal integration guide a few times though and have a vague understanding of how to get this to work. I think the recurring payments option would be fine enough - however I don't know how do I implement this in my system.
Like when a user decides to go for a paid account i.e. Gold or premium from basic - what should I do on both my code side and on the paypal account side - I'd really appreciate if anyone would outline what I'd have to do here.
Plus when a user decides to upgrade from lets say a Gold to a premium account - there is the issue of computing how much should be charged to upgrade his/her account eg: a user has been billed for 4 dollars and the next day opts to go for a premium account so assuming that the surplus for the rest of the month is 5 dollars and further from that all payments would be recurring 10 dollars monthly - how do I implement this?
And in case a user decides to downgrade from a premium account of 10 dollars a month to a gold account of 4 dollars a month - how do I handle the surplus which would have to be refunded for that month alone and changing the membership?
And like wise if someone wishes to cancel membership and go to having a free account - how do I refund whatever is owed and cancel the subscription.
I'm sorry if it sounds like I'm asking to be spoon fed :( I'm quite new to this and this is for a client and I would really appreciate all the help here and really have to get this working right.
Thanks again everyone - waiting for all your replies. | You need to start reading up on [Instant Payment Notification](https://www.paypal.com/ipn) (IPN). This is basically just a callback from PayPal to your site, when some kind of transaction has occurred.
What you need is a php-script on your site, which you register in your paypal account. PayPal will invoke this script with information and you send information back to PayPal to let them know if the transaction is ok nor not. While doing this you have all sorts of ways to intercept what has happened.
If the customer bought product X, where X in your case can be a "gold membership" you can check against your database (assuming you have some php/mysql or similar setup) if this particular customer already had product Y you should refund blabla. That logic is completely up to you. Since it's a php script you have access to anything that php gives you access too, reading/writing from/to databases, files, mail etc.
There are also various packages that have support for this IPN. I believe ColdFusion is one of them.
Cheers !
Edit:
> Good advice - however considering the
> situation I have I would like to know
> what is the easiest and most hassle
> free method to follow i.e. should I go
> with recurring billing or have the
> customer pay periodically. I'm open to
> all options and better yet any code
> samples that I can use straight on :)
I'd personally go for the method the customer finds the easiest way. Using recurring billing is for love and match making sites, that want to exploit on your deepest feelings as a human being. "When the customer forgets about his account we can bill him an extra period" (sitting in a wheel chair in his evil den, laughing out loud muahahaha and pats his white cat).
Here's a quick [php skeleton](http://www.pdncommunity.com/pdn/board/message?board.id=samplecode&thread.id=14) that you can use as IPN receiver.
Edit2
> Ok so recurring billing isn't such a
> good idea then :-S - I mean with
> recurring billing I don't think we
> would be able to maintain on our
> website a history of when teh customer
> has been billing is it?
Sure you could keep a history of this. You know when the customer first started paying and you could keep track internally whenever the customer should be invoiced/billed again. It's just a periodic check versus the first payment date.
Edit3
> So in this case I would do best to go
> with my older idea of allowing the
> customer to pay in advance for 3,6,12
> months and run a check when the time
> is near to get him/ her to renew. Cool
> - so in that case I won't be using paypals recurring subscription service
> but their Buy Now button thingy or
> sorta :-S are there any free books on
> how to do this? I seem to have a bad
> habit of overcomplicating things.
Yup. Buy now buttons are very nice to use together with IPN. I think you can have different IPN handlers (e.g. different php pages) for different buttons. Free books? As in those old things made out of paper? ;) There are a lot of information on the web. PayPal has tutorials on how to get started. PayPal also has a "sandbox" site, where you can create test buttons that produce fake transactions against your site. You will need to use this.
Edit4
> Thanks a lot man for the great advice
> - figures the simpler I keep it the less issues I'd run into. Would holler
> again on SO should I need more advice.
> I had worked once a while back in
> 2Checkout but that was on code already
> built so I had a vague idea of what
> was going on - this is my first
> project using paypal though - ah well
> never too late to learn :)
One final thingie. Make sure that you from the beginning setup basic logging abilities, so you can dump data to file and see what's going on, what kind of data PayPal is sending to you. This has helped me tremendously. It doesn't have to be anything advanced, just a simple text file will do fine. Otherwise it can be real pain to "debug" these transactions. "FTW is going on now?" :)
Good luck ! | I'm fairly certain there are membership modules/add-ons/extensions/etc for various content management systems and community, err.. management systems that add this very functionality.
If you're basing this on a prefab solution like Wordpress, just google for [Wordpress paid membership](http://www.google.co.uk/search?q=wordpress+paid+membership) and you'll find various plug-ins that do 90% of the work for you.
I should add that considering these are almost always for commercial use, you'll likely have to pay for the best result. | Building Paypal based membership website - total noob - would appreciate help | [
"",
"php",
"paypal",
"membership",
"paypal-subscriptions",
""
] |
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.
This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:
```
def select_rows(to_select):
# For a list
for row in range(0, table.numRows()):
if _table.item(row, 1).text() in to_select:
table.selectRow(row)
# For a single integer
for row in range(0, table.numRows()):
if _table.item(row, 1).text() == to_select:
table.selectRow(row)
``` | Actually I agree with [Andrew Hare's answer](https://stackoverflow.com/a/998949/3357935), just pass a list with a single element.
But if you really must accept a non-list, how about just turning it into a list in that case?
```
def select_rows(to_select):
if type(to_select) is not list: to_select = [ to_select ]
for row in range(0, table.numRows()):
if _table.item(row, 1).text() in to_select:
table.selectRow(row)
```
The performance penalty for doing 'in' on a single-item list isn't likely to be high :-)
But that does point out one other thing you might want to consider doing if your 'to\_select' list may be long: consider casting it to a set so that lookups are more efficient.
```
def select_rows(to_select):
if type(to_select) is list: to_select = set( to_select )
elif type(to_select) is not set: to_select = set( [to_select] )
for row in range(0, table.numRows()):
if _table.item(row, 1).text() in to_select:
table.selectRow(row)
``` | You could redefine your function to take any number of arguments, like this:
```
def select_rows(*arguments):
for row in range(0, table.numRows()):
if _table.item(row, 1).text() in arguments:
table.selectRow(row)
```
Then you can pass a single argument like this:
```
select_rows('abc')
```
multiple arguments like this:
```
select_rows('abc', 'def')
```
And if you already have a list:
```
items = ['abc', 'def']
select_rows(*items)
``` | Handle either a list or single integer as an argument | [
"",
"python",
"list",
"function",
"integer",
""
] |
I am very confused by the following results:
```
PRINT 3.1415926535897931 /180
```
Console result = 0.01745329251994329500
```
DECLARE @whatTheHell float(53)
SET @whatTheHell = 3.1415926535897931/180
PRINT @whatTheHell
```
Console result = 0.0174533
I don't understand because referring to this:
<http://msdn.microsoft.com/en-us/library/ms131092.aspx>
Sql Server Float should be equivalent to c# double.
But when I compute this in c#:
```
double hellYeah = 3.1415926535897931 /180;
```
I get 0.017453292519943295... | I think you're getting confused by the fact that `PRINT` implicitly converts numeric to character with the default setting for the `STR` function -- a length of 10 (see [MSDN](http://msdn.microsoft.com/en-us/library/ms189527(SQL.90).aspx)). Try `PRINT STR(@wth, 20, 16)` and you might be happier. | Divide is not rounding. PRINT is rounding.
```
DECLARE
@var1 float,
@var2 float,
@var3 float
SET @var1 = 3.1415926535897931
SET @var2 = 180
SET @var3 = @var1 / @var2
SELECT @var1/@var2 as Computed, @var3 as FromVariable
PRINT @var1/@var2
PRINT @var3
``` | SQL Server Automatic Rounding? | [
"",
"sql",
"sql-server",
"rounding",
""
] |
I am using Smarty in my projects when I enable caching it doesn't seem to work.
I am using the following structure:
> index.php — display(index.tpl)
>
> index.tpl —- {include
> file=$page\_center}
>
> ?module=product —
> $smarty->assign(”page\_center” ,
> “product.tpl”) ;
In product.php the template product.tpl must loaded in center of index.tpl.
When I enable caching it still shows the default content not product.tpl. When caching is disabled it works fine. What is the problem when caching is enabled? | You will need to use a unique cache ID for each page to make this work correctly:
```
$cacheID = 'some_unique_value_for_this_page';
$smarty->assign('page_center', 'product.tpl');
$smarty->display('index.tpl', $cacheID);
```
Given the example you gave in the question, it could make sense to use the module name from your query string as the basis for the cache ID.
There's more information about in the Smarty manual: <http://www.smarty.net/manual/en/api.display.php> | you need create an dynamic module!
```
function smarty_block_dynamic($param, $content, &$smarty) {
return $content;
}
```
then
```
$smarty = new Smarty
$smarty->register_block('dynamic',
'smarty_block_dynamic',
false /* this block wont be cached */);
```
and your tpl
```
Hello {$name}
this is your las update
{/dyamic}
{include file="some/dynamic/thing.tpl"}
{/dynamic}
``` | Smarty cache not working? | [
"",
"php",
"caching",
"smarty",
""
] |
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:
> ValueError: startupinfo is only supported on Windows platforms
Is there a simpler way than creating a separate Popen command for each OS?
```
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
if os.name == 'posix':
proc = subprocess.Popen(command)
``` | You can reduce one line :)
```
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(command, startupinfo=startupinfo)
``` | Just a note: for **Python 2.7** I have to use `subprocess._subprocess.STARTF_USESHOWWINDOW` instead of `subprocess.STARTF_USESHOWWINDOW`. | Cross-platform subprocess with hidden window | [
"",
"python",
"windows",
"linux",
"cross-platform",
"subprocess",
""
] |
I want to define a class like this
```
class HttpRestAccessor
{
public:
IResource& UpdateResource(string& , IResource& );
};
```
and implementing in cpp file
```
IResource& HttpRestAccessor::UpdateResource(string& resourceUri, IResource& resource)
```
this cpp file refers to Winbase.h which has defined UpdateResource as follows
```
#define UpdateResource UpdateResourceW
```
And hence while compiling i get following error
error C2039: 'UpdateResourceW' : is not a member of 'RestToolkit::HttpRestAccessor'
this problem would be solved if rename function name to something different.
but I would love to keep my function name as UpdateResource.
Thanks In Advance,
Uday | Macro's totally ignore scope.
Basically the pre-precessor will do a find/replace of UpdateResource with UpdateResourceW so you're all out of luck.
renaming the method is your only option | Just undefine it:
```
#undef UpdateResource
```
then redefine later if you actually need it.
EDIT: However, you should reconsider your aversion to renaming the method. As others have said, that's a more elegant solution. | How to define a function with same name which is present in different file | [
"",
"c++",
""
] |
A client has reported repeated instances of Very strange behaviour when executing a stored procedure.
They have code which runs off a cached transposition of a volatile dataset. A stored proc was written to reprocess the dataset on demand if:
1. The dataset had changed since the last reprocessing
2. The datset has been unchanged for 5 minutes
(The second condition stops massive repeated recalculation during times of change.)
This worked fine for a couple of weeks, the SP was taking 1-2 seconds to complete the re-processing, and it only did it when required. Then...
* The SP suddenly "stopped working" (it just kept running and never returned)
* We changed the SP in a subtle way and it worked again
* A few days later it stopped working again
* Someone then said "we've seen this before, just recompile the SP"
* With no change to the code we recompiled the SP, and it worked
* A few days later it stopped working again
This has now repeated many, many times. The SP suddenly "stops working", never returning and the client times out. (We tried running it through management studio and cancelled the query after 15 minutes.)
Yet every time we recompile the SP, it suddenly works again.
I haven't yet tried WITH RECOMPILE on the appropriate EXEC statments, but I don't particularly want to do that any way. It gets called hundred of times an hour and normally does Nothing (It only reprocesses the data a few times a day). If possible I want to avoid the overhead of recompiling what is a relatively complicated SP "just to avoid something which "shouldn't" happen...
* Has anyone experienced this before?
* Does anyone have any suggestions on how to overcome it?
Cheers,
Dems.
**EDIT:**
The pseduo-code would be as follows:
* read "a" from table\_x
* read "b" from table\_x
* If (a < b) return
* BEGIN TRANSACTION
* DELETE table\_y
* INSERT INTO table\_y <3 selects unioned together>
* UPDATE table\_x
* COMMIT TRANSACTION
The selects are "not pretty", but when executed in-line they execute in no time. Including when the SP refuses to complete. And the profiler shows it is the INSERT at which the SP "stalls"
There are no parameters to the SP, and sp\_lock shows nothing blocking the process. | As others have said, something about the way the data or the source table statistics are changing is causing the cached query plan to go stale.
`WITH RECOMPILE` will probably be the quickest fix - use `SET STATISTICS TIME ON` to find out what the recompilation cost actually is before dismissing it out of hand.
If that's still not an acceptable solution, the best option is probably to try to refactor the insert statement.
You don't say whether you're using `UNION` or `UNION ALL` in your insert statement. I've seen `INSERT INTO` with `UNION` produce some bizarre query plans, particularly on pre-SP2 versions of SQL 2005.
* Raj's suggestion of dropping and
recreating the target table with
`SELECT INTO` is one way to go.
* You could also try selecting each of
the three source queries into their own
temporary table, then `UNION` those temp tables
together in the insert.
* Alternatively, you could try a
combination of these suggestions -
put the results of the union into a
temporary table with `SELECT INTO`,
then insert from that into the target
table.
I've seen all of these approaches resolve performance problems in similar scenarios; testing will reveal which gives the best results with the data you have. | This is the footprint of parameter-sniffing. Yes, first step is to try RECOMPILE, though it doesn't always work the way that you want it to on 2005.
Update:
I would try statement-level Recompile on the INSERT anyway as this might be a statistics problem (oh yeah, check that automatics statistics updating is on).
If this does not seem to fit parameter-sniffing, then compare th actual query plan from when it works correctly and from when it is running forever (use estimated plan if you cannot get the actual, though actual is better). You are looking to see if the plan changes or not. | MS SQL Server 2005 - Stored Procedure "Spontaneously Breaks" | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"stored-procedures",
""
] |
I have to retrieve only particular records whose sum value of size field is <=150.
I have table like below ...
```
userid size
1 70
2 100
3 50
4 25
5 120
6 90
```
The output should be ...
```
userid size
1 70
3 50
4 25
```
For example, if we add 70,50,25 we get 145 which is <=150.
How would I write a query to accomplish this? | Here's a query which will produce the above results:
```
SELECT * FROM `users` u
WHERE (select sum(size) from `users` where size <= u.size order by size) < 150
ORDER BY userid
```
However, the problem you describe of wanting the selection of users which would most closely fit into a given size, is a [bin packing problem](http://en.wikipedia.org/wiki/Bin_packing_problem). This is an [NP-Hard](http://www.codinghorror.com/blog/archives/001187.html) problem, and won't be easily solved with ANSI SQL. However, the above seems to return the right result, but in fact it simply starts with the smallest item, and continues to add items until the bin is full.
A general, more effective bin packing algorithm would is to start with the largest item and continue to add smaller ones as they fit. This algorithm would select users 5 and 4. | What you're looking for is a [greedy algorithm.](http://en.wikipedia.org/wiki/Greedy_algorithm) You can't really do this with one SQL statement. | how to find Sum(field) in condition ie "select * from table where sum(field) < 150" | [
"",
"sql",
"mysql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.