Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've been reading articles on how to program in a functional (i.e F#) style in C#, for example, foregoing loops for recursion and always returning a copy of a value/object instead of returning the same variable with a new state.
For example, what sort of code inspection things should I watch out for? Is there any way to tell if a method on a BCL class causes a mutation? | Here are two things that would help you find variables and fields whose values are getting changed. Mutability is more complex than this, of course (for example these won't find calls to add to collections) but depending on what you're looking for, they may be helpful.
1. Make all of your fields readonly; then they can only be set from the constructor, and not changed thereafter.
2. Pick up a copy of [ReSharper](http://www.jetbrains.com/resharper/). It expands on Visual Studio's syntax highlighting, and has an option to set up custom highlighting for [mutable local variables](http://resharper.blogspot.com/2008/05/functional-style-highlight-mutable.html). This will let you see at a glance whether locals are being modified. | The tool [NDepend](http://www.NDepend.com) can tell you where you have side effect. It can also ensure automatically that a class is immutable (i.e no side effect on its object instances) or a method is pure (i.e no side effects during the execution of the method. *Disclaimer: I am one of the developers of the tool.*
In short, trick is to define an attribute, such as, MyNamespace.ImmutableAttribute
and to tag classes that you wish to be immutable.
```
[Immutable]class MyImmutableClass {...}
```
If the class is not immutable, or more likely, if one day a developer modifies it and breaks its immutability, then the following [Code Rule over LINQ Query (CQLinq)](http://www.ndepend.com/Features.aspx#CQL) will suddenly warn:
```
warnif count > 0
from t in Application.Types
where !t.IsImmutable && t.HasAttribute("MyNamespace.ImmutableAttribute")
select t
```
On a side note, I wrote an article on immutability/purity/side-effects and NDepend usage:
[Immutable Types: Understand Them And Use Them](http://codebetter.com/blogs/patricksmacchia/archive/2008/01/13/immutable-types-understand-them-and-use-them.aspx) | How does one detect mutation in a C# function? | [
"",
"c#",
"functional-programming",
""
] |
I'm doing a project to manage membership and other kind of payments, but mainly membership so I created a polymorphic schema. any idea, improvement, for some reason I don't fully convinced about the schema.
as you will see, the idea of having month, year NULL-ABLE is allow save record of any other payment
```
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(11) NOT NULL auto_increment,
`partner_id` int(11) NOT NULL,
`status` enum('pending','accepted','cancelled','other') NOT NULL,
`created_on` datetime NOT NULL,
`concept` varchar(250) NOT NULL,
`type` enum('membership','other') NOT NULL default 'membership',
`source` enum('dineromail','casati','deposit','other') NOT NULL default 'dineromail',
`notes` text NULL,
`last_check_on` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM ;
CREATE TABLE IF NOT EXISTS `payments` (
`id` int(11) NOT NULL auto_increment,
`order_id` int(11) NOT NULL,
`month` int(11) default NULL,
`year` int(11) default NULL,
`amount` float NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx-order_id-month-year` (`order_id`,`month`,`year`)
) ENGINE=MyISAM ;
CREATE TABLE IF NOT EXISTS `partners` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
`last_name` varchar(255) default NULL,
) ENGINE=MyISAM;
``` | I would also include a date time stamp for when the payment is received and possibly mark if a payment is complete or incomplete amount. | A few commnets:
1. I would consider making month an enum in this case. It could certainly remove all ambiguity, unless you need to do math on that field (was this earlier that).
2. The money should be stored as a Decimal, not a float. Weird rounding stuff will creep in if not.
3. There is no concept of the price of an order. If they underpay, how will you know by how much?
4. (Kind of related to 3) You would typically see this as an invoice and payment type representation (even if you don't issue invoices), so that would imply that one payment could represent more than one order, and vice-versa, so that would imply a many to many relationship.
5. Do you care how they paid? (Check, Credit Card, Cash, etc.?)
6. Why would you make an order with multiple payments if they can only be received one in a month? What would you do if payments are received within the same month? Should there really be just a one-to-one relationship here? | Is this good membership payment database schema? | [
"",
"php",
"mysql",
"database",
"database-design",
"schema",
""
] |
I am not sure to be enough be by my question...
Well i'm developping a CMS in PHP with Zend Framework.
I would like to have a nice web gui to install and set up the application after unpacked it somewhere...
Some CMS or whatever the application is, offer this way to do by simply entering an 'install url' like '<http://localhost/app/install>'
I'd like to do the same but i don't want to let any users to set it up, so i am looking for a way to determine if the application has been set up or no.
Inspired by the pid file in the unix world, i though to do the same with an InstallState file.
Writing any boolean value inside and then check could be an idea..
What do you think about that ? Do you have better ideas ? | Though I upvoted Sam152's answer, I felt the need to give some further clarification (that just didn't really fit in a comment). The practice I use for these situations is as follows:
1. Let the user run the installer.
2. Upon successful completion, generate some form of lock file (many applications just create an 'installer.lock' file, with nothing in it). The presence of this file **should stop the user running the** ***installer*** **again**.
3. Prevent the main script from executing (even after a successful setup) until the **entire installation directory** is removed from the server.
This provides safeguards on two levels. It prevents the installer being run again (which may or may not be a problem for your application), and it prevents the product being run. You can use the presence of the locking file to tell the user that they've already compleed the install successfully, they don't need to install again, and that they should remove the directory.
Simple, safe, sorted. :) | You could write a value your database somewhere or simply have the file delete itself after the installation is complete. A lot of software ask users to delete the /install file after it is complete. To force this, you could check if the install directory exists and make the admin delete it before the rest of the script can run. | How to determine if a web application has been installed and set up? | [
"",
"php",
"zend-framework",
"installation",
""
] |
I'm trying to write an editor overtop a multi-threaded game engine. In theory, through the editor, the contents of the scene can be totally changed but I haven't been able to come up with a good way for the engine to cope with the changes. (ie delete an entity while the renderer was drawing it). Additionally, I'm hesitant to write code to manage locks at every instance I use an entity or resource that can be potentially deleted. I imagine there has to be a relatively more elegant solution.
Does anyone have any ideas or strategies I can start looking at?
Thanks! | In addition to the two-stage process suggested by @lassevk you could use a [Pipe structure](http://www.stackframe.net/en/content/06-2008/data-types-pipe) to "push" commands to the renderer so that these changes gets the form of another work item for the render engine.
For example, say your engine follows a workflow like:
1. Calculate positions
2. Process Physics
3. Process Lights Process Cameras
4. Render Scene
You could just add a new item to the workflow in the position 0, called Process Changes which pulls out the information from the Pipe and incorporates it to the scene. | If memory is not a problem, you can could have a two-stage process, where the changes are done in one model, and then a snapshot is taken for the renderer, this way the renderer would always see a consistent view of the model. | Multi-threading strategies? (Modifying a scene in a multi-threaded engine through an Editor) | [
"",
"c++",
""
] |
I have two tables, a `vehicle` table with columns:
* `id`
* `stock`
* `year`
* `make`
* `model`
and an `images` table with columns:
* `id`
* `vehicle_id`
* `name`
* `caption`
* `default tinyint(1)`
I am trying to list the vehicle's information, its default image, and a total count of images the vehicle has. Currently I am using the following `SELECT` statement:
```
SELECT vehicle.id, vehicle.stock, vehicle.year,
vehicle.make, vehicle.model, images.name,
COUNT(images.id)
FROM vehicle
LEFT JOIN images
ON vehicle.id = images.vehicle_id
```
I initially was using:
```
ON vehicle.id = images.vehicle_id AND images.default = 1
```
but then the images count would only be 1 or 0 depending if there was a default image in the database. I have tried using `UNION` and other `SELECT` statements but I am still unable to get a proper result. Do I need to use two `SELECT` statements or is there another way to handle it with `JOIN` or `UNION`? | ```
SELECT
`vehicle`.`id`,
`vehicle`.`stock`,
`vehicle`.`year`,
`vehicle`.`make`,
`vehicle`.`model`,
`images`.`name`,
(
SELECT COUNT(*)
FROM `images`
WHERE `vehicle_id` = `vehicle`.`id`
) AS `image_count`
FROM `vehicle`
LEFT JOIN `images`
ON `images`.`vehicle_id` = `vehicle`.`id`
WHERE `images`.`default`
``` | In the way the anser suggests, you get repeated values of "vehicle". A better way, is to group results. Try without the JOIN :
```
SELECT
`vehicle`.`id`,
`vehicle`.`stock`,
`vehicle`.`year`,
`vehicle`.`make`,
`vehicle`.`model`,
`images`.`name`,
(
SELECT COUNT(*)
FROM `images`
WHERE `vehicle_id` = `vehicle`.`id`
) AS `image_count`
FROM `vehicle`
WHERE `images`.`default`
``` | How do I get a count of associated rows in a left join in MySQL? | [
"",
"sql",
"mysql",
"select",
"join",
"subquery",
""
] |
I want to know *everything* about the `yield` statement, in an easy to understand form.
I have read about the `yield` statement and its ease when implementing the iterator pattern. However, most of it is very dry. I would like to get under the covers and see how Microsoft handles return yield.
Also, when do you use yield break? | `yield` works by building a state machine internally. It stores the current state of the routine when it exits and resumes from that state next time.
You can use Reflector to see how it's implemented by the compiler.
`yield break` is used when you want to stop returning results. If you don't have a `yield break`, the compiler would assume one at the end of the function (just like a `return;` statement in a normal function) | As Mehrdad says, it builds a state machine.
As well as using Reflector (another excellent suggestion) you might find [my article on iterator block implementation](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) useful. It would be *relatively* simple if it weren't for `finally` blocks - but they introduce a whole extra dimension of complexity! | yield statement implementation | [
"",
"c#",
".net",
"yield",
"iterator",
""
] |
I want to write an application using [processing-JS](http://processingjs.org), and I'd like to be able to load it with server-side data. I haven't written the server side yet so I can use anything, but it seems the obvious AJAX thing would be to use JSON to upload the data into the page.
How can I get access to that data from my processing code? Is it something as easy as the data is in scope, or could be attached to the window object and directly accessed from the processing code?
**Update**: Let me refine the question a little bit. I'm comfortable with JSON (but thanks for the links) and with writing code for both the client and server; my real question (which admittedly could be somewhat silly) is: if I get data with, e.g., JQuery, and want to manipulate it in processing-js, is it in the same namespace? Do I have to do anything special to access it? | Your Processing code gets "sloppily" parsed and converted into JavaScript. Anything the parser doesn't understand just gets ignored, which means you can freely mix bits of JavaScript code in with your Processing and it will, in general, "just work".
Have a look here for more information: <http://processingjs.org/reference/articles/best-pratice> | You could use [jQuery](http://jquery.com/) like [this](http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback) to get JSON results from your server and iterate them to do whatever. I'm sure there wouldn't be a problem with using processing-JS and jQuery together. | Using JSON from Processing-JS | [
"",
"javascript",
"ajax",
"json",
"processing",
""
] |
I'm trying to port a PHP site developed by another coder (who is no longer around) and I'm having a problem with the Apache Rewrite rules which are prompting a file download on the target server. I'm sure this is a simple problem, but I'm having some difficulty Googling an answer. I'm running on a (dedicated) Ubuntu Server with a standard installation of Apache and PHP5 and porting from shared a shared server where everything runs fine. No site files have been altered during the port.
The .htaccess file contains this code (only)
```
# Use PHP5 as default
AddHandler application/x-httpd-php5 .php
Options -Indexes FollowSymlinks
RewriteEngine on
RewriteRule ^html/(.*) /index.php?init=site\/$1\/$2\/$3\/$4\/$5\/$6\/$7\/$8\/$9
RewriteRule ^mykart$ /index.php?admin=true
RewriteRule ^mykart/$ /index.php?admin=true
RewriteRule ^mykart/(.*)$ /index.php?init=admin\/$1\/$2\/$3\/$4\/$5\/$6\/$7\/$8\/$9&admin=true
```
When I try to open the file <http://www.mysite.com/html/#home> the browser attempts to download the (index.php) file instead of displaying it, with the message
"You have chosen to Open
[dialog shows blank space here]
which is a: application/x-httpd-php
from....
"
I guess I must have missed something in either the PHP or Apache configuration, but what?
EDIT: To clarify, the server is running Apache2 and has several, functioning, PHP sites on it. Furthermore if I delete the .htaccess file and run a simple phpinfo display page everything runs fine, so it's not the execution of PHP per see. | I suppose that the MIME type `application/x-httpd-php5` is not valid. I’ve tried it on my local machine and it caused the same behavior.
Have you tried `application/x-httpd-php` instead? | Looks like an Apache config issue, of course I could be wrong. Have you checked httpd.conf for the following lines:
```
# Add index.php to your DirectoryIndex line:
DirectoryIndex index.html index.php
AddType text/html php
``` | Apache rewrite rule forces download | [
"",
"php",
"apache",
".htaccess",
""
] |
I have the basic html form echoed through php:
```
<html>
<body>
<?php
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
echo '<form action="up.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
</body>
</html>
```
I would like to pass the value of pk to up.php
Modifying action="up.php?pk=$pk" did not work. | Use a hidden field:
```
<input type="hidden" name="pk" value="<?php echo $pk; ?>">
```
By the way, printing large amounts of HTML like you have there is *ugly*. Consider either stepping out of PHP to do so, using HEREDOC, a template engine, or a framework.
**EDIT**:
As noted below, you should not print GET and POST data back to the page without sanitizing it first. Assuming pk is a primary key, you should wrap `$pk` above with the [intval](http://www.php.net/intval) function, *at the very least*. | I agree with all the comments regarding some kind of input control of the $\_GET['pk'] variable. I would recommend the filter module in php, which is pretty much a default installed module I believe.
```
<html>
<body>
<?php
$param = filter_input(INPUT_GET, 'pk', FILTER_SANITIZE_ENCODED);
?>
<form action="up.php<?php echo (isset($param) && $param != false) ? '?pk=' . $params : ''); ?>" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
```
You can find more information about the filter module here: [link text](https://www.php.net/manual/en/ref.filter.php)
I also agree with Paolo Bergantino, this is not the prettiest way to do it, and a template engine, heredocs or regexp could be a better way of increasing the readability and maintainability of the system. | passing parameters to php in a form? | [
"",
"php",
"forms",
""
] |
I'm quite familiar with the System.Diagnostics.Process class. But, I'm wondering about how I can monitor a specific process (i.e. Check to see if it's running every XX mins/secs). I need to be able to checking whether a process is running and if it is, continue with initialising the rest of the program.
Thanks,
-Zack | If you didn't start the process yourself, you get find the `Process` object associated with a process by looking through the list returned by [`Process.GetProcessesByName(...)`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx) or [`Process.GetProcesses(...)`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocesses.aspx)
Once you have the process, you can listen read its properties (including [`HasExited`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx)) and (as Jon mentions in his response) if you set [`EnableRaisingEvents`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx) you can listen to its events (including [`Exited`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx)). | Checking if it's still running is easy: [`Process.HasExited`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx).
Rather than polling this periodically, however, you could set [`EnableRaisingEvents`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx) to true, and attach a handler to the [`Exited`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx) event.
EDIT: To answer the question in the comment about "fetching" the process - that depends on what you already know. If you know its process ID, you could use [`Process.GetProcessById`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessbyid.aspx). If you only know its name, you would have to use [`Process.GetProcessesByName`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx) and work out what to do if you get multiple results. If you don't know the *exact* name, you could use [`Process.GetProcesses`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocesses.aspx) and look for whatever you *do* know about it. Those options are effectively in order of preference :) | Process Monitoring | [
"",
"c#",
"process",
""
] |
I have an application that is currently creating a text file to import into an accounting application. It is using the following code to create the file and write lines to it:
```
TextWriter tw = new StreamWriter(ExtractFileName);
tw.WriteLine("ref\tACCOUNT\tbatch\tDEBIT\tCREDIT\tDesc");
```
I now need to create multiple extract files and plan on compressing them into a single .zip file using SharpZipLib (#ziplib) and want to change my code to do the text file creation "in memory" and using that to create my zip file. I think I should be creating/using a MemoryStream but can't figure out how to port my existing code.
Thanks. | You could do:
```
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine("ref\tACCOUNT\tbatch\tDEBIT\tCREDIT\tDesc");
``` | **Don't create unnecessary abstraction.** While the exporter class is cool it only adds value when you have more than one export strategy. Otherwise it is clutter that distracts from the core purpose of your code.
If you want to add the exporter to *practice* a good abstraction technique that's fine, but there are **infinite** abstraction opportunities when writing any significant amount of code. Abstraction creates modularity and reduces code **only** when there are multiple implementations of a particular process or data set. | c# creating file using memorystream instead of textwriter | [
"",
"c#",
"memorystream",
""
] |
I'm creating a 2d tile based sim game.
I have a 2d array of gridSquares, which are accessed and changed from many different classes and methods.
Should I pass the 2d array of gridSquares each time, or make it a global? Which is best practice?
I was thinking, would it be an option to create a class which just contains a set of variables which all classes could extend? Is that a good or bad idea / not good practice?
I'm still fairly new to java so I'm still learning lots!
Thanks in advance.
Rel | You should not be designing in terms of a data structure. Java's an object-oriented language. Try thinking about your problem as objects interacting. It's not a 2D array; it's a Board object. Build the behavior for manipulating its state into the problem and hide the fact that you happen to have chosen a 2D array.
I don't have all the details of a Board worked out, but it would start like this:
```
public class Board
{
// This is what you're passing around now; Board hides it.
// Square is the abstraction of a position on the Board
private Square[][] grid;
public Board(int nRows, int nCols)
{
this.grid = new Square[nRows][];
for (int i = 0; i < this.grid[i].length; ++i)
{
this.grid[i] = new Square[nCols];
}
}
// Now add methods for adding Pieces to the Board, rules for moving them, etc.
}
``` | Pass them in constructors and hold them in member variables.
If you access them from too many places you probably have a design problem. | Should I be using global variables or passing the variables in java? | [
"",
"java",
"global-variables",
"argument-passing",
""
] |
I'm hacking some support for DomainKeys and DKIM into an open source email marketing program, which uses a python script to send the actual emails via SMTP. I decided to go the quick and dirty route, and just write a perl script that accepts an email message from STDIN, signs it, then returns it signed.
What I would like to do, is from the python script, pipe the email text that's in a string to the perl script, and store the result in another variable, so I can send the email signed. I'm not exactly a python guru, however, and I can't seem to find a good way to do this. I'm pretty sure I can use something like `os.system` for this, but piping a variable to the perl script is something that seems to elude me.
In short: How can I pipe a variable from a python script, to a perl script, and store the result in Python?
EDIT: I forgot to include that the system I'm working with only has python v2.3 | [os.popen()](http://docs.python.org/library/os.html#os.popen) will return a tuple with the stdin and stdout of the subprocess. | Use [subprocess](http://docs.python.org/library/subprocess.html). Here is the Python script:
```
#!/usr/bin/python
import subprocess
var = "world"
pipe = subprocess.Popen(["./x.pl", var], stdout=subprocess.PIPE)
result = pipe.stdout.read()
print result
```
And here is the Perl script:
```
#!/usr/bin/perl
use strict;
use warnings;
my $name = shift;
print "Hello $name!\n";
``` | How to call a Perl script from Python, piping input to it? | [
"",
"python",
"perl",
"domainkeys",
"dkim",
""
] |
I was searcing for some information, and I found a method like this:
```
public partial class Customer {
private string customerIDField;
private string companyNameField;
private string contactNameField;
private string contactTitleField;
private string addressField;
private string cityField;
private string regionField;
private string postalCodeField;
private string countryField;
private string phoneField;
private string faxField;
// Other properties
}
```
Then the coder used this class like this. How?
```
private static Model.Customer[] BuildCustomers(SqlDataReader reader)
{
if (reader.HasRows)
{
List<Model.Customer> custs = new List<Model.Customer>();
while (reader.Read())
{
Model.Customer cust = new Model.Customer();
cust.CustomerID = reader["CustomerID"].ToString();
cust.CompanyName = reader["CompanyName"].ToString();
cust.ContactName = reader["ContactName"].ToString();
custs.Add(cust);
}
return custs.ToArray();
}
return null;
}
```
I really want to learn how this coder uses "Customer -----> Model.Customer[] ". Is there any method that does this? | Are you asking how to convert a `Customer` object in to an array?
There are a couple of ways to do it - the example you showed in the second piece of code built up a `List` by adding `Customers`, then converted the `List` to an array. This works well when you do not know how many customers you have, you keep adding to the list and create and array at the end and the array will be the correct size.
If you just have one `customer` object you could also create an array called `customers` with one element and add a `customer` object to it like this:
```
Model.Customer[] customers = new Model.Customer[1];
customers[0] = customer;
```
or, an even shorter way:
```
Model.Customer[] customers = new Model.Customer[] {customer};
``` | Is your confusion over how the method is returning an array?
It's just using [`List<T>.ToArray()`](http://msdn.microsoft.com/en-us/library/x303t819.aspx). The list is built up one customer at a time, and then `ToArray()` is called at the end. | How can I make class into an array? | [
"",
"c#",
".net",
"asp.net",
""
] |
How can I get the **number of "1"s** in the binary representation of a number without actually converting and counting ?
e.g.
```
def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
``` | IMO, a good approach would be to use a look-up table - create a dictionary which converts bytes to number of 1's (you can use the code you posted to generate it, it would only need to run once), and then use something like this:
```
def number_of_ones(n):
sum = 0
while n != 0:
sum += lookup_table[n & 0xff]
n >>= 8
return sum
```
I believe this is a fairly good trade-off between space and running-time. | I'm not a python programmer, but hopefully it will be enough for you to follow.
```
c = 0
while n:
c += 1
n &= n - 1
return c
```
While a little obscure, it's primary advantage is speed and simplicity. The while loop is only iterated once for every bit set to 1 in n. | How can I check Hamming Weight without converting to binary? | [
"",
"python",
"algorithm",
"discrete-mathematics",
"hammingweight",
""
] |
```
int? test;
try
{
test = (int?) Int32.Parse ("7");
} catch {}
if (test == null)
Console.WriteLine("test is null!");
else
Console.WriteLine("test = {0}", test);
```
I am have some code that does something VERY similar to this, same idea really... Creating a variable, trying to initialize it, then test to see if the initialization was a success.
Visual Studios is giving me an error saying " Use of unassigned local variable 'test' ", which is kind of annoying, this is easily fixed by setting the first line to:
```
int? test = null;
```
but I am curious what the difference between the two lines are, because the compiler really seems to care. And to the best of my knowledge, the two lines do the same thing. | The problem is the catch block. The compiler must assume the Int32.Parse code can throw and hence hit your catch block. In the case that happens the Int32.Parse line does not complete and hence test is never assigned a value. That means the "if" line is attempting to use an uninitialized value.
You can fix this by
1. Assigning test a value in the catch block
2. Initializing it to null at the start of the method | you're confusing the difference between what is a variable declaration and what is variable initialization
```
int? test;
```
simply states that you have a variable named test that is a nullable int
but
```
int? test = null;
```
states that you have a variable named test that is a nullable int and its value is null
In VB there is no distinction, but in c# there is a difference. That's why the compiler is complaining, because if something fails in your try block then your test variable would never have been initialized. | C# Initialization Confusion! | [
"",
"c#",
"syntax",
"null",
""
] |
I have an SQL 2008 server running three instances. Each instance is assigned a unique IP address and listens on port 1433. Only TCPIP is enabled.
All of my ASP.Net applications connect successfully using the IP address, with a connection string similar to:
```
User ID=SQLUser;Password=userpass;Database=TestDB;Data Source=sqlserver
```
My ASP applications will only connect to the default instance; I am getting this error whenever I try to connect to another instance:
```
Microsoft OLE DB Provider for ODBC Drivers error '80004005' <br />
[Microsoft][ODBC SQL Server Driver][DBNETLIB]Invalid connection.
```
The ASP connection strings are like this:
```
driver={SQL Server};server=sqlserver;uid=SqlUser; pwd=userpass; database=TestDB
```
I turned off Windows Firewall on both the IIS and SQL Server for now. There's not any other firewalls between the SQL Server and the IIS server. SQL Browser is running on the SQL Server. I tried modifying the ASP connection strings to include the instance name, like:
```
driver={SQL Server};server=sqlserver/InstanceName;uid=SqlUser;pwd=userpass;database=TestDB
```
but I get the same error.
Is there any way to connect to a named instance from ASP? | Write the server name like so:
```
server=sqlserver\InstanceName
```
Also, check the port number as it might not be on 1433.
Related SO question:
* [SQL Server 2005 Named Instance port problem](https://stackoverflow.com/questions/272429/sql-server-2005-named-instance-port-problem) | EDIT: Sql Server names are not [UNC](http://en.wikipedia.org/wiki/Path_(computing)) ;)
Trying it with a \ instead of a / like:
```
mysqlserver\myinstance
```
Personally I always try to include the port. It saves a roundtrip where the client tries to figure out the port number:
```
server=mysqlserver\myinstance,1433;uid=SqlUser;pwd=userpass;database=TestDB
```
Interesting, is database a synonym for initial catalog? | ASP Connections to SQL 2008 Named Instance | [
"",
"sql",
"asp-classic",
""
] |
I want to be able to initialize a vector of a size 'SIZE' before main. Normally I would do
```
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
```
But the problem is that I would like to initialize the first item of the vector to be of a certain value, and the other to another value.
Is there an easy way to do this? | Here's alternative solution:
```
#include <vector>
static std::vector<int> myVector(4,100);
bool init()
{
myVector[0] = 42;
return true;
}
bool initresult = init();
int main()
{
;
}
``` | Try this:
```
static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init / sizeof init[ 0 ]);
```
Also, see [`std::generate`](http://en.cppreference.com/w/cpp/algorithm/generate) (if you want to initialize within a function). | Initializing a vector before main() in C++ | [
"",
"c++",
"stl",
"static",
"vector",
""
] |
I've searched high and low for a list of the contents of .net 3.0 and 3.5 framework, since i've been programming using old technologies such as hashtables instead of a dictionary(newer technology).
I've been having a bit of a swat up and wondered where I can find a list of all the latest capabilities of C# and the .Net framework so that I can start getting my head round how to use some of the stuff.
Help would be greatly appreciated! | To be honest, [wikipedia](http://en.wikipedia.org/wiki/.NET_Framework) does a reasonable job here...
.NET 3.0 introduces:
* WCF - communication framework to hopefully replaces asmx and remoting
* WF - workflow framework for sequential and state flows
* WPF - replacement for windows forms
.NET 3.5 introduces:
* LINQ
+ LINQ-to-SQL
+ LINQ-to-Objects
+ `HashSet<T>`, `Action<...>`, `Func<...>`, `Expression<...>`, `Lookup<,>`
* C# 3.0
* some other minor tweaks ;-p
.NET 3.5 SP 1 introduces:
* LINQ
+ Entity Framework
+ ADO.NET Data Services
EDIT: (jonskeet) The [C#](http://en.wikipedia.org/wiki/C_Sharp_(programming_language)) page has a similar layout, showing which versions introduced which features. | "latest capabilities of C#"...
**Implicitly Typed Local Variables:**
The compiler derives the type from the initialized value.
```
// Implicitly typed local variables.
var myInt = 0;
var myBool = true;
var myString = "Time, marches on...";
```
These are greatly useful while using with LINQ.
**Automatic properties:**
No need to write the entire property syntax.
```
class Car
{
// Automatic property syntax.
public string PetName { get; set; }
}
```
**Extension Methods:**
This technique can be quite helpful when you need to inject new functionality into types for which you do not have an existing code base.
More information on Scott Gu's blog [here](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx). | C# Capabilities? | [
"",
"c#",
".net",
".net-3.5",
"c#-3.0",
""
] |
I am trying to come up with a query to report revenue. It will require 2 tables: clicks and offers. Revenue is calculated by the number of conversions \* commission for the offer. Conversions are stored in the clicks table in a field called "conversionDate", and the commission for each offer is stored in the offers table.
There needs to be a condition in the query to ignore any clicks that did not convert (meaning conversionDate is NULL) when adding up revenue for the offer.
What I've got needs a bit of tweaking as it is not giving the correct value for revenue:
SELECT o.name offer, count(c.id) clicks, if(not isnull(c.conversionDate), revenue=revenue+o.commission, revenue) revenue FROM clicks c, offers o where c.offerID=o.ID GROUP BY o.ID;
I have 3 dummy records in clicks right now, 2 of which are conversions. With the commission set to 1, revenue should be 2. The result I am getting is 1. Am I on the right track or should the revenue calculation be some kind of subquery or what? | I'd write the query this way:
```
SELECT o.name AS offer, COUNT(c.id) AS clicks,
SUM( IF(c.conversionDate IS NOT NULL, o.commission, NULL) ) AS revenue
FROM offers o JOIN clicks c ON (c.offerID=o.ID)
GROUP BY o.ID;
```
Here's another solution, but offers that don't have *any* converted clicks are not shown in the query result:
```
SELECT o.name AS offer, COUNT(c.id) AS clicks,
SUM(o.commission) AS revenue
FROM offers o JOIN clicks c
ON (c.offerID=o.ID AND c.conversionDate IS NOT NULL)
GROUP BY o.ID;
``` | move the null check to the WHERE clause | sql query with if statment | [
"",
"sql",
"mysql",
"conditional-statements",
""
] |
I would like to know where is the best place to set my db object with my model.
Should I hard coded it since my model should be designed for one project, so i set it inside my constructor or wherever i do initialization ?
or
Should I pass my db object to my constructor when instancing my object ?
What is the best way, i mean from experimented users, and efficient that'll give me more confort to use ? | Couple of things:
1. Most PHP projects that utilize a database connection represent that database using a [Singleton pattern][1], if you aren't sure what this is, read up on it.
2. Typically I define my database connections in a configuration file which can easily be changed between environments (development, stage, production).
3. I'll then instantiate my database connection in a bootstrap file using the aforementioned Singleton pattern and configuration file.
4. My models will typically completely abstract the database/table data store, for each model I'll do something like this:
bootstrap.php
<?php
```
$config = load_config_data(ENVIRONMENT);
Db::setDefaultAdapter($config['database']);
```
Model/Table/User.php
<?php
```
class Table_User extends Db_Table
{
// Table name
protected $_name = 'user';
/* Do a bunch of database specific stuff */
}
```
Model/User.php
update(
array('username'=>$username),
Db::quoteInto('userid = ?', $userid)
);
}
}
This is pretty much an introduction to the [Model][2] in the [Zend Framework MVC][3], I would check it out for some ideas on how to organize your code (or save yourself some trouble and actually use the [framework][4].)
[1]: https://www.php.net/singleton
[2]: http://framework.zend.com/manual/en/zend.db.table.html
[3]: http://framework.zend.com/manual/en/zend.controller.html
[4]: http://framework.zend.com | For testability, you should pass it into the constructor rather than hard coding it. This helps you to write unit test because you can mock your DB object. | Where should i set my db object in my model ? (MVC) | [
"",
"php",
"model-view-controller",
"oop",
""
] |
How can I write a regular expression to replace links with no link text like this:
```
<a href="http://www.somesite.com"></a>
```
with
```
<a href="http://www.somesite.com">http://www.somesite.com</a>
```
?
This is what I was trying to do to capture the matches, and it isn't catching any. What am I doing wrong?
```
string pattern = "<a\\s+href\\s*=\\s*\"(?<href>.*)\">\\s*</a>";
``` | I could be wrong, but I think you simply need to change the quantifier within the `href` group to be lazy rather than greedy.
```
string pattern = @"<a\s+href\s*=\s*""(?<href>.*?)"">\s*</a>";
```
(I've also changed the type of the string literal to use @, for better readability.)
The rest of the regex *appears* fine to me. That you're not capturing any matches at all makes me think otherwise, but there could be a problem in the rest of the code (or even the input data - have you verified that?). | I wouldn't use a regex - I'd use the [Html Agility Pack](http://www.codeplex.com/htmlagilitypack), and a query like:
```
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[.='']")) {
link.InnerText = link.GetAttribute("href");
}
``` | How can I write a regular expression to capture links with no link text? | [
"",
"c#",
".net",
"regex",
""
] |
I've written a few functions with a prototype like this:
```
template <typename input_iterator>
int parse_integer(input_iterator &begin, input_iterator end);
```
The idea is that the caller would provide a range of characters, and the function would interpret the characters as an integer value and return it, leaving `begin` at one past the last-used character. For example:
```
std::string sample_text("123 foo bar");
std::string::const_iterator p(sample_text.begin());
std::string::const_iterator end(sample_text.end());
int i = parse_integer(p, end);
```
This would leave `i` set to 123 and `p` "pointing" at the space before `foo`.
I've since been told (without explanation) that it's bad form to pass an iterator by reference. Is it bad form? If so, why? | There is nothing really wrong, but it will certainly limit the use of the template. You won't be able to just put an iterator returned by something else or generated like `v.begin()`, since those will be temporaries. You will always first have to make a local copy, which is some kind of boilerplate not really nice to have.
One way is to overload it:
```
int parse_integer(input_iterator begin, input_iterator end,
input_iterator &newbegin);
template<typename input_iterator>
int parse_integer(input_iterator begin, input_iterator end) {
return parse_integer(begin, end, begin);
}
```
Another option is to have an output iterator where the number will be written into:
```
template<typename input_iterator, typename output_iterator>
input_iterator parse_integer(input_iterator begin, input_iterator end,
output_iterator out);
```
You will have the return value to return the new input iterator. And you could then use a inserter iterator to put the parsed numbers into a vector or a pointer to put them directly into an integer or an array thereof if you already know the amount of numbers.
```
int i;
b = parse_integer(b, end, &i);
std::vector<int> numbers;
b = parse_integer(b, end, std::back_inserter(numbers));
``` | **In general:**
If you pass a non-`const` reference, the caller doesn't know if the iterator is being modified.
You could pass a `const` reference, but usually iterators are small enough that it gives no advantage over passing by value.
**In your case:**
I don't think there's anything wrong with what you do, except that it's not too standard-esque regarding iterator usage. | What's wrong with passing C++ iterator by reference? | [
"",
"c++",
"pass-by-reference",
"iterator",
""
] |
Among the Java [templating solutions](http://en.wikipedia.org/wiki/Template_engine_(web)) such as Apache Velocity, Freemarker, Hamlets, Tapestry, StringTemplate, JSP, JSP Weaver (others?) which would most closely approximate the conciseness and simplicity of similar HTML templating solutions in Ruby - haml/erb. I'm concerned both with the syntax of the templating engine as well as how simply it integrates with Controller code on the server. | i think what u are getting at is this
ruby
```
<% foreach vars do |var| %>
<!-- some html code to do -->
<%=h var %>
<% end %>
```
java
```
<% for( int i = 0; i < vars.length; i++ ) { %>
<%=vars[i]%>
<% } %>
```
so the tags are similar
for the a java side of the controller , views spring provides a way to separate them nicely | The practice of mixing code and data is frowned upon in Java much more so than in Ruby. The recommended Java practice is to use taglibs instead of code blocks. I mention this only because if you write your Java templates in the same way as typical Ruby templates, other Java developers (I'm assuming you work on a team) are likely to complain.
So now to answer your question.....standard JSPs together with JSTL and EL are really not a bad solution. But for extra conciseness, check out GSPs, the templating solution used by Grails. You can use GSPs in any Java webapp, i.e. you don't need to be using Groovy/Grails. | Which Java HTML templating technology works in a way that is closest to Ruby (erb/haml)? | [
"",
"java",
"haml",
"velocity",
"freemarker",
"stringtemplate",
""
] |
I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).
I have a simple class I'd like to persist, but keep getting:
```
SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
[ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
[ a bunch more ]
```
The relevant code for the persisted class is:
```
package hibtest.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem {
protected Long id;
protected Mensagem() { }
@Id
@GeneratedValue
public Long getId() {
return id;
}
public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
```
And the actual running code is just plain:
```
SessionFactory factory = new AnnotationConfiguration()
.configure()
.buildSessionFactory();
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Mensagem msg = new Mensagem("YARR!");
session.save(msg);
tx.commit();
session.close();
}
```
I tried some "strategies" within the `GeneratedValue` annotation but it just doesn't seem to work. Initializing `id` doesn't help either! (eg `Long id = 20L`).
Could anyone shed some light?
**EDIT 2:** confirmed: messing with`@GeneratedValue(strategy = GenerationType.XXX)` doesn't solve it
**SOLVED:** recreating the database solved the problem | Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of `SchemaUpdate`.
If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with `SchemaExport`. | If you want MySQL to automatically produce primary keys then you have to tell it when creating the table. You don't have to do this in Oracle.
On the Primary Key you have to include `AUTO_INCREMENT`. See the example below.
```
CREATE TABLE `supplier`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`FIRSTNAME` varchar(60) NOT NULL,
`SECONDNAME` varchar(100) NOT NULL,
`PROPERTYNUM` varchar(50) DEFAULT NULL,
`STREETNAME` varchar(50) DEFAULT NULL,
`CITY` varchar(50) DEFAULT NULL,
`COUNTY` varchar(50) DEFAULT NULL,
`COUNTRY` varchar(50) DEFAULT NULL,
`POSTCODE` varchar(50) DEFAULT NULL,
`HomePHONENUM` bigint(20) DEFAULT NULL,
`WorkPHONENUM` bigint(20) DEFAULT NULL,
`MobilePHONENUM` bigint(20) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB DEFAULT CHARSET=latin1;
```
Here's the Entity
```
package com.keyes.jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigInteger;
/**
* The persistent class for the parkingsupplier database table.
*
*/
@Entity
@Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
**@GeneratedValue(strategy = GenerationType.IDENTITY)**
@Column(name = "ID")
private long id;
@Column(name = "CITY")
private String city;
@Column(name = "COUNTRY")
private String country;
@Column(name = "COUNTY")
private String county;
@Column(name = "EMAIL")
private String email;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "HomePHONENUM")
private BigInteger homePHONENUM;
@Column(name = "MobilePHONENUM")
private BigInteger mobilePHONENUM;
@Column(name = "POSTCODE")
private String postcode;
@Column(name = "PROPERTYNUM")
private String propertynum;
@Column(name = "SECONDNAME")
private String secondname;
@Column(name = "STREETNAME")
private String streetname;
@Column(name = "WorkPHONENUM")
private BigInteger workPHONENUM;
public supplier()
{
}
public long getId()
{
return this.id;
}
public void setId(long id)
{
this.id = id;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCounty()
{
return this.county;
}
public void setCounty(String county)
{
this.county = county;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getFirstname()
{
return this.firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
public BigInteger getHomePHONENUM()
{
return this.homePHONENUM;
}
public void setHomePHONENUM(BigInteger homePHONENUM)
{
this.homePHONENUM = homePHONENUM;
}
public BigInteger getMobilePHONENUM()
{
return this.mobilePHONENUM;
}
public void setMobilePHONENUM(BigInteger mobilePHONENUM)
{
this.mobilePHONENUM = mobilePHONENUM;
}
public String getPostcode()
{
return this.postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getPropertynum()
{
return this.propertynum;
}
public void setPropertynum(String propertynum)
{
this.propertynum = propertynum;
}
public String getSecondname()
{
return this.secondname;
}
public void setSecondname(String secondname)
{
this.secondname = secondname;
}
public String getStreetname()
{
return this.streetname;
}
public void setStreetname(String streetname)
{
this.streetname = streetname;
}
public BigInteger getWorkPHONENUM()
{
return this.workPHONENUM;
}
public void setWorkPHONENUM(BigInteger workPHONENUM)
{
this.workPHONENUM = workPHONENUM;
}
}
``` | Hibernate: "Field 'id' doesn't have a default value" | [
"",
"java",
"hibernate",
"jpa",
"persistence",
""
] |
Bulls & Cows is a game for two players in which each one has a secret number with 4 non-repeating digits, and each one tries to guess the other number.
For instance, let´s say my secret number is 1576.
If my opponent says the number 1234, i would answer: 1F, because the digit 1 is in my secret number and in the same position.
If my opponent says the number 7890, i would answer: 1P, because the digit 7 is in my secret number and in different position.
ETC.
[Here](http://en.wikipedia.org/wiki/Bulls_and_Cows) it is explained.
Well, as a hobby, I wish to implement a computer player that tryes to guess my number, but I don't know where to start,
* any ideas?
* Is there something already done on this game?
* Is out there any C# Implementation? | This is a variant of the game [Mastermind](http://en.wikipedia.org/wiki/Mastermind_(board_game)#Algorithms). Quite a lot of work has been done on algorithms for guessing solutions. Beyond those shown at the wikipedia link, some googling using "mastermind" as the keyword will probably turn up a lot. (I'm assuming you haven't found much so far because you didn't know that name). | It sounds like a variation on the game 'Mastermind' - there are a few resources [here](http://richardbowles.tripod.com/durham/ai/mastermind/mastermind.html) and [here](http://ece.uprm.edu/~s016965/ICOM%205015%20-%20Artificial%20Intelligence/Mastermind%20Report.doc) (.doc), as well as on the [Wikipedia page](http://en.wikipedia.org/wiki/Mastermind_(board_game)#Algorithms).
Have fun! | Bulls & Cows C# Implementation (Mastermind Variation) | [
"",
"c#",
"artificial-intelligence",
""
] |
I am trying to programatically unzip a zipped file.
I have tried using the `System.IO.Compression.GZipStream` class in .NET, but when my app runs (actually a unit test) I get this exception:
> System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream..
I now realize that a `.zip` file is not the same as a `.gz` file, and that `GZip` is not the same as `Zip`.
However, since I'm able to extract the file by manually double clicking the zipped file and then clicking the "Extract all files"-button, I think there should be a way of doing that in code as well.
Therefore I've tried to use `Process.Start()` with the path to the zipped file as input. This causes my app to open a Window showing the contents in the zipped file. That's all fine, but the app will be installed on a server with none around to click the "Extract all files"-button.
So, how do I get my app to extract the files in the zipped files?
Or is there another way to do it? I prefer doing it in code, without downloading any third party libraries or apps; the security department ain't too fancy about that... | We have used [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) successfully on many projects. I know it's a third party tool, but source code is included and could provide some insight if you chose to reinvent the wheel here. | With **.NET 4.5** you can now unzip files using the .NET framework:
```
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath);
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
```
The above code was taken directly from Microsoft's documentation: <http://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx>
`ZipFile` is contained in the assembly `System.IO.Compression.FileSystem`. (Thanks nateirvin...see comment below). You need to add a DLL reference to the framework assembly `System.IO.Compression.FileSystem.dll` | Unzip files programmatically in .net | [
"",
"c#",
"unzip",
""
] |
I'm working on a data warehouse project and would like to know how to (preferably in a Derived Column component in a Data flow) strip the date piece off of a SQL datetime record.
Once I have the datetime converted to just a time I am going to do a lookup on the time to find the related time record in a time dimension table.
Can someone give me a simple function to accomplish this inside a derived column transform?
Example: Transform a datetime such as "12/02/2008 11:32:21 AM" into simply "11:32:21 AM". | I would just do a cast to `DT_DBTIME` type (using Derived Column transform, or Convert type transform). `DT_DBTIME` contains just (hours, minutes, seconds) part of the date/time, so you'll get rid of the date part. | If you need to do this in a variable expression Michael's solution won't work, but you can use the following expression:
```
(DT_DATE)(DT_DBDATE)GETDATE()
```
(DT\_DBDATE) converts the current date and time to a date only. But the new datatype is not compatiple with SSIS's datetime. Therefore you'll have to use (DT\_DATE) for converting to a compatible type.
Courtesy of this solution belongs to Russel Loski who has posted it in his blog:
<http://www.bidn.com/blogs/RussLoski/ssas/1458/converting-datetime-to-date-in-ssis> | How do I strip the date off of a datetime string in SQL SSIS? | [
"",
"sql",
"t-sql",
"ssis",
"business-intelligence",
""
] |
I've tried using the standard serializing type things, stuff like:
```
FileOutputStream f_out;
try {
f_out = new FileOutputStream("MAOS.data");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject(s);
obj_out.flush();
obj_out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} ;
```
But the problem seems to be that if my object s contains any recursion at ALL I get a stack overflow. If s is a graph that contains nodes and edges (with nodes knowing about edges for purposes of spreading activation, and edges knowing about nodes for the same reason) then it stack overflows. If I take edges out entirely, and just have nodes that know about which nodes they're supposed to spread activation too, the same thing happens! I can even just try to save the ArrayList of nodes that the graph knows about, and the stack overflows again!
I'm so frustrated!
Graphs aren't exactly strange and mysterious, surely SOMEONE has wanted to save one before me. I'm seeing something about saving them as XML files here...but if my problem is the recursiveness, wouldn't I still be having the same problems even if I saved it differently? I just can't think of how you could make a graph without there being connections!
Am I just doing things wrong, or is this object serialization less powerful than I thought? Or do I need to just abandon the idea of saving a graph?
-Jenny
Edit, part of the HUGE stack trace:
```
Exception in thread "main" java.lang.StackOverflowError
at java.io.ObjectStreamClass.getPrimFieldValues(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
``` | These sort of structures are best saved like this:
```
collection of nodes, each node has a unique ID
collection of edges, each edge has two node IDs (or however many nodes an edge connects to)
```
without using any recursion. On reading the nodes, create a dictionary of nodes indexed by their ID. Then use the dictionary to fix up the edges when they're read. The IDs do not need to be part of the objects' run time structure, they only need to be unique within the data stream when the stream is written/read. | You could use the [JGraphT](http://www.jgrapht.org/) library which supports serializing graphs into a text file with the ML format. [GraphMLExporter Javadoc](http://www.jgrapht.org/javadoc/org/jgrapht/ext/GraphMLExporter.html). | Is there ANY way to save a graph object containing nodes and edges? | [
"",
"java",
"serialization",
""
] |
I'd like to filter a couple of nested xml elements, evaluation of their attributes. For this purposes I'm searching a efficient and lightweight java api or framework.
The main requirements are:
* filtering of element bodies, based
on some pattern or condition
* event based XML transformation
My first idea was apache jelly, but jelly has an ungly side effect. It removes CDATA tags and thats an unwanted behaviour.
Thanks in advance. | Finally I implemented the filterchain using dom4j and xpath.
I decided for this api because it is quite handy if you got to move a number of branches inside one document and it's build in xpath facilitates finding the wanted elements.
Thanks for your answers. | Go simple and try [SAX](http://www.saxproject.org/). | Perform xml transformation and filtering in java | [
"",
"java",
"xml",
"pipeline",
""
] |
Sorry. I don't know a good title for this, but please look here:
<http://joshblog.net/projects/logic-gate-simulator/Logicly.html>
I saw this from delicious over the weekend. It is in flash and I wondered if something like this, as far as the graphics and interaction goes, could be done in javascript (jquery or other library, *not* rolling my own.)
Again, I do not mean logic gates specifically but more the dragging, dropping and the drawing lines between objects, moving them around, etc.
Does anyone know of a website that has something like this in javascript? It kind of reminds me of dragging and dropping points on google maps but nicer. Thank you. | Looks like someone has recently made a [Logic Gate Thing](http://knolleary.net/code/logic/) that might interest you, though it doesn't quite have the level of animation that the Flash version has. ([Here](http://knolleary.net/2009/03/24/logic-gate-thing/) is an explanation from the author.) | <http://javascript.neyric.com/wireit/> and jQuery draggables is what you want.
Too bad the wire-it library is YUI. Would be nice if it were jQuery. | Can this type of flash dragging, dropping, and animation be done in a javascript library? | [
"",
"javascript",
"animation",
""
] |
I have a DataGridView that is populated with 4 columns and multiple rows of data. I want to iterate through the DataGridView and get the cell value from *a specific column only*, since I need this data to pass into a method.
Here is my code:
```
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
}
```
This just seems to go through all the cells, however I need to be able to specify something like:
```
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
foreach (DataGridViewCell cell in row.Cells[2])//Note specified column index
{
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
}
``` | Don't you just want to remove the inner `foreach` loop? Or have I missed something?
```
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
DataGridViewCell cell = row.Cells[2]; //Note specified column index
if (cell.Value == null || cell.Value.Equals(""))
{
continue;
}
GetQuestions(cell.Value.ToString());
}
``` | ```
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
DataGridViewCell cell = row.Cells["foo"];//Note specified column NAME
{
if (cell != null && (cell.Value != null || !cell.Value.Equals("")))
{
GetQuestions(cell.Value.ToString());
}
}
}
``` | Getting text only from a specific column of DataGridView | [
"",
"c#",
"datagridview",
"cell",
""
] |
I've got a code base with lots of this:
```
byte[] contents = FileUtils.FileToByteArray(FileOfGartantuanProportions);
```
I don't control my IIS server, so I can't see the system log or do instrumentation, I just get to see my request fail to return (white page of death) and sometimes YSOD with Out of Memory error.
Does anyone have a rule of thumb for what is the most data you can load up into memory before IIS5 or IIS6 will kill the work process or just keel over and die?
Or better yet, is there an API call I an make, something like:
```
if(!IsEnoughMemoryFor(FileOfGartantuanProportion.Length)) throw new SomeException() ;
```
On my XP Pro workstation I can get get an ASP.NET page to successfully deal with a very large byte array in memory, but these results obviously weren't applicable to a real shared server. | According to [Tess Ferrandez](http://blogs.msdn.com/tess/)'s talk at TechEd, you can start seeing Out Of Memory exceptions on a 32bit server when you have about 800MB in Private Bytes or 1.4GB in Virtual Bytes.
She also had a good post about why this is here:
> [A restaurant analogy](http://blogs.msdn.com/tess/archive/2006/09/06/net-memory-usage-a-restaurant-analogy.aspx)
Other points she made included thinking about what you're serialising into session - for example serialising a 1MB dataset can result in 15-20MB of memory used on the server every page as that data is serialised and de-serialised. | With IIS6 in native mode you can configure the limits for each Application Pool.
With IIS5 it's configured using the element in machine.config as a percentage of total system memory - default is 60%. | Rule of thumb for amount of usage memory it takes to make a worker process recycle? | [
"",
"c#",
".net",
"asp.net",
"worker-process",
""
] |
I'm trying to call SendMessage with an uint parameter from Java, but I can't convert int to uint. I can't change the uint parameter in SendMessage because it is a windows function. Is there some way of doing this?
Background:
I'm actually using Processing, and I'm following the following tutorials to access user32.dll: <http://processing.org/hacks/hacks:jnative>
and <http://jnative.free.fr/SPIP-v1-8-3/article.php3?id_article=8>
And I'm following this to call SendMessage
<http://www.codeproject.com/KB/cs/Monitor_management_guide.aspx>
Here's my code, GetActiveWindow works fine, it's from the second link above.
```
int SC_MONITORPOWER = 0xF170;
int WM_SYSCOMMAND = 0x0112;
int MONITOR_ON = -1;
int MONITOR_OFF = 2;
int MONITOR_STANDBY = 1;
HWND ValidHWND = org.xvolks.jnative.util.User32.GetActiveWindow();
org.xvolks.jnative.util.User32.SendMessage(ValidHWND, (UINT)WM_SYSCOMMAND,
(WPARAM)SC_MONITORPOWER, (LPARAM)MONITOR_STANDBY);
```
last line is where the error happens, it says the expected UINT in type User32 is not applicable to the LONG I provided. I can't modify SendMessage either
Here's the corresponding java file the call above invokes, the GetActiveWindow part works fine since it's from a tutorial. I'm trying to tailor Sendmessage to follow it, but I haven't figured it all out yet. However, I don't think it matters to the error I'm getting, since changing the parameters to SendMessage here doesn't change what the compiler expects. I've tried changing int Msg to uint Msg to long Msg, the compiler still expects uint from the code above.
```
public class Paul_s_User32 extends User32 {
public HANDLE GetActiveWindow() {
JNative GetActiveWindow = new JNative(DLL_NAME, "GetActiveWindow");
GetActiveWindow.setRetVal(Type.INT);
GetActiveWindow.invoke();
HWND handle = new HWND(GetActiveWindow.getRetValAsInt());
GetActiveWindow.dispose();
return handle;
}
public IntPtr SendMessage(IntPtr hWnd, int Msg,
IntPtr wParam, IntPtr lParam) {
JNative SendMessage = new JNative(DLL_NAME, "SendMessage");
//SendMessage.setRetVal(Type.long);
SendMessage.invoke();
SendMessage(ValidHWND, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_STANDBY);
}
``` | If you are using the org.xvolks.jnative package, all of the parameters (HWND, UINT, WPARAM, and LPARAM) are classes in org.xvolks.jnative.misc.basicStructures. So you should be able to do something like this (untested code):
```
import org.xvolks.jnative.misc.basicStructures.*;
...
User32.SendMessage(
new HWND(ValidHWND),
new UINT(WM_SYSCOMMAND),
new WPARAM(SC_MONITORPOWER),
new LPARAM(MONITOR_STANDBY);
```
For your reference, here's the implementation of SendMessage in org.xvolks.jnative.util.User32. As you can see, the jnative code does not care at all about signed and unsigned. You might find it useful to grab the [jnative source code](http://sourceforge.net/project/showfiles.php?group_id=156421&package_id=174535).
```
public static LRESULT SendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) throws NativeException, IllegalAccessException
{
JNative SendMessage = new JNative(DLL_NAME, "SendMessageA");
SendMessage.setRetVal(Type.INT);
int pos = 0;
SendMessage.setParameter(pos++, hWnd.getValue());
SendMessage.setParameter(pos++, Msg.getValue());
SendMessage.setParameter(pos++, wParam.getValue());
SendMessage.setParameter(pos++, lParam.getValue());
SendMessage.invoke();
pos = SendMessage.getRetValAsInt();
SendMessage.dispose();
return new LRESULT(pos);
}
```
And if you decide that you don't like JNative, you could take a look at [Java Native Access (JNA)](https://github.com/twall/jna/). | From a data perspective, a uint and an int are the same thing -- a 32 bit value. The only difference is how opcodes interpret the uppermost bit. When passing between Java and C, you're just passing 32 bits, so the sign is not relevant. The solution is to just declare the uint parameter as an int.
BTW, the issue of unsigned/signed is not significant here because the uMsg value for SendMessage is positive for all Microsoft messages, and for that matter, is more than likely positive for anything else you're likely to encounter. | How to pass uint in Java? | [
"",
"java",
"winapi",
"uint32",
""
] |
As a non-.NET programmer I'm looking for the .NET equivalent of the old Visual Basic function `left(string, length)`. It was lazy in that it worked for any length string. As expected, `left("foobar", 3) = "foo"` while, most helpfully, `left("f", 3) = "f"`.
In .NET `string.Substring(index, length)` throws exceptions for everything out of range. In Java I always had the Apache-Commons lang.StringUtils handy. In Google I don't get very far searching for string functions.
---
**@Noldorin** - Wow, thank you for your VB.NET extensions! My first encounter, although it took me several seconds to do the same in C#:
```
public static class Utils
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
}
```
Note the static class and method as well as the `this` keyword. Yes, they are as simple to invoke as `"foobar".Left(3)`. See also [C# extensions on MSDN](http://msdn.microsoft.com/en-us/library/bb383977.aspx). | Here's an extension method that will do the job.
```
<System.Runtime.CompilerServices.Extension()> _
Public Function Left(ByVal str As String, ByVal length As Integer) As String
Return str.Substring(0, Math.Min(str.Length, length))
End Function
```
This means you can use it just like the old VB `Left` function (i.e. `Left("foobar", 3)` ) or using the newer VB.NET syntax, i.e.
```
Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"
``` | Another one line option would be something like the following:
```
myString.Substring(0, Math.Min(length, myString.Length))
```
Where myString is the string you are trying to work with. | .NET equivalent of the old vb left(string, length) function | [
"",
"c#",
".net",
"vb.net",
""
] |
I have used `FindControl` in the past, prior to .NET 2.0/3.0. It seems like now, for some reason, the ID's of my controls get a funky named assigned. For example I assigned an id "cbSelect" to a checkbox, but FindControl does not find it. When I view the HTML it was assigned `ctl00_bodyPlaceHolder_ctl02_cbSelect`.
I have not found one example of FindControl that mentions that. In fact everyone seems to just use find control like normal.
So, am I doing something wrong? Did .Net change? Can anyone shed some light onto this for me, it is really frustrating! | You are probably using a MasterPage or user controls (ascx) and this is the reason the for client ids change. Imagine you have a control in the master page with the same id as one in the page. This would result in clashes. The id changes ensures all ClientID properties are unique on a page.
FindControl needs some special attention when working with MasterPages. Have a look at [ASP.NET 2.0 MasterPages and FindControl()](http://west-wind.com/weblog/posts/5127.aspx). The FindControl works inside a [naming container](http://www.asp.net/LEARN/master-pages/tutorial-05-vb.aspx). The MastePage and the page are different naming containers. | You could write extender to find any control on page using recursion.
This could be in some Util/Helper class.
```
public static Control FindAnyControl(this Page page, string controlId)
{
return FindControlRecursive(controlId, page.Form);
}
public static Control FindAnyControl(this UserControl control, string controlId)
{
return FindControlRecursive(controlId, control);
}
public static Control FindControlRecursive(string controlId, Control parent)
{
foreach (Control control in parent.Controls)
{
Control result = FindControlRecursive(controlId, control);
if (result != null)
{
return result;
}
}
return parent.FindControl(controlId);
}
``` | ASP.Net FindControl is not working - How come? | [
"",
"c#",
".net",
"asp.net",
"findcontrol",
""
] |
I know it sounds stupid but:
I've found [this](http://do.davebsd.com/) application written on Mono and it is open source.
While peeking at the source code I've found this two "using" directive that stoped me:
```
using Gdk;
using Mono.Unix;
```
I guess they're Mono specific libraries.
So, it is possible to run Mono under Windows? ( perhaps Visual Studio express edition ? )
I'm trying to learn C#
I see there is a Windows branch of the app, but it is empty.
BTW: Is it Mono thought for cross platform in first place?
**EDIT**
I've downloaded/installed and run the sample code
```
using Mono.Unix;
class X { static void Main () { System.Console.Write("OK");} }
```
And the answer to my own question is:
```
x.cs(1,12): error CS0234: The type or namespace name `Unix' does not exist
in the namespace `Mono'. Are you missing an assembly reference?
Compilation failed: 1 error(s), 0 warnings
```
No, it doesn't work :( | [Mono on windows guide](http://www.mono-project.com/Mono:Windows)
I am not sure you will be able to use code using the Mono.Unix namespace, but generally if you are creating cross platform code, you shouldn't have to.
[Gnome Do linux port](https://code.launchpad.net/~do-windows). For a learning project however, I might suggest starting with code that is actually cross platform, or develop on Linux for now. Tackling cross platform issues and possibly an incomplete port will just complicate the learning process.
So, I suppose in summary to your initial question. Yes, you can run Mono on Windows, but it is possible to write platform specific code, which the example application you have chosen has indeed done. The link I provided above is a port to make that code work on Windows. Without porting ( changing the platform specific code ), that program will not compile on windows. | Yes, you can install mono under windows. There is an experimental installer.
See: <http://mono-project.com/Mono:Windows>
That page also has information on the gtk libs. | Using Mono on Windows | [
"",
"c#",
"windows",
"mono",
""
] |
I'm implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to make sure that the value of this variable is copied when one of my objects is copied?
Using the old sets module, the following code worked perfectly:
```
import sets
class Fooset(sets.Set):
def __init__(self, s = []):
sets.Set.__init__(self, s)
if isinstance(s, Fooset):
self.foo = s.foo
else:
self.foo = 'default'
f = Fooset([1,2,4])
f.foo = 'bar'
assert( (f | f).foo == 'bar')
```
but this does not work using the built-in set module.
The only solution that I can see is to override every single method that returns a copied set object... in which case I might as well not bother subclassing the set object. Surely there is a standard way to do this?
(To clarify, the following code does *not* work (the assertion fails):
```
class Fooset(set):
def __init__(self, s = []):
set.__init__(self, s)
if isinstance(s, Fooset):
self.foo = s.foo
else:
self.foo = 'default'
f = Fooset([1,2,4])
f.foo = 'bar'
assert( (f | f).foo == 'bar')
```
) | My favorite way to wrap methods of a built-in collection:
```
class Fooset(set):
def __init__(self, s=(), foo=None):
super(Fooset,self).__init__(s)
if foo is None and hasattr(s, 'foo'):
foo = s.foo
self.foo = foo
@classmethod
def _wrap_methods(cls, names):
def wrap_method_closure(name):
def inner(self, *args):
result = getattr(super(cls, self), name)(*args)
if isinstance(result, set) and not hasattr(result, 'foo'):
result = cls(result, foo=self.foo)
return result
inner.fn_name = name
setattr(cls, name, inner)
for name in names:
wrap_method_closure(name)
Fooset._wrap_methods(['__ror__', 'difference_update', '__isub__',
'symmetric_difference', '__rsub__', '__and__', '__rand__', 'intersection',
'difference', '__iand__', 'union', '__ixor__',
'symmetric_difference_update', '__or__', 'copy', '__rxor__',
'intersection_update', '__xor__', '__ior__', '__sub__',
])
```
Essentially the same thing you're doing in your own answer, but with fewer loc. It's also easy to put in a metaclass if you want to do the same thing with lists and dicts as well. | I think that the recommended way to do this is not to subclass directly from the built-in `set`, but rather to make use of the [Abstract Base Class `Set`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Set) available in [collections.abc](https://docs.python.org/3/library/collections.abc.html).
Using the ABC Set gives you some methods for free as a mix-in so you can have a minimal Set class by defining only `__contains__()`, `__len__()` and `__iter__()`. If you want some of the nicer set methods like `intersection()` and `difference()`, you probably do have to wrap them.
Here's my attempt (this one happens to be a frozenset-like, but you can inherit from `MutableSet` to get a mutable version):
```
from collections.abc import Set, Hashable
class CustomSet(Set, Hashable):
"""An example of a custom frozenset-like object using
Abstract Base Classes.
"""
__hash__ = Set._hash
wrapped_methods = ('difference',
'intersection',
'symetric_difference',
'union',
'copy')
def __repr__(self):
return "CustomSet({0})".format(list(self._set))
def __new__(cls, iterable=None):
selfobj = super(CustomSet, cls).__new__(CustomSet)
selfobj._set = frozenset() if iterable is None else frozenset(iterable)
for method_name in cls.wrapped_methods:
setattr(selfobj, method_name, cls._wrap_method(method_name, selfobj))
return selfobj
@classmethod
def _wrap_method(cls, method_name, obj):
def method(*args, **kwargs):
result = getattr(obj._set, method_name)(*args, **kwargs)
return CustomSet(result)
return method
def __getattr__(self, attr):
"""Make sure that we get things like issuperset() that aren't provided
by the mix-in, but don't need to return a new set."""
return getattr(self._set, attr)
def __contains__(self, item):
return item in self._set
def __len__(self):
return len(self._set)
def __iter__(self):
return iter(self._set)
``` | What is the correct (or best) way to subclass the Python set class, adding a new instance variable? | [
"",
"python",
"subclass",
"set",
"instance-variables",
""
] |
I am looking for a built-in extension method like Apply:
```
collection.Apply (predicate)
```
which will apply a method on all items contained in the collection.
I am asking first so that I don't write something that already exists.
EDIT: The reason I didn't use foreach was because I want to express the method using LINQ. | Well, there's `List<T>.ForEach`, but nothing on `IEnumerable<T>`. It's the kind of thing that's in plenty of 3rd party "extra extension methods" toolkits though :)
I'd agree with the other answers that `foreach` is usually a better way to go - although it could occasionally make the difference between:
```
DoSomething(x => x.Where(...).Select(...).ForEach(...));
```
and
```
DoSomething(x => {
foreach (var y in x.Where(...).Select(...)) {
(...)
}
});
```
which is more significant than just a single line.
I think I'd *usually* only use such a method if I already had a delegate to hand, or potentially a method group. For example, it's quite nice to be able to have a one-liner to dump a filtered collection:
```
people.Where(p => p.Age >= 18).ForEach(Console.WriteLine);
```
It's possible that after more exposure to functional programming I'd use it more often though. | I'm pretty sure there isn't one for `IEnumerable<T>`, `ICollection<T>`, or `IList<T>`.
The `List<T>` class, however, has a generic [`ForEach`](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx) method (built-in, not extension), which you can use as such:
```
list.ForEach(delegate);
```
Personally, I don't any real value to such methods. A simple foreach loop uses a single line more and offers the same usability, but there's nothing stopping you from writing one yourself of course. | Is there a built-in extension methods on collections like Apply? | [
"",
"c#",
".net",
""
] |
I'm using [XStream](http://xstream.codehaus.org/json-tutorial.html) and JETTISON's Stax JSON serializer to send/receive messages to/from JSON javascripts clients and Java web applications.
I want to be able to create a list of objects to send to the server and be properly marshalled into Java but the format that XStream and JSON expect it in is very non-intuitive and requires our javascript libraries to jump through hoops.
[EDIT Update issues using [GSON](http://code.google.com/p/google-gson/) library]
I attempted to use the [GSON library](http://code.google.com/p/google-gson/) but it cannot deserialize concrete objects when I only have it expect generic super classes (XStream and Jettison handles this because type information is baked into the serialization).
[GSON FAQ states Collection Limitation](https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Limitations):
> Collections Limitations
>
> Can serialize collection of arbitrary objects but can not deserialize from it
>
> Because there is no way for the user to indicate the type of the resulting object
>
> While deserializing, Collection must be of a specific generic type
Maybe I'm using bad java practices but how would I go about building a JSON to Java messaging framework that sent/received various concrete Message objects in JSON format?
For example this fails:
```
public static void main(String[] args) {
Gson gson = new Gson();
MockMessage mock1 = new MockMessage();
MockMessage mock2 = new MockMessage();
MockMessageOther mock3 = new MockMessageOther();
List<MockMessage> messages = new ArrayList<MockMessage>();
messages.add(mock1);
messages.add(mock2);
messages.add(mock3);
String jsonString = gson.toJson(messages);
//JSON list format is non-intuitive single element array with class name fields
System.out.println(jsonString);
List gsonJSONUnmarshalledMessages = (List)gson.fromJson(jsonString, List.class);
//This will print 3 messages unmarshalled
System.out.println("XStream format JSON Number of messages unmarshalled: " + gsonJSONUnmarshalledMessages.size());
}
[{"val":1},{"val":1},{"otherVal":1,"val":1}]
Exception in thread "main" com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@638bd7f1 failed to deserialized json object [{"val":1},{"val":1},{"otherVal":1,"val":1}] given the type interface java.util.List
```
Here's an example, I want to send a list of 3 Message objects, 2 are of the same type and the 3rd is a different type.
```
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
class MockMessage {
int val = 1;
}
class MockMessageOther {
int otherVal = 1;
}
public class TestJSONXStream {
public static void main(String[] args) {
JettisonMappedXmlDriver xmlDriver = new JettisonMappedXmlDriver();
XStream xstream = new XStream(xmlDriver);
MockMessage mock1 = new MockMessage();
MockMessage mock2 = new MockMessage();
MockMessageOther mock3 = new MockMessageOther();
List messages = new ArrayList();
messages.add(mock1);
messages.add(mock2);
messages.add(mock3);
String jsonString = xstream.toXML(messages);
//JSON list format is non-intuitive single element array with class name fields
System.out.println(jsonString);
List xstreamJSONUnmarshalledMessages = (List)xstream.fromXML(jsonString);
//This will print 3 messages unmarshalled
System.out.println("XStream format JSON Number of messages unmarshalled: " + xstreamJSONUnmarshalledMessages.size());
//Attempt to deserialize a reasonable looking JSON string
String jsonTest =
"{"+
"\"list\" : ["+
"{"+
"\"MockMessage\" : {"+
"\"val\" : 1"+
"}"+
"}, {"+
"\"MockMessage\" : {"+
"\"val\" : 1"+
"}"+
"}, {"+
"\"MockMessageOther\" : {"+
"\"otherVal\" : 1"+
"}"+
"} ]"+
"};";
List unmarshalledMessages = (List)xstream.fromXML(jsonTest);
//We expect 3 messages but XStream only deserializes one
System.out.println("Normal format JSON Number of messages unmarshalled: " + unmarshalledMessages.size());
}
}
```
Intuitively I expect the XStream JSON to be serialized (and able to deserialize correctly) from the following format:
```
{
"list" : [
{
"MockMessage" : {
"val" : 1
}
}, {
"MockMessage" : {
"val" : 1
}
}, {
"MockMessageOther" : {
"otherVal" : 1
}
} ]
}
```
Instead XStream creates a single element list with fields that are named the classnames and nested arrays of Objects of the same type.
```
{
"list" : [ {
"MockMessage" : [ {
"val" : 1
}, {
"val" : 1
} ],
"MockMessageOther" : {
"otherVal" : 1
}
} ]
}
```
The trouble may be caused by it using the XStream XML [CollectionConverter](http://xstream.codehaus.org/converters.html)?
Does anyone have a suggestion for a good JSON Java object serialization that allows you to read/write arbitrary Java objects. I looked at the [Jackson Java JSON Processor](http://jackson.codehaus.org/) but when you were reading in objects from a stream you had to specify what type of object it was unlike XStream where it will read in any object (because the serialized XStream JSON contains class name information). | I agree with other poster in that XStream is not a good fit -- it's an OXM (Object/Xml Mapper), and JSON is handled as a secondary output format using XML processing path. This is why a "convention" (of how to convert hierarchich xml model into object-graph model of json and vice versa) is needed; and your choice boils down to using whatever is least intrusive of sub-optimal choices.
That works ok if XML is your primary data format, and you just need some rudimentary JSON(-like) support.
To get good JSON-support, I would consider using a JSON processing library that does real OJM mapping (I assume Svenson does too, but additionally), such as:
* [Jackson](http://jackson.codehaus.org/Tutorial)
* [Google-gson](http://code.google.com/p/google-gson/)
Also: even if you do need to support both XML and JSON, you are IMO better off using separate libraries for these tasks -- objects (beans) to use on server-side need not be different, just serialization libs that convert to/from xml and json. | I realize this is off-topic, but I'd like to present a solution in [svenson JSON](http://code.google.com/p/svenson/).
Do you really need public fields in your domain classes? Apart from having to use properties, svenson can handle cases like this with a more simple JSON output with a discriminator property
```
class Message
{
// .. your properties with getters and setters ..
// special property "type" acts a signal for conversion
}
class MessageOther
{
...
}
List list = new ArrayList();
list.add(new Message());
list.add(new MessageOther());
list.add(new Message());
String jsonDataSet = JSON.defaultJSON().forValue(list);
```
would output JSON like
```
[
{"type":"message", ... },
{"type":"message_other", ... },
{"type":"message", ... }
]
```
which could be parsed again with code like this
```
// configure reusable parse instance
JSONParser parser = new JSONParser();
// type mapper to map to your types
PropertyValueBasedTypeMapper mapper = new PropertyValueBasedTypeMapper();
mapper.setParsePathInfo("[]");
mapper.addFieldValueMapping("message", Message.class);
mapper.addFieldValueMapping("message_other", MessageOther.class);
parser.setTypeMapper(mapper);
List list = parser.parse(List.class, jsonDataset);
``` | In XStream is there a better way to marshall/unmarshall List<Object>'s in JSON and Java | [
"",
"java",
"ajax",
"json",
"serialization",
"xstream",
""
] |
I assume I have to do this via a DataSet, but it doesn't like my syntax.
I have an XMLDocument called "XmlDocument xmlAPDP".
I want it in a DataTable called "DataTable dtAPDP".
I also have a DataSet called "DataSet dsAPDP".
-
if I do DataSet dsAPDP.ReadXML(xmlAPDP) it doesn't like that because ReadXML wants a string, I assume a filename? | No hacks required:
```
xmlAPDP = new XmlDocument()
...
xmlReader = new XmlNodeReader(xmlAPDP)
dataSet = new DataSet()
...
dataSet.ReadXml(xmlReader)
```
XmlDocument is an XmlNode, and XmlNodeReader is a XmlReader, which ReadXml accepts. | ASP.net example:
```
private DataTable GetReportDataTable()
{
//get mapped path to xml document
string xmlDocString = Server.MapPath("CustomReports.xml");
//read into dataset
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlDocString);
//return single table inside of dataset
return dataSet.Tables[0];
}
``` | C# XMLDocument to DataTable? | [
"",
"c#",
".net",
"datatable",
"dataset",
"xmldocument",
""
] |
What exactly makes the JVM (in particular, Sun's implementation) slow to get running compared to other runtimes like CPython? My impression was that it mainly has to do with a boatload of libraries getting loaded whether they're needed or not, but that seems like something that shouldn't take 10 years to fix.
Come to think of it, how does the JVM start time compare to the CLR on Windows? How about Mono's CLR?
UPDATE: I'm particularly concerned with the use case of small utilities chained together as is common in Unix. Is Java now suitable for this style? Whatever startup overhead Java incurs, does it add up for every Java process, or does the overhead only really manifest for the first process? | Here is [what Wikipedia has to say on the issue](http://en.wikipedia.org/wiki/Java_performance#Startup_time) (with some references).
It appears that most of the time is taken just loading data (classes) from disk (i.e. startup time is I/O bound). | Just to note some solutions:
There are two mechanisms that allow to faster startup JVM.
The first one, is the class data sharing mechanism, that is supported since Java 6 Update 21 (only with the HotSpot Client VM, and only with the serial garbage collector as far as I know)
To activate it you need to set **-Xshare** (on some implementations: **-Xshareclasses** ) JVM options.
To read more about the feature you may visit:
[Class data sharing](http://publib.boulder.ibm.com/infocenter/java7sdk/v7r0/topic/com.ibm.java.aix.70.doc/diag/understanding/shared_classes.html)
The second mechanism is a Java Quick Starter. It allows to preload classes during OS startup, see:
[Java Quick Starter](http://www.java.com/en/download/help/quickstarter.xml) for more details. | Why is the JVM slow to start? | [
"",
"java",
"jvm",
"performance",
"startup",
""
] |
I'm making a script that goes through a table that contains all the other table names on the database. As it parses each row, it checks to see if the table is empty by
```
select count(*) cnt from $table_name
```
Some tables don't exist in the schema anymore and if I do that
```
select count(*)
```
directly into the command prompt, it returns the error:
> 206: The specified table (adm\_rpt\_rec) is not in the database.
When I run it from inside Perl, it appends this to the beginning:
> DBD::Informix::db prepare failed: SQL: -
How can I avoid the program quitting when it tries to prepare this SQL statement? | Working code - assuming you have a 'stores' database.
```
#!/bin/perl -w
use strict;
use DBI;
my $dbh = DBI->connect('dbi:Informix:stores','','',
{RaiseError=>0,PrintError=>1}) or die;
$dbh->do("create temp table tlist(tname varchar(128) not null) with no log");
$dbh->do("insert into tlist values('systables')");
$dbh->do("insert into tlist values('syzygy')");
my $sth = $dbh->prepare("select tname from tlist");
$sth->execute;
while (my($tabname) = $sth->fetchrow_array)
{
my $sql = "select count(*) cnt from $tabname";
my $st2 = $dbh->prepare($sql);
if ($st2)
{
$st2->execute;
if (my($num) = $st2->fetchrow_array)
{
print "$tabname: $num\n";
}
else
{
print "$tabname: error - missing?\n";
}
}
}
$sth->finish;
$dbh->disconnect;
print "Done - finished under control.\n";
```
Output from running the code above.
```
systables: 72
DBD::Informix::db prepare failed: SQL: -206: The specified table (syzygy) is not in the database.
ISAM: -111: ISAM error: no record found. at xx.pl line 14.
Done - finished under control.
```
This printed the error (`PrintError=>1`), but continued. Change the 1 to 0 and no error appears. The parentheses in the declarations of `$tabname` and `$num` are crucial - array context vs scalar context. | One option is not to use RaiseError => 1 when constructing $dbh. The other is to wrap the prepare in an eval block. | How can I avoid the program quitting when Perl's DBI encounters an error preparing a statement? | [
"",
"sql",
"perl",
"informix",
"dbi",
""
] |
I am trying to use JAXB's introspection to marshall and unmashall some existing domain objects marked up with JAXB annotations. Most things work as expected, but I am having quite a bit of trouble getting a fairly simple class to serialize. This class is used as an @XmlElement on a number of beans and looks something like:
```
public class Range<E extends Comparable<E>> implements Serializable {
protected boolean startInclusive, endInclusive;
protected E start, end;
public Range(){
startInclusive = endInclusive = true;
}
public boolean contains(E value){...}
public E getEnd() {
return end;
}
public void setEnd(E end) {
this.end = end;
}
public boolean isEndInclusive() {
return endInclusive;
}
public void setEndInclusive(boolean endInclusive) {
this.endInclusive = endInclusive;
}
public E getStart() {
return start;
}
public void setStart(E start) {
this.start = start;
}
public boolean isStartInclusive() {
return startInclusive;
}
public void setStartInclusive(boolean startInclusive) {
this.startInclusive = startInclusive;
}
}
```
I have tried to do the following, with no success, JAXB is still angry with the interface Comparable.
```
public class DoubleRange extends Range<Double> {}
```
Using both Range and DoubleRange as return types for the bean getter's yields an exception like:
```
java.lang.Comparable is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at java.lang.Comparable
at protected java.lang.Comparable com.controlpath.util.Range.start
at example.util.Range
at example.util.DoubleRange
at public example.util.DoubleRange example.domain.SomeBean.getRange()
at example.domain.SomeBean
```
I realize that in most cases List<T> and Map<T, U> only work because the JAXB specification has special provisions for those types when they are encountered on beans, but is there any way to convey what I want to the JAXB introspection engine without having to reimplement range with non-generic fields? | You could write a custom adapter (not using JAXB's XmlAdapter) by doing the following:
1) declare a class which accepts all kinds of elements and has JAXB annotations
and handles them as you wish (in my example I convert everything to String)
```
@YourJAXBAnnotationsGoHere
public class MyAdapter{
@XmlElement // or @XmlAttribute if you wish
private String content;
public MyAdapter(Object input){
if(input instanceof String){
content = (String)input;
}else if(input instanceof YourFavoriteClass){
content = ((YourFavoriteClass)input).convertSomehowToString();
}else if(input instanceof .....){
content = ((.....)input).convertSomehowToString();
// and so on
}else{
content = input.toString();
}
}
}
// I would suggest to use a Map<Class<?>,IMyObjToStringConverter> ...
// to avoid nasty if-else-instanceof things
```
2) use this class instead of E in your to-be-marshalled class
**NOTES**
* Of course this would **not** work for complex (nested) data structures.
* You have to think how to unmarshall this back again, could be more tricky. If
it's too tricky, wait for a better proposal than mine ;) | How about
```
public class Range<**E extends Number**> implements Serializable { ...
```
* Number is a **class**
* I bet JAXB knows **default** marshalling/unmarshalling rules for Number
For unmarshalling to specific type, you need XmlAdapter as I
described here: [JAXB inheritance, unmarshal to subclass of marshaled class](https://stackoverflow.com/questions/619761/jaxb-inheritance-unmarshal-to-subclass-of-marshaled-class/636597#636597) | JAXB Marshalling and Generics | [
"",
"java",
"generics",
"jaxb",
""
] |
I'm looking for a `cat` for aac music files (the stuff iTunes uses).
Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.
I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.
I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net... | I created a freeware program called "Chapter and Verse" to concatenate m4a (AAC) files into a single m4b audiobook file with chapter marks and metadata.
If you have already ripped the CD's to AAC using itunes (which you say you have) then the rest is easy with my software. I wrote it for this exact reason and scenario. You can download it from [www.lodensoftware.com](http://lodensoftware.com/)
After trying to work with SlideShow Assembler, the QT SDK and a bunch of other command line tools, I ended up building my own application based on the publicly available MP4v2 library. The concatenating of files and adding of chapters is done using the MP4v2 library.
There are quite a few nuances in building an audiobook properly formatted for the iPod. The information is hard to find. Working with Apple documentation and open libraries has its own challenges as well.
Best of Luck. | Not programming related (well, kinda.)
iTunes already has functionality to rip as a single track (e.g. an audiobook.) Check this out: <http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html>
That fixes your immediate problem, but I guess people can keep discussing how to do it programatically. | How to programatically combine two aac files into one? | [
"",
"python",
"windows",
"scripting",
"itunes",
"aac",
""
] |
Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires?
For example, theoretical usage:
```
$ magic_tool <EOF
with something:
pass
EOF
1: 'with' statement requires Python 2.6 or greater
$ magic_tool <EOF
class Something:
@classmethod
def blah(cls):
pass
EOF
2: classmethod requires Python 2.2 or greater
$ magic_tool <EOF
print """Test
"""
EOF
1: Triple-quote requires Python 1.5 of later
```
Is such a thing possible? I suppose the simplest way would be to have all Python versions on disc, run the script with each one and see what errors occur.. | The tool pyqver from Greg Hewgill wasn't updated since a while.
[vermin](https://pypi.org/project/vermin/) is a similar utility which shows in the verbose mode (`-vvv`) what lines are considered in the decision.
```
% pip install vermin
% vermin -vvv somescript.py
Detecting python files..
Analyzing using 8 processes..
!2, 3.6 /path/to/somescript.py
L13: f-strings require 3.6+
L14: f-strings require 3.6+
L15: f-strings require 3.6+
L16: f-strings require 3.6+
print(expr) requires 2+ or 3+
Minimum required versions: 3.6
Incompatible versions: 2
```
Bonus: With the parameter `-t=V` you can define a target version `V` you want to be compatible with. If this version requirement is not met, the script will exit with an exit code `1`, making it easy integratable into a test suite. | Inspired by this excellent question, I recently put together a script that tries to do this. You can find it on github at [pyqver](http://github.com/ghewgill/pyqver/tree/master).
It's reasonably complete but there are some aspects that are not yet handled (as mentioned in the README file). Feel free to fork and improve it! | Tool to determine what lowest version of Python required? | [
"",
"python",
"code-analysis",
""
] |
I'm trying to send emails from a system that connects to internet through a http proxy which is set in Internet Options.
i'm using SmtpClient.
Is there any way to send mails with SmtpClient through this proxy setting.
Thanks | I understand that you want to use the browsers default settings, i would also like an answer for that.
Meanwhile, you could do it manually.
```
MailAddress from = new MailAddress("from@mailserver.com");
MailAddress to = new MailAddress("to@mailserver.com");
MailMessage mm = new MailMessage(from, to);
mm.Subject = "Subject"
mm.Body = "Body";
SmtpClient client = new SmtpClient("proxy.mailserver.com", 8080);
client.Credentials = new System.Net.NetworkCredential("from@mailserver.com", "password");
client.Send(mm);
``` | Http Proxies control http traffic, they rarely have anything to do with SMTP at all. I've never heard of proxying SMTP before after all SMTP itself is intrinsically supports a chain of "proxies" to the destination SMTP server. | Sending mail through http proxy | [
"",
"c#",
"proxy",
"smtpclient",
"http-proxy",
""
] |
We have a query that runs off a fairly large table that unfortunately needs to use LIKE '%ABC%' on a couple varchar fields so the user can search on partial names, etc. SQL Server 2005
Would adding an index on these varchar fields help any in terms of select query performance when using LIKE or does it basically ignore the indexes and do a full scan in those cases?
Any other possible ways to improve performance when using LIKE? | Only if you add full-text searching to those columns, and use the full-text query capabilities of SQL Server.
Otherwise, no, an index will not help. | You can potentially see performance improvements by adding index(es), it depends a lot on the specifics :)
How much of the total size of the row are your predicated columns? How many rows do you expect to match? Do you need to return all rows that match the predicate, or just top 1 or top n rows?
If you are searching for values with high selectivity/uniqueness (so few rows to return), and the predicated columns are a smallish portion of the entire row size, an index could be quite useful. It will still be a scan, but your index will fit more rows per page than the source table.
Here is an example where the total row size is much greater than the column size to search across:
```
create table t1 (v1 varchar(100), b1 varbinary(8000))
go
--add 10k rows of filler
insert t1 values ('abc123def', cast(replicate('a', 8000) as varbinary(8000)))
go 10000
--add 1 row to find
insert t1 values ('abc456def', cast(replicate('a', 8000) as varbinary(8000)))
go
set statistics io on
go
select * from t1 where v1 like '%456%'
--shows 10001 logical reads
--create index that only contains the column(s) to search across
create index t1i1 on t1(v1)
go
select * from t1 where v1 like '%456%'
--or can force to
--shows 37 logical reads
```
If you look at the actual execution plan you can see the engine scanned the index and did a bookmark lookup on the matching row. Or you can tell the optimizer directly to use the index, if it hadn't decide to use this plan on its own:
select \* from t1 with (index(t1i1)) where v1 like '%456%'
If you have a bunch of columns to search across only a few that are highly selective, you could create multiple indexes and use a reduction approach. E.g. first determine a set of IDs (or whatever your PK is) from your highly selective index, then search your less selective columns with a filter against that small set of PKs.
If you always need to return a large set of rows you would almost certainly be better off with a table scan.
So the possible optimizations depend a lot on the specifics of your table definition and the selectivity of your data.
HTH!
-Adrian | SQL Server Index - Any improvement for LIKE queries? | [
"",
"sql",
"sql-server",
"select",
"query-optimization",
""
] |
I was able to find the solution for this in c# / .net but not for regular web html. If there's already an answer let me know and i'll close question.
How to create a text box that only will allow certain characters (ex. alphanumeric) based on a given regex (ex. [a-zA-Z0-9])? So if a user tries to enter anything else, paste included, it is removed or not allowed.
```
<input type="text" class="alphanumericOnly">
``` | The basic function would be this:
```
string = string.replace(/[^a-zA-Z0-9]/g, '')
```
This would replace any character that is not described by `[a-zA-Z0-9]`.
Now you could either put it directly into your element declaration:
```
<input type="text" class="alphanumericOnly" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')">
```
Or (as you used the class hint) you assign this behavior to every `input` element with the class `alphanumericOnly`:
```
var inputElems = document.getElemenstByTagName("input");
for (var i=0; i<inputElems.length; i++) {
var elem = inputElems[i];
if (elem.nodeName == "INPUT" && /(?:^|\s+)alphanumericOnly(?:\s+|$)/.test(elem.className) {
elem.onkeyup = function() {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
}
}
```
But it’s probably easier to do that with [jQuery](http://jquery.com/) or another JavaScript framework:
```
$("input.alphanumericOnly").bind("keyup", function(e) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
``` | 1. Example on how to allow alphanumeric chars and space (a-z, A-Z, 0-9 and space, others are eliminated as typed):
```
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-zA-Z0-9 ]/g)){this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');}});
```
2. Example on how to allow only lowercase alpha chars (a-z, others are eliminated as typed):
```
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-z]/g)){this.value = this.value.replace(/[^a-z]/g, '');}});
```
Etc...
**EDIT:**
As of jQuery version 3.0, `.bind()` and `.unbind()` are deprecated. Instead, if you use jQuery 3.0 (and above), simply use `.on()` and `.off()` event handler attachments, respectively. | Javascript Regex Only Textbox | [
"",
"javascript",
"regex",
"textbox",
""
] |
For custom rendering, I've created a class that extends JPanel and overrides the paintComponent method. In the custom paintComponent I rendering multiple shape objects held in a array. What I would like to add is the ability to drag and select 1 or more of the shapes. While dragging I would like to show a translucent rectangle defining the selection region akin to what is seen in Windows Explorer. Can any provide a starting point for accomplishing this?
Thanks. | All,
Thanks for the suggestions. Ended up resolving this by adapting some the code used in this rather clever demo. <http://forums.sun.com/thread.jspa?threadID=5299064&start=19>
```
public class ExamplePanel extends JPanel
{
Rectangle2D.Double selectionRect;
Point mouseDown, mouseHere;
...
protected void paintComponent(Graphics g)
{
AlphaComposite ta = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(ta);
g2d.setColor(Color.BLUE);
g2d.fill(selectionRect);
g2d.setComposite(AlphaComposite.SrcOver);
g2d.setColor(Color.BLACK);
g2d.draw(selectionRect);
}
}
public class ExammpleMouseListener extends MouseAdapter
{
@Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
// store the mouse down location
pnl.mouseDown = e.getPoint();
}
/**
* @see java.awt.event.MouseAdapter#mouseDragged(java.awt.event.MouseEvent)
*/
@Override
public void mouseDragged(MouseEvent e)
{
super.mouseDragged(e);
// check for left mouse button
if ((e.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) == 0)
{
return;
}
// store the current location
pnl.mouseHere = e.getPoint();
// calculate the size of the selection rectangle
double downX = pnl.mouseDown.getX();
double downY = pnl.mouseDown.getY();
double hereX = pnl.mouseHere.getX();
double hereY = pnl.mouseHere.getY();
double l = Math.min(downX, hereX);
double t = Math.min(downY, hereY);
double w = Math.abs(downX - hereX);
double h = Math.abs(downY - hereY);
pnl.selectionRect = new Rectangle2D.Double(l, t, w, h);
// queue a repaint of the panel
pnl.repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
// clear the selection rectangle
pnl.selectionRect = null;
// queue a repaint of the panel
pnl.repaint();
}
}
}
``` | I saw an interesting way of doing this in JFreeChart's source code. You can draw a marquee over a section of the chart, and when you release the mouse the chart zooms in on the selected are. Re-rending the chart is expensive and unfortunately JFreeChart doesn't support partial paints of a chart. So to draw the marquee they do some sort of bitwise operation to the colors of the component, in a reversible fashion. Every time the mouse moves while selecting a marquee, you reverse the previous bitwise operation on the old coordinates, then redo it on the new coordinates.
Take a look at ChartPanel.java in JFreeChart
```
private void drawZoomRectangle(Graphics2D g2) {
// Set XOR mode to draw the zoom rectangle
g2.setXORMode(Color.gray);
if (this.zoomRectangle != null) {
if (this.fillZoomRectangle) {
g2.fill(this.zoomRectangle);
}
else {
g2.draw(this.zoomRectangle);
}
}
// Reset to the default 'overwrite' mode
g2.setPaintMode();
}
``` | Java Translucent Selection Box | [
"",
"java",
""
] |
I'm new to Drupal 6.10 CMS and PHP too. I'm creating my website with drupal and I have found a module called [Webform](http://drupal.org/project/webform) I like it, it's pretty easy to create forms with different types of fields and file uploading. The one thing that i can't figure out is how to add Rich Text before all fields. Something like introduction to the form. This module has "Description" field that will show text as a plain text but it doesn't have rich text in it.
What can I use to make that happen. Is it possible to hardcode html there or is there any other modules that can allow to do something like that?
Thanks | the value of the "Description" field is passed through [\_webform\_filter\_descriptions()](http://cvs.drupal.org/viewvc.py/drupal/contributions/modules/webform/webform.module?annotate=1.124.2.95#l2170). this function has a `$strict` parameter, defaulting to `TRUE`, which determines if the description is filtered through [filter\_xss()](http://api.drupal.org/api/function/filter_xss/6) or not. `filter_xss()` allows some html:
> 'a', 'em', 'strong', 'cite', 'code',
> 'ul', 'ol', 'li', 'dl', 'dt', 'dd'
so you can either restrict your "rich text" html to these elements, or modify \_webform\_filter\_descriptions(), setting `$strict` to `FALSE`. if you do latter, be aware of the security implications (users with rights to create webform descriptions could enter malicious html - that's what filter\_xss() protects against). | I think all you need to do is set the 'input format' to 'full html' and then you can use whatever HTML/CSS tags you want to style the text. | Customize WebForm module in Drupal | [
"",
"php",
"content-management-system",
"drupal-6",
"module",
"richtext",
""
] |
I have a query returning a column of floating point numbers but I am only interested in the number before the decimal place. I don't want to round the number so I am looking for something like:
```
1.95 = 1
1.45678 = 1
12.00 = 12
12.9999 = 12
```
Is there an easy way to achieve this in SqlServer other than doing a substring? | You can use the [floor function](http://msdn.microsoft.com/en-us/library/ms178531.aspx). | You can do this -
```
SELECT CAST(1.230 AS INT)
```
Output: 1 | Left side of a floating point number in Sql Server | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
A [question that I answered](https://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python) got me wondering:
How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?
I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). [Laurence Gonsalves](https://stackoverflow.com/users/90848/laurence-gonsalves) raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA.
So, to reiterate: what are the implementation details and guarantees of Python regular expressions?
It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the [question that I referenced before](https://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python). | Python's re module was based on [PCRE](http://en.wikipedia.org/wiki/PCRE), but has moved on to their own implementation.
Here is the link to the [C code](http://hg.python.org/cpython/file/a82fc1f366b4/Modules/_sre.c).
It appears as though the library is based on recursive backtracking when an incorrect path has been taken.

Regular expression and text size n
a?nan matching an
Keep in mind that this graph is not representative of normal regex searches.
<http://swtch.com/~rsc/regexp/regexp1.html> | There are no "efficiency guarantees" on Python REs any more than on any other part of the language (C++'s standard library is the only widespread language standard I know that tries to establish such standards -- but there are no standards, even in C++, specifying that, say, multiplying two ints must take constant time, or anything like that); nor is there any guarantee that big optimizations won't be applied at any time.
Today, F. Lundh (originally responsible for implementing Python's current RE module, etc), presenting Unladen Swallow at Pycon Italia, mentioned that one of the avenues they'll be exploring is to compile regular expressions directly to LLVM intermediate code (rather than their own bytecode flavor to be interpreted by an ad-hoc runtime) -- since ordinary Python code is also getting compiled to LLVM (in a soon-forthcoming release of Unladen Swallow), a RE and its surrounding Python code could then be optimized together, even in quite aggressive ways sometimes. I doubt anything like that will be anywhere close to "production-ready" very soon, though;-). | Regular expression implementation details | [
"",
"python",
"regex",
""
] |
When inserting a guid as a primary key does the db server go through every single row to make sure there's no duplicate or does it just assume that a duplicate is not possible or very unlikely?
with int the db server can simply increment the key but not the case with GUIDs | That's the databases responsibility once you tell it that a column is a primary key.
It's nothing that you have to be concerned with at this point, let the database worry about this for you.
Also, since this is a primary key it's going to be indexed. So your preformance concern about going though each row (or a table scan) would not really occur at this level. The database would use the index file to ensure that only a unique value could be inserted. | All primary keys are unique. So the server is responsible for verifying no two rows ever have the same primary key. This is true if the primary key is int, varchar, guid, whatever. *How* the uniqueness constraint is verified is implementation-defined. Basically, don't let it concern you unless you've shown it to be a performance barrier.
Always profile before worrying excessively about performance. | Does sql server check for duplicate GUID on insertion? | [
"",
"sql",
"sql-server",
"guid",
""
] |
I have a stored procedure that executes much faster from Sql Server Management Studio (2 seconds) than when run with `System.Data.SqlClient.SqlCommand` (times out after 2 minutes).
What could be the reason for this?
---
Details:
In Sql Server Management Studio this runs in 2 seconds (on production database):
```
EXEC sp_Stat
@DepartmentID = NULL
```
In .NET/C# the following times out after 2 minutes (on production database):
```
string selectCommand = @"
EXEC sp_Stat
@DepartmentID = NULL";
string connectionString = "server=***;database=***;user id=***;pwd=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(selectCommand, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
}
}
}
}
```
I also tried with `selectCommand = "sp_Stat"`, `CommandType = StoredProcedure`, and an `SqlParameter`, but it's the same result.
And without `EXEC` it's the same result as well.
On an almost data-empty development database both cases finishes in less than 1 second. So it's related to that there's a lot of data in the database, but it seems to only happen from .NET...
---
What Marc Gravell wrote about different `SET` values makes the difference in the presented case.
SQL Server Profiler showed that Sql Server Management Studio runs the following `SET`'s that .NET Sql Client Data Provider does not:
```
SET ROWCOUNT 0
SET TEXTSIZE 2147483647
SET NOCOUNT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ARITHABORT ON
SET LOCK_TIMEOUT -1
SET QUERY_GOVERNOR_COST_LIMIT 0
SET DEADLOCK_PRIORITY NORMAL
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SET ANSI_NULLS ON
SET ANSI_NULL_DFLT_ON ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET CURSOR_CLOSE_ON_COMMIT OFF
SET IMPLICIT_TRANSACTIONS OFF
SET QUOTED_IDENTIFIER ON
SET NOEXEC, PARSEONLY, FMTONLY OFF
```
When I included these, the same query took the same amount of time in SSMS and .NET.
And the responsible `SET` is ...
```
SET ARITHABORT ON
```
What have I learnt? Maybe to use a profiler instead of guessing...
(The solution at first seemed to be related to parameter sniffing. But I had mixed some things up...) | Another thing that can be important is [the `SET` options](http://msdn.microsoft.com/en-us/library/ms190356.aspx) that are enabled. Some of these options change the query plan sufficiently to change the profile. Some can have a huge impact if you are looking at (for example) a calculated + persisted (and possibly indexed) column: if the `SET` options aren't compatible, it can be forced to re-calculate the values, rather than using the indexed value - which can change an index seek into a table scan + calculation.
Try using the profiler to see what `SET` options are "in play", and see if using those options changes things.
Another impact is the connection string; for example, if you enable MARS that can change the behaviour in subtle ways.
Finally, transactions (implicit (`TransactionScope`) or explicit) can have a *huge* impact, depending on the isolation level. | This is almost certainly due to an 'incorrect' cached query plan. This has come up on SO quite a few times.
Do you have up-to-date statistics? A regular scheduled index maintenance plan?
You can test if it is definitely due to the cached query plan by adding this to your stored procedure definition:
```
CREATE PROCEDURE usp_MyProcedure WITH RECOMPILE...
```
This will re-index an entire database (caution if database is very large!):
```
exec sp_msforeachtable "dbcc dbreindex('?')"
```
SO posts:
[Big difference in execution time of stored proc between Managment Studio and TableAdapter.](https://stackoverflow.com/questions/452467/big-difference-in-execution-time-of-stored-proc-between-managment-studio-and-tabl)
[Parameter Sniffing (or Spoofing) in SQL Server](https://stackoverflow.com/questions/211355/parameter-sniffing-or-spoofing-in-sql-server)
[optimize for unknown for SQL Server 2005?](https://stackoverflow.com/questions/650914/optimize-for-unknown-for-sql-server-2005)
[Different Execution Plan for the same Stored Procedure](https://stackoverflow.com/questions/505995/different-execution-plan-for-the-same-stored-procedure) | Why is some sql query much slower when used with SqlCommand? | [
"",
".net",
"sql",
"sqlcommand",
""
] |
I have a job that runs every night to pull xml files from a directory that has over 20,000 subfolders under the root. Here is what the structure looks like:
```
rootFolder/someFolder/someSubFolder/xml/myFile.xml
rootFolder/someFolder/someSubFolder1/xml/myFile1.xml
rootFolder/someFolder/someSubFolderN/xml/myFile2.xml
rootFolder/someFolder1
rootFolder/someFolderN
```
So looking at the above, the structure is always the same - a root folder, then two subfolders, then an xml directory, and then the xml file.
Only the name of the rootFolder and the xml directory are known to me.
The code below traverses through all the directories and is extremely slow. Any recommendations on how I can optimize the search especially if the directory structure is known?
```
string[] files = Directory.GetFiles(@"\\somenetworkpath\rootFolder", "*.xml", SearchOption.AllDirectories);
``` | Rather than doing GetFiles and doing a brute force search you could most likely use GetDirectories, first to get a list of the "First sub folder", loop through those directories, then repeat the process for the sub folder, looping through them, lastly look for the xml folder, and finally searching for .xml files.
Now, as for performance the speed of this will vary, but searching for directories first, THEN getting to files should help a lot!
**Update**
Ok, I did a quick bit of testing and you can actually optimize it much further than I thought.
The following code snippet will search a directory structure and find ALL "xml" folders inside the entire directory tree.
```
string startPath = @"C:\Testing\Testing\bin\Debug";
string[] oDirectories = Directory.GetDirectories(startPath, "xml", SearchOption.AllDirectories);
Console.WriteLine(oDirectories.Length.ToString());
foreach (string oCurrent in oDirectories)
Console.WriteLine(oCurrent);
Console.ReadLine();
```
If you drop that into a test console app you will see it output the results.
Now, once you have this, just look in each of the found directories for you .xml files. | I created a recursive method `GetFolders` using a `Parallel.ForEach` to find all the folders named as the variable `yourKeyword`
```
List<string> returnFolders = new List<string>();
object locker = new object();
Parallel.ForEach(subFolders, subFolder =>
{
if (subFolder.ToUpper().EndsWith(yourKeyword))
{
lock (locker)
{
returnFolders.Add(subFolder);
}
}
else
{
lock (locker)
{
returnFolders.AddRange(GetFolders(Directory.GetDirectories(subFolder)));
}
}
});
return returnFolders;
``` | Quickest way in C# to find a file in a directory with over 20,000 files | [
"",
"c#",
".net",
"file-io",
""
] |
Do you know some neat Java libaries that allow you to make cartesian product of two (or more) sets?
For example: I have three sets. One with objects of class Person, second with objects of class Gift and third with objects of class GiftExtension.
I want to generate one set containing all possible triples Person-Gift-GiftExtension.
The number of sets might vary so I cannot do this in nested foreach loop.
Under some conditions my application needs to make a product of Person-Gift pair, sometimes it is triple Person-Gift-GiftExtension, sometimes there might even be sets Person-Gift-GiftExtension-GiftSecondExtension-GiftThirdExtension, etc. | ***Edit:*** Previous solutions for two sets removed. See edit history for details.
Here is a way to do it recursively for an arbitrary number of sets:
```
public static Set<Set<Object>> cartesianProduct(Set<?>... sets) {
if (sets.length < 2)
throw new IllegalArgumentException(
"Can't have a product of fewer than two sets (got " +
sets.length + ")");
return _cartesianProduct(0, sets);
}
private static Set<Set<Object>> _cartesianProduct(int index, Set<?>... sets) {
Set<Set<Object>> ret = new HashSet<Set<Object>>();
if (index == sets.length) {
ret.add(new HashSet<Object>());
} else {
for (Object obj : sets[index]) {
for (Set<Object> set : _cartesianProduct(index+1, sets)) {
set.add(obj);
ret.add(set);
}
}
}
return ret;
}
```
Note that it is impossible to keep any generic type information with the returned sets. If you knew in advance how many sets you wanted to take the product of, you could define a generic tuple to hold that many elements (for instance `Triple<A, B, C>`), but there is no way to have an arbitrary number of generic parameters in Java. | This is a pretty old question, but why not use [Guava's cartesianProduct](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Sets.html#cartesianProduct-java.util.List-)? | Cartesian product of an arbitrary number of sets | [
"",
"java",
"set",
"cartesian-product",
""
] |
I have a datagridview that i bind from an sql table, in that dv i have those attributes: Id, Name and Price. When i set the SortMode of the Name Columns to Automatic and i click on the header of this column i can sort this dv based on the first letter of the Name, this way i can order products based on their first letters ( Acumulator, Boat, CocaCola, Engine etc).
Is there a way this thing to happen without clicking the header of the column Name. I am looking some code that will do this job when the form will load. | There's a method on the DataGridView called "Sort":
```
this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);
```
This will programmatically sort your datagridview. | ```
dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);
``` | Sort dataGridView columns in C# ? (Windows Form) | [
"",
"c#",
"winforms",
"datagridview",
"sorting",
"grid",
""
] |
```
int qempty()
{
return (f == r ? 1 : 0);
}
```
In the above snippet, what does "?" mean? What can we replace it with? | This is commonly referred to as the [**conditional operator**](http://en.wikipedia.org/wiki/%3F:), and when used like this:
```
condition ? result_if_true : result_if_false
```
... if the `condition` evaluates to `true`, the expression evaluates to `result_if_true`, otherwise it evaluates to `result_if_false`.
It is [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar), and in this case, it can be replaced with
```
int qempty()
{
if(f == r)
{
return 1;
}
else
{
return 0;
}
}
```
**Note:** Some people refer to `?:` it as "**the ternary operator**", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using. | This is a ternary operator, it's basically an inline if statement
```
x ? y : z
```
works like
```
if(x) y else z
```
except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.
It's useful for writing succinct code, but can be overused to create hard to maintain code. | What does the question mark character ('?') mean in C++? | [
"",
"c++",
"operators",
"conditional-operator",
""
] |
I have seen something like the following a couple times... and I hate it. Is this basically 'cheating' the language? Or.. would you consider this to be 'ok' because the IsNullOrEmpty is evaluated first, all the time?
(We could argue whether or not a string should be NULL when it comes out of a function, but that isn't really the question.)
```
string someString;
someString = MagicFunction();
if (!string.IsNullOrEmpty(someString) && someString.Length > 3)
{
// normal string, do whatever
}
else
{
// On a NULL string, it drops to here, because first evaluation of IsNullOrEmpty fails
// However, the Length function, if used by itself, would throw an exception.
}
```
**EDIT:**
Thanks again to everyone for reminding me of this language fundamental. While I knew "why" it worked, I can't believe I didn't know/remember the name of the concept.
(In case anyone wants any background.. I came upon this while troubleshooting exceptions generated by NULL strings and .Length > x exceptions... in different places of the code. So when I saw the above code, in addition to everything else, my frustration took over from there.) | You're taking advantage of a language feature known as short circuiting. This is not cheating the language but in fact using a feature exactly how it was designed to be used. | If you are asking if its ok to depend on the "short circuit" relational operators `&&` and `||`, then yes thats totally fine. | I don't like this... Is this cheating the language? | [
"",
"c#",
"syntax",
"short-circuiting",
""
] |
I know from [this question](https://stackoverflow.com/questions/302294/cookies-in-firefox) that Firefox 3.0 and up stores its cookies in an SQLite database. My question is: can you access this database from other **desktop** programs in such a way that you could add a cookie?
I realize this has security implications. However, I do not want to read them at all. I want to be able to set one cookie if possible. I don't even want to overwrite a cookie. I just want to add it if it isn't there already. This is sort of a personal project I'm working on for fun.
This question is mostly language agnostic. I would prefer a solution in C#, but proof of concept in any language will suffice.
Extra credit: It would be cool to set the same cookie in Internet Explorer, too | For FF3, you can access the cookies.sqlite file with [any SQLite wrapper](http://www.google.com/search?client=opera&rls=en&q=c%23+sqlite&sourceid=opera&ie=utf-8&oe=utf-8) - however, check whether FF is running - it may be write-locking the file (not tested).
The database contains this:
```
TABLE moz_cookies (
id INTEGER PRIMARY KEY,
name TEXT,
value TEXT,
host TEXT,
path TEXT,
expiry INTEGER,
lastAccessed INTEGER,
isSecure INTEGER,
isHttpOnly INTEGER
)
```
Not sure about the primary key, it looks like it is a unix timestamp of when the cookie was created; expiry and lastAccessed are also unix timestamps, the rest is self-explanatory.
Try an `INSERT INTO moz_cookies` and see if FF becomes immediately aware of the new cookie or if it requires a restart. | I know this question is really old, but I had the same problem and never really found a complete sample of code (though the answers on this page pointed me in the right direction). HTH!
```
public static void ClearFirefoxCookies()
{
int procCount = Process.GetProcessesByName("firefox").Length;
if (procCount > 0)
throw new ApplicationException(string.Format("There are {0} instances of Firefox still running", procCount));
try
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + GetFirefoxCookiesFileName()))
{
conn.Open();
SQLiteCommand command = conn.CreateCommand();
command.CommandText = "delete from moz_cookies";
int count = command.ExecuteNonQuery();
}
}
catch (SQLiteException ex)
{
if (!(ex.ErrorCode == SQLiteErrorCode.Busy || ex.ErrorCode == SQLiteErrorCode.Locked))
throw new ApplicationException("The Firefox cookies.sqlite file is locked");
}
}
private static string GetFirefoxCookiesFileName()
{
string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), @"Mozilla\Firefox\Profiles");
if (!System.IO.Directory.Exists(path))
throw new ApplicationException("Firefox profiles folder not found");
string[] fileNames = System.IO.Directory.GetFiles(path, "cookies.sqlite", System.IO.SearchOption.AllDirectories);
if (fileNames.Length != 1 || !System.IO.File.Exists(fileNames[0]))
throw new ApplicationException("Firefox cookies.sqlite file not found");
return fileNames[0];
}
``` | Programmatically set browser cookie (Firefox) | [
"",
"c#",
"internet-explorer",
"firefox",
"sqlite",
"cookies",
""
] |
I am trying to figure out what APIs to use to connect and record from a webcam. In al of my research, Google, I have found many OLD articles which discus Directshow and COM. I don't want to write code that is using an obsolete API.
Any direction with this is greatly appreciated. | DiectShow is still the best way to connect to Webcams (or other sources).
You can use [DirectShow.NET](http://directshownet.sourceforge.net/) which is a thin warpper arund DirectShow. | avicap32.dll I guess is the safest option due to its readily availability... <http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C> has the PInvoke code you will be needing.
<http://codeplex.com/touchless> is an interesting related project! | Using c# .NET 3.0 on a Windows XP machine, what is the most efficent way to record from multiple webcams? | [
"",
"c#",
"c#-3.0",
"windows-xp",
"directshow",
"webcam",
""
] |
How do I sort ArrayList of DateTime objects in descending order?
Thank you. | First of all, unless you are stuck with using framework 1.1, you should not be using an `ArrayList` at all. You should use a strongly typed generic `List<DateTime>` instead.
For custom sorting there is an overload of the `Sort` method that takes a comparer. By reversing the regular comparison you get a sort in descending order:
```
list.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });
```
### Update:
With lambda expressions in C# 3, the delegate is easier to create:
```
list.Sort((x, y) => y.CompareTo(x));
``` | As "Guffa" already said, you shouldn't be using `ArrayList` unless you are in .NET 1.1; here's a simpler `List<DateTime>` example, though:
```
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
```
Your dates are now sorted in descending order. | How to sort ArrayList of DateTime objects in descending order? | [
"",
"c#",
""
] |
I always set the modifiers on my form to **private**,I don't like internal nor public.
Till now I used to Invoke like this:
```
public string Addtext
{
if(InvokeRequired)
{
Invoke((MethodInvoker)delegate
{
textbox.text = value;
});
}
else
textbox.text = value;
}
```
But adding such property for every member on my form is just not Object Orientated at all.
I want to create a function that will Invoke the parameter(action).I tried my best,but I failed - it requires the form members to be **public** or **internal** :(
```
public void PerformActionOnForm(Action<FormMain> action)
{
var form = Form.ActiveForm as FormMain;
object s = action.Clone();
if (form != null)
{
form.PerformAction(action);
}
}
public void PerformAction(Action<FormMain> action)
{
if (InvokeRequired)
Invoke(action, this);
else
action(this);
}
```
two problems in my code:
It requires the property I'd like to change to be != private :(
Doesn't work if the form is not on focus. | In what way is adding properties for data that needs to be accessed or set outside of the scope of the form "not object oriented at all?" This is really your only option. Code in an anonymous delegate (or any delegate, for that matter) executes in the context in which it was declared. The only facility for getting around visibility issues is reflection, and that is **big smelly code smell**. Create your properties and use them as appropriate.
As for your second option, I'm assuming that you want to execute this on your "main form". You have two options here: assume that there is only one instance and keep that as a static property on the class, assigning it in the instance constructor.
```
public partial class MainForm : Form
{
private static MainForm singletonInstance;
public static MainForm SingletonInstance
{
get { return singletonInstance; }
}
public MainForm() : base()
{
InitializeComponent();
singletonInstance = this;
}
}
public void PerformActionOnForm(Action<FormMain> action)
{
var form = MainForm.SingletonInstance;
// object s = action.Clone(); What was this for?
if (form != null)
{
form.PerformAction(action);
}
}
```
The other only works if all of your forms are properly "owned" and the only form with no owner is your main form. In that instance you could do this:
```
public void PerformActionOnForm(Action<FormMain> action)
{
var form = Form.ActiveForm.TopLevelControl as FormMain;
// object s = action.Clone(); What was this for?
if (form != null)
{
form.PerformAction(action);
}
}
``` | ## Calling a UI component from a non-UI thread
Assuming you only have one message loop (99% that's the case), then:
```
public static class SynchronizedInvoker
{
public static void Invoke(Action action)
{
Form form = Application.OpenForms.Cast<Form>().FirstOrDefault();
if (form != null && form.InvokeRequired)
form.Invoke(action);
else
action();
}
}
```
Calling the code:
```
SynchronizedInvoker.Invoke(() => myForm.Text = myText);
```
## Accessing private UI components
Accessing private UI members is not different from accessing other private members to .NET objects. It's in the nature of a private member not to be accessed from other objects. If you still want access, you'll eitherway have to pass the reference of the UI component to the caller or use reflection to resolve the path to the private object.
An example of passing the reference of the UI component to the caller:
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(delegate { MyWorker.Run(button1); });
}
}
class MyWorker
{
public static void Run(Button button)
{
SynchronizedInvoker.Invoke(() => button.Text = "running");
Thread.Sleep(5000); // do some important work here
SynchronizedInvoker.Invoke(() => button.Text = "finished");
}
}
```
Using reflection is technically possible, but not ideal. You need to know the path to the private member, and that requires information about the internals of an object. You should then question yourself why you've made it private in the first place. | How to invoke with action? | [
"",
"c#",
"winforms",
"invoke",
""
] |
I'm trying to calculate the number of days between two days, but I'm running into issues with Daylight Savings Time. Here's my code:
```
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date) - strtotime($old_date);
return $offset/60/60/24;
}
```
Works fine as long as the days are both within the same DST period:
```
echo date_diff('3/15/09', '3/18/09'); // 3
```
But not if they're further apart:
```
echo date_diff('11/15/08', '3/18/09'); // 122.95833333333
```
I want an even number of days, and don't care about DST. I suppose I could round the result, but that feels kludgy. Is there a better (easy) way? I don't want to have to write a whole day-parsing-and-counting-avoiding-leap-years thing if I can avoid it.
(Note: this has to run under php 5.1.6, so some of the date features in 5.3 may not be available.)
A bit more info: I'm going to take the offset and add it to other datetimes that are in a db, and I want only the day part to change, not the time part. Turns out rounding won't work, anyway, because when I do the adding it gets off by one hour in the other direction. Maybe there's a better approach to the whole problem.... | you could use <https://www.php.net/date_default_timezone_set> to set the timezone to GMT so there will be no offset.
Alternately, you can manually add an offset using the `date('I',$timetamp)`
```
if ( date("I") == 1 ) { // "WE ARE MDT";
$timeZone = "MDT";
} else {
$timeZone = "MST";
}
``` | Force the dates to live into a timezone without Daylight Savings Time, GMT/UTC:
```
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date . " UTC") - strtotime($old_date . " UTC");
return $offset/60/60/24;
}
echo date_diff('3/15/09', '3/18/09'); // 3
echo date_diff('11/15/08', '3/18/09'); // 123
``` | How to subtract two dates, ignoring daylight savings time in PHP? | [
"",
"php",
"datetime",
"dst",
""
] |
Is there any speed difference between
```
if (isset($_POST['var']))
```
or
```
if ($_POST['var'])
```
And which is better or are they the same? | It is a good practice to use `isset` for the following reasons:
* If `$_POST['var']` is an empty string or `"0"`, `isset` will still detect that the variable exists.
* Not using isset will generate a notice. | They aren't the same. Consider a notional array:
```
$arr = array(
'a' => false,
'b' => 0,
'c' => '',
'd' => array(),
'e' => null,
'f' => 0.0,
);
```
Assuming `$x` is one of those keys ('a' to 'f') and the key 'g' which isn't there it works like this:
* `$arr[$x]` is `false` for all keys a to g;
* `isset($arr[$x])` is `true` for keys a, b, c, d and f but `false` for e and g; and
* `array_key_exists($x, $arr)` is `true` for all keys a to f, `false` for g.
I suggest you look at [PHP's type juggling](http://au.php.net/language.types.type-juggling), specifically conversion to booleans.
Lastly, what you're doing is called [micro-optimization](http://www.codinghorror.com/blog/archives/000185.html). Never choose which one of those by whichever is perceived to be faster. Whichever is faster is so negligible in difference that it should **never** be a factor even if you could reliably determine which is faster (which I'm not sure you could to any statistically significant level). | What's better, isset or not? | [
"",
"php",
"isset",
""
] |
Is there any way to query the name of the current method if you've obfuscated your code? I'm asking because there are times when I want to log a message with the executing method as a prefix. | Just add the method name directly to the string you are outputting. If you get the name of the current method via reflection, it will be the obfuscated name. If it was not this way, anybody would be able to figure out the original method, defeating the obfuscation (or dramatically hampering it). | Alternatively, obfuscation tools are supposed to be able to output their own obfuscation logs so you can write a tool to translate your application's obfuscated logs into something human-readable.
Of course, once you get there, development versions of your application could include the ability to access their own obfuscation logs and translate the result of reflection before they output logs.
You can have obfuscation logs on the file system, as an application resource in the jar file or download them from a remote server.
If you only keep decrypted obfuscation logs in your application memory, the VM sandbox is supposed to keep them fairly safe. | Real runtime method names despite obfuscation? | [
"",
"java",
"runtime",
"obfuscation",
""
] |
Is there any way to set the initial directory of a folder browser dialog to a non-special folder? This is what I'm currently using
```
fdbLocation.RootFolder = Environment.SpecialFolder.Desktop;
```
but I want to use a path I have stored in a string something like this
```
fdbLocation.RootFolder = myFolder;
```
This causes an error "Cannot convert 'string' to 'System.Environment.SpecialFolder'". | Just set the `SelectedPath` property before calling `ShowDialog`.
```
fdbLocation.SelectedPath = myFolder;
``` | Set the `SelectedPath` property before you call `ShowDialog` ...
```
folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();
```
Will start them at `C:\Temp` | Set folder browser dialog start location | [
"",
"c#",
""
] |
I've been developing in java then I stopped, so now since I have my google app engine account I wanted to start with this again. Also, I love web and I know struts is a good MVC framework.
I've been reading [this](http://www.roseindia.net/struts/). Do you think struts can help me to start or should I start with "plain" servlets, and then go to some framework? | I would at least learn the basic servlet lifecycle and API.
As Joel puts it [abstractions are leaky](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) and this applies to frameworks--all frameworks not just Web ones--equally well. You will be much better equipped to use a framework, to know why it's good and how it can help you if you understand the underlying technology, the thing it is trying to abstract.
As for Struts, I would steer clear of STruts 1. It's rather ancient now. There's still a lot of code around for it but I wouldn't consider it best practice now, particularly for its (over)use of inheritance. Struts 2 is really a completely different framework based on Webwork.
There are plenty of other MVC frameworks out there. Personally I like Spring MVC as being quite "pure" and lightweight. | I'd definitely start with an MVC framework as opposed to "plain" servlets as you suggest.
While I've used Struts 1.x a lot, I think for a new application you should look at Struts 2, Spring MVC or some other newer framework that leverage new Java features such as annotations. | is struts a good starting point for java web | [
"",
"java",
"google-app-engine",
"jakarta-ee",
"struts",
""
] |
What is the best way (or are the various ways) to pretty print XML in Python? | ```
import xml.dom.minidom
dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
``` | lxml is recent, updated, and includes a pretty print function
```
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
```
Check out the lxml tutorial:
<https://lxml.de/tutorial.html> | Pretty printing XML in Python | [
"",
"python",
"xml",
"pretty-print",
""
] |
I'm trying to create a notepad/wordpad clone. I want to save it in .rtf format so that it can be read by wordpad. How do I save a do this in C#? | Assuming you are trying to do this yourself for learning purposes, you don't want to use a library to do it for you:
Basically you need to write a program which holds in memory either a string with RTF markup, or a DOM-like data tree. Using the [RTF specification](http://msdn.microsoft.com/en-us/library/aa140277.aspx), you should write a flat (text) file marked up properly and with a .rtf extension. Just the same as if you were writing an HTML file. | Correct me if I'm wrong, but if you're using the RichTextBox control, you can just use the RichTextBox.SaveFile method to accomplush this. Just a guess though that you mean doing it without using that control. | What's the best way to save a RichTextFile in C#? | [
"",
"c#",
"richtextbox",
"richtext",
"notepad",
"wordpad",
""
] |
I need to get an image's dimensions in javascript (jQuery) when no styles are specified for it (jQuery's css() returns 0).
Maybe it is because I'm loading the image with jQuery just before asking for its dimensions. If this is the case, is there any event to listen that tells when the image has been loaded? | Maybe the image has not fully loaded therefore the dimensions can not be given.But without your code I can't tell what you're doing wrong, but here is an **Example** that would work:
```
function LoadImage(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
}
else {
window.setTimeout('iLoad(imgsrc)', 1000);
}
}
<body onLoad='LoadImage(imgsrc)'>
``` | here's a link that helps, look at the demo: <http://docs.jquery.com/Events/load>
with jquery there is a load() event that's fired when an image is done loading ie:
```
<script type="text/javascript">
$(document).ready(function()
{
$('#theImage').load(function()
{
// do the stuff here.
});
});
</script>
<img src="blah.jpg" id="theImage" />
``` | Get image width and height | [
"",
"javascript",
"jquery",
""
] |
I was wondering if there's a simple way to cancel an AJAX request?
Beyond just calling an 'abort' on the XMLHTTPRequest on the client side, is there a way to easily stop the server process? The server is using Apache.
Thanks | No. There's definitely no simple way.
I can think of some complex ways, but they would be unreliable.
You'll probably have more luck developing a process for *reversing* the changes from a request you've just run (I'm assuming that's the reason you would want to stop it.) | Initiate another Ajax request. I found this thread by trying to figure out how to prevent a previous request from being interrupted when another is called. | How to cancel ajax request that has run (on server side) | [
"",
"php",
"ajax",
"request-cancelling",
""
] |
in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):
* user.cash is decreased
* user.contracts is increased by the number
* contracts.current\_price is updated.
* market.no\_of\_transactions is increased by 1.
in a rdms, these would be placed within the same transaction. I conceive that google datastore does not allow entities of more than one model to be in the same transaction.
what is the correct approach to this issue? how can I ensure that if a write fails, all preceding writes are rolled back?
edit: I have obviously missed entity groups. Now I'd appreciate some further information regarding how they are used. Another point to clarify is google says "Only use entity groups when they are needed for transactions. For other relationships between entities, use ReferenceProperty properties and Key values, which can be used in queries". does it mean I have to define both a reference property (since I need queriying them) and a parent-child relationship (for transactions)?
edit 2: and finally, how do I define two parents for an entity if the entity is being created to establish an n-to-n relationship between 2 parents? | After a through research, I have found that a distributed transaction layer that provides a solution to the single entity group restriction has been developed in userland with the help of some google people. But so far, it is not released and is only available in java. | Let me add a quote from the [Datastore documentation](http://code.google.com/intl/de/appengine/docs/python/datastore/keysandentitygroups.html):
> A good rule of thumb for entity groups is that they should be about
> the size of a single user's worth of
> data or smaller.
You could create a pseudo root entity and put everything below this. Then, you execute everything in a transaction. | datastore transaction restrictions | [
"",
"python",
"google-app-engine",
"transactions",
"google-cloud-datastore",
""
] |
I need a regular expression that I can use in VBScript and .NET that will return only the numbers that are found in a string.
For Example any of the following "strings" should return only **1231231234**
* 123 123 1234
* (123) 123-1234
* 123-123-1234
* (123)123-1234
* 123.123.1234
* 123 123 1234
* 1 2 3 1 2 3 1 2 3 4
This will be used in an email parser to find telephone numbers that customers may provide in the email and do a database search.
I may have missed a similar regex but I did search on regexlib.com.
[EDIT] - Added code generated by [RegexBuddy](http://www.regexbuddy.com/) after setting up musicfreak's answer
**VBScript Code**
```
Dim myRegExp, ResultString
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "[^\d]"
ResultString = myRegExp.Replace(SubjectString, "")
```
**VB.NET**
```
Dim ResultString As String
Try
Dim RegexObj As New Regex("[^\d]")
ResultString = RegexObj.Replace(SubjectString, "")
Catch ex As ArgumentException
'Syntax error in the regular expression
End Try
```
**C#**
```
string resultString = null;
try {
Regex regexObj = new Regex(@"[^\d]");
resultString = regexObj.Replace(subjectString, "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
``` | I don't know if VBScript has some kind of a "regular expression replace" function, but if it does, then you could do something like this pseudocode:
```
reg_replace(/\D+/g, '', your_string)
```
I don't know VBScript so I can't give you the exact code but this would remove anything that is not a number.
EDIT: Make sure to have the global flag (the "g" at the end of the regexp), otherwise it will only match the first non-number in your string. | In .NET, you could extract just the digits from the string. Using Linq like this:
```
string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
```
Don't forget to include `using System.Linq` | return only Digits 0-9 from a String | [
"",
"c#",
"vb.net",
"regex",
"vbscript",
"code-generation",
""
] |
C# 2008 SP1
I am using the code to detect if a proxy has been set under "Internet Options". If there is a proxy then I will set this in my webclient.
So I am just checking if the address of the proxy exists. If there is not, then there is no proxy to set in the webclient.
Is this the correct way to do this:
Many thanks for any advice,
```
WebProxy proxy = WebProxy.GetDefaultProxy();
if (proxy.Address.ToString() != string.Empty)
{
Console.WriteLine("Proxy URL: " + proxy.Address.ToString());
wc.Proxy = proxy;
}
```
====== Code edit ======
```
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
private extern static bool InternetGetConnectedState(ref InternetConnectionState_e lpdwFlags, int dwReserved);
[Flags]
enum InternetConnectionState_e : int
{
INTERNET_CONNECTION_MODEM = 0x1,
INTERNET_CONNECTION_LAN = 0x2,
INTERNET_CONNECTION_PROXY = 0x4,
INTERNET_RAS_INSTALLED = 0x10,
INTERNET_CONNECTION_OFFLINE = 0x20,
INTERNET_CONNECTION_CONFIGURED = 0x40
}
// Return true or false if connecting through a proxy server
public bool connectingThroughProxy()
{
InternetConnectionState_e flags = 0;
InternetGetConnectedState(ref flags, 0);
bool hasProxy = false;
if ((flags & InternetConnectionState_e.INTERNET_CONNECTION_PROXY) != 0)
{
hasProxy = true;
}
else
{
hasProxy = false;
}
return hasProxy;
}
``` | It appears that [WebRequest.DefaultWebProxy](http://msdn.microsoft.com/en-us/library/system.net.webrequest.defaultwebproxy.aspx) is the [official replacement](http://www.west-wind.com/weblog/posts/2005/Jul/11/Replacing-deprecated-SystemNetWebProxyGetDefaultProxy-in-NET-20) for WebProxy.GetDefaultProxy.
You should be able to drop that in to your original code with only a little modification. Something like:
```
WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy;
if (proxy.Address.AbsoluteUri != string.Empty)
{
Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);
wc.Proxy = proxy;
}
``` | First, [GetDefaultProxy](http://msdn.microsoft.com/en-us/library/system.net.webproxy.getdefaultproxy.aspx) is marked as deprecated so you have no guarantee it will be around in even the immediate future. Second, [Address](http://msdn.microsoft.com/en-us/library/system.net.webproxy.address.aspx) can be null so the code you gave risks a NullReferenceException: | C# auto detect proxy settings | [
"",
"c#",
"networking",
"proxy",
""
] |
I've got a file organizer application I'm working on. The files are regularly 500MB to 2GB. Everything works fine, but it is extremely annoying that the application "Stops Responding." What I'd like to do is a byte by byte or meg by meg copy with some Application.DoEvents() in there after each read/write action. Something along these lines, I don't know what the actual classes to use would be so I'm just going to make some stuff up :)
```
private void CopyFile(string inFilename, string outFilename)
{
FileReader inReader(inFilename);
FileWriter outWriter(outFilename, FileMode.OpenOrCreate);
byte theByte;
while (theByte = inReader.ReadByte())
{
outWriter.WriteByte(theByte, WriteMode.Append);
UpdateProgressBar();
Application.DoEvents();
}
inReader.CloseFile();
outWriter.CloseFile();
}
```
I know this seems like it should be a simple thing to do but I for the life of me can't seem to find any kind of example for doing this without using direct API calls or whatever. I've got to be missing something here so if anyone could get me on the right track here I'd really appreciate it.
Thanks in advance! | You should use a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) on your form to do the copying. It will allow the file copies to be done on a separate thread and let your UI be responsive. There is some added complexity, but the BackgroundWorker takes care of a lot of the plumbing for you. But, there are plenty of [examples](http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/a285bdb9-6838-48f3-b8ed-1bf0156f8c51) of [what you want to do](http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx). | You need to use a **BackgroundWorkerThread** to accomplish this. Here's a very good example of how to do that: [Copy File Using Background Worker Threads](http://blogs.microsoft.co.il/blogs/gillyb/archive/2008/08/05/ui-multithreading-for-beginners-using-backgroundworker.aspx) | Forms application "Not Responding" when copying large files? | [
"",
"c#",
"winforms",
"file",
"progress-bar",
"copying",
""
] |
Lets say there is an array like this:
```
double [] numbers = new double[] {1,1,2,2,5,7,7,7};
```
I want to copy only the different numbers to a new array (the result should be numbers = {1,2,5,7}) in a time efficient way. I know how to do it in a time inefficient way - by looking if the next number is the same as the one before and continuing the copy loop if they are. Is there another way? | If you don't have Linq, you can do the following:
```
List<double> uniques = new List<double>;
foreach (double num in numbers)
{
if (!uniques.Contains(num)) uniques.Add(num);
}
double[] uniquearray = uniques.ToArray();
``` | ```
using System.Linq;
double[] newArray = numbers.Distinct().ToArray();
``` | How to copy all different elements from an array in c# | [
"",
"c#",
"arrays",
""
] |
I have a small web application.
This is what I want to do: Create partial classes to split up a code behind file.
Why am I not able to create partial classes directly?
If this is the codebehind file:
```
using System;
using System.Configuration....
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
}
```
And also create this class:
```
public partial class _Default
{
public void Test()
{
}
}
```
I get an error message, Test doesn't exists in current context.
Why is this?
I get everything to work if I create a couple of partial classes which inherits from System.Web.UI.Page and then inherit my codebehind file from this class (the result of the partial classes). Is this the only way?
Has is something to do with that the codebehind and the aspx-page is dynamically compiled into a class?
Would appreciate if anyone could answer my problem. Things are working out right now but I would prefer to create the partial classes at the same "level" as the codebehind and avoid to use inheritance.
Thank you /John
(note that I have underscore in front of both classes but only one is visible in the preview, I don't know why..) | 1) Put your partial classes in the app\_code directory (I've never tried this)
2) Convert your application into a Web Application Project from a Website Project
A WAP is more like a dll or winforms project, which is compiled before runtime (although the ui can be updatable) and puts classes in namespaces. Website projects are compiled using the aspnet\_compiler which operates differently (e.g., dynamically named assemblies) than the standard compiler. | Okey. Well it wasn't a namespace problem but thanks for that suggestion.
Everything worked fine when I created a web application instead of a website, thank you very much.
By default when I start new projects I always select create new website, I have never had any problem with this before.
So of course I'll have to ask what is the difference except the one mentioned above?
Will there be any drawbacks with always going with web application projects instead of website projects?
Thank you /John | Create partial classes in Asp.Net | [
"",
"c#",
"asp.net",
"partial-classes",
""
] |
Let's say I've got a form for editing the properties of a Pony, and in my web application there are multiple places where you can choose to edit a Pony. For instance, in a list of Ponies there might be an "edit" link next to each Pony, and when the user is viewing a Pony, there might also be an "edit" link in that view.
When a user clicks "submit" after editing a Pony, I would like to return the user to the page that he or she was when clicking the "edit" link.
How do I write my controller to redirect the user back to where they started? Certainly I can do this by passing a parameter to the controller, but that seems a little goofy. Am I thinking about this all wrong or is that pretty much what I'll have to do? | One option, of course, would be to open the edit form in a new window, so all the user has to do is close it and they're back where they were.
There are a few places in my current application where I need to do something complicated, then pass the user to a form, and then have them return to the starting point. In those cases I store the starting point in the session before passing them off. That's probably overkill for what you're doing.
Other options: 1) you can store the "Referer" header and use that, but that may not be dependable; not all browsers set that header. 2) you could have javascript on the confirmation page after the form submission that calls "`history.go(-2)`". | Here's how to do it boys (Note this is RESTful Spring 3 MVC syntax but it will work in older Spring controllers):
```
@RequestMapping(value = "/rate", method = RequestMethod.POST)
public String rateHandler(HttpServletRequest request) {
//your controller code
String referer = request.getHeader("Referer");
return "redirect:"+ referer;
}
``` | Spring-MVC controller redirect to "previous" page? | [
"",
"java",
"spring-mvc",
""
] |
We have a folder where our app will be potentially reading, writing and creating/deleting files on, and while we can default to a safe location, we allow the user to select a different directory. How can we check if the directory they select is "safe"?
We'd like to not require admin elevation at runtime, and this path will be used for subsequent launches of the app, so it is not enough that we check whether our process is currently able to write to that location because it could be that the app is launched with admin privileges the first time (actually it does when launched by the installer because the installer runs elevated) and if they select a protected location, the next time they try to run the app, they won't have access to the directory. Potentially GB's of Persistent data is stored in this location so asking for a new location and moving the files isn't an ideal solution. | Not only can any folder have any permissions, but they can change at any time, *including between when you check a file and when you use it*. So really, the only thing you can do is just use a file and handle the exception when it fails. | Since any folder can have permissions set however the administrator sees fit, the only real way to find out is to know what user it will be running as (currently logged in user?) and then do an access check to see if that user has the appropriate access to that directory. | (C#) How do you check if a path is a protected path in Windows that requires elevation to modify? | [
"",
"c#",
"uac",
"protected-folders",
""
] |
I am looking for a Java library to incorporate into a demo web app and have looked on github, Google Code and sourceforge. So far, sourceforge seems to have the biggest selection. Are there any other places to look, or is sourceforge going to be my best bet? | [Freshmeat](http://freshmeat.net/) is also a large source of open source projects. [Here](http://freshmeat.net/tags/java-libraries) is a list of projects tagged as Java libraries. | I believe you should take a look on [Java-Source.net](http://java-source.net/) and [OpenSymphony](http://www.opensymphony.com/) | Where to look for open source Java libraries? | [
"",
"java",
"open-source",
"github",
"google-code",
"sourceforge",
""
] |
Suppose I write a program using immutable data structures in Java. Even though it is not a functional language, it should be able to execute parallely. How do I ensure that my program is being executed using all the cores of my processer? How does the computer decide which code can be run parallely?
P.S. My intent in asking this question was not to find out how to parrallelize java programs. But to know - how does the computer parallelize code. Can it do it in a functional program written in a non functional language? | i dont think you can "force" the JVM to parallelize your program, but having a separate thread executing each "task", if you can break down your program that way, would probably do the trick in most cases? parallelism is still not guaranteed however. | Java programs are parallelized through threads. The computer can't magically figure out how to distribute the pieces of your application across all the cores in an imperative language like Java. Only a functional language like Erlang or Haskell could do that. Read up on Java threads. | Writing functional programs in non-functional languages | [
"",
"java",
"functional-programming",
"multicore",
"imperative-languages",
""
] |
The global layout.php file contains the tags for each page:
```
<body>
<?php echo $sf_content ?>
</body>
```
But for all my inner HTML pages of the site, a class is applied to the body tag:
```
<body class="inner-page">
<?php echo $sf_content ?>
</body>
```
How can I pass in a class to the layout from different templates? | in your layout.php
```
<body <?php if (!include_slot('body_id')): ?>id="default"<?php endif; ?>>
```
in your templates :
```
<?php slot('body_id') ?>id="bla"<?php end_slot(); ?>
```
or
```
<?php slot(
'body_id',
sprintf('id="%s"', $sf_params->get('module')))
?>
``` | Here is the solution I used with Symfony 1.2+
Use setSlot() in the action:
```
$this->getResponse()->setSlot('home_page', 'yes');
```
Then use get\_slot() in the Layout:
```
<body class="<?php echo has_slot('home_page') ? 'home-page' : 'inner-page' ?>">
``` | How can you pass a parameter from an action to the layout in Symfony | [
"",
"php",
"symfony1",
""
] |
My Qt application should be able to create/open/save a single "Project" at once. What is the painless way to store project's settings in a file? Should it be XML or something less horrible?
Of course data to be stored in a file is a subject to change over time.
What I need is something like `QSettings` but bounded to a **project** in my application rather than to the whole application. | You can use QSettings to store data in a specific .ini file.
From the docs:
Sometimes you do want to access settings stored in a specific file or registry path. On all platforms, if you want to read an INI file directly, you can use the QSettings constructor that takes a file name as first argument and pass QSettings::IniFormat as second argument. For example:
QSettings settings("/home/petra/misc/myapp.ini",
QSettings::IniFormat); | I order to make it user editable, I would stick to plain text with one key = values by line, like in most of the Linux apps.
However this is only for the settings, not for the complete project's data which I suppose requires more complex structures.
So maybe [JSON](http://www.json.org/) ? | How do I deal with "Project Files" in my Qt application? | [
"",
"c++",
"xml",
"qt",
"settings",
""
] |
I'm searching for a proper way to clean my pointers.
Here the example code:
```
class Parent {
protected:
int m_Var;
public:
Parent() : m_Var(0) {}
virtual ~Parent() {}
void PubFunc();
};
class Child : public Parent {
protected:
bool m_Bool;
public:
Child() : m_Bool(false) {}
virtual ~Child() {}
void ChildFunc();
};
void RemoveObj(Parent **ppObj)
{
*ppObj->PubFunc();
delete *ppObj;
ppObj = NULL;
}
int main()
{
Parent* pPObj = NULL;
Child* pCObj = NULL;
pPObj = new Parent();
pCObj = new Child();
RemoveObj(&pPObj);
RemoveObj(&pCObj); // This is line 33
return 1;
}
```
But the compiler gives error:
```
classes.cpp:33: error: invalid conversion from ‘Child**’ to ‘Parent**’
classes.cpp:33: error: initializing argument 1 of ‘void RemoveObj(Parent**)’
``` | There are soo many ways to handle memory correctly.
The one close to your example would be:
```
template <typename T>
RemoveObj(T **p)
{
if (p == NULL) return;
delete *p;
*p = NULL;
}
```
Additionally you might want to use std::auto\_ptr instead. It would look like:
```
int main()
{
std::auto_ptr<Parent*> pPObj(new Parent);
std::auto_ptr<Child*> pCObj(new Child);
// no deletes needed anymore
``` | To put it simple :
Child is a subclass of Parent so that means that Child\* can be substituted with Parent\*
BUT
Child\* is NOT a subclass of Parent\* so that means that Child\*\* can't be substituted with Parent\*\*
"Child" and "Child\*" are not the same types. | C++ polymorphism not supported for pointer-to-pointer | [
"",
"c++",
"pointers",
"polymorphism",
""
] |
I have a ColdFusion 8.1 application. It gets heavy use and I see jrun.exe getting very high memory usage in the task manager. This is a 32-bit windows 2003 server. When Jrun gets around a gig of memory usage ColdFusion will stop responding at some point. The logs are a little vague, but I start to see garbage collection and heap errors in the ColdFusion log. I assume that the JRE is running out of memory.
I have the max JVM heap set to 1.2gig. After some experimenting, this seemed to be the biggest amount I could allocate and still have ColdFusion start ok. I realize that going to 64-bit might solve the problem, but that is not an option at this time.
I am considering upgrading the JRE (it is at v6.x dated pre-2008, though I don't know the exact version. I am using the JRE that came with ColdFusion 8.1. Has anyone gone through this? I assume it's just a matter of installing the new JRE and pointing ColdFusion to the new JRE directory in the ColdFusion server settings.
tia
don | it's **EXTREMELY** easy to do.
1) download the [Java SE Development Kit](https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jdk-6u13-oth-JPR@CDS-CDS_Developer) and install it like normal.
2) open up the **jmv.config** for cf in a text editor, located in **c:\coldfusion8\runtime\bin**
3) comment out the existing **java.home** line with a by putting a **"#"** at the beginning of the line add a new **java.home** line below it pointing to your jvm installation.
As an example, my java.home and jvm.config look like this:
**java.home=C:/Program Files/Java/jdk1.6.0\_11/jre**
4) restart the CF services.
As a bonus, you can running [JavaRa](http://www.softpedia.com/progDownload/JavaRa-Download-97297.html) and free up some space by deleting all the old versions of the JRE. | Adobe has a Knowledge Base that covers issues like this. Check out <http://www.adobe.com/go/2d547983> for instructions.
Sean Corfield has an article that provides some info on using Java 6 with ColdFusion 8 here:
<http://corfield.org/blog/index.cfm/do/blog.entry/entry/Java_6_and_ColdFusion_8>
As long as you install 1.6.0\_10 or greater, you should be fine. You might check out ColdFusionBloggers.org from time to time in case other JVM issues come to light in the future. | Upgrading the JRE used by ColdFusion | [
"",
"coldfusion",
"java",
""
] |
Suggestions for an updated title are welcome, as I'm having trouble easily quantifying what I'm trying to do.
This is a web-based form with PHP doing the calculations, though this question probably has an algorithmic or language agnostic answer.
Essentially, there is an Amount field and a Charge Code field.
The Charge code entered represents a short-hand for several 'agents' to whom the Amount is divided by. Most cases are single letters, however there are a couple cases where this varies, and gives a bit of trouble.
Basically, A = AgentType1, J = AgentType2, L = AgentType3, and as paperwork and user requirements would have it, "A2" is also a valid replacement for "J".
So an amount of 50 and a Charge Code of "AJ" would result in the Amount being divided by 2 (two agents) and dispersed accordingly. The same for a string like "AA2".
I have currently set up process (that works) that goes like this:
```
Divide = 0;
RegEx check for AgentType1 in Charge Code:
Divide++;
Set This-AgentType-Gets-Return;
RegEx check for AgentType2 in Charge Code:
Devide++;
Set This-AgentType-Gets-Return;
... etc ...
```
Then I divide the Amount by the "Divide" amount, and the result gets divvied up to each AgentType present in the Charge Code.
I know there must be an easier/simpler way to implement this, but it's not coming to me at the moment.
Is there a way to quickly derive the number of AgentTypes involved in the Charge Code, and which they are? | I would probably just do something simple like this:
```
$valid_codes = array('A', 'J', 'L');
// deal with the special A2 case first, to get it out of the string
// this code could be generalized if more special cases need to be handled
if (stripos($charge_code, 'A2') !== FALSE)
{
$found['J'] = true;
str_ireplace('A2', '', $charge_code);
}
foreach ($valid_codes as $code)
{
if (stripos($charge_code, $code) !== FALSE) // if the code was in the string
{
$found[$code] = true;
}
}
```
Now you can get the number you need to divide amount by with `count($found)`, and the codes you need to divide between with `array_keys($found)`. | Can you change the charge code field to an array of fields? Something like:
```
<input type="hidden" name="agent[]" value="A" />
```
for all your agents would let you do:
```
$divide = count($_POST["agent"]);
foreach($_POST["agent"] as $agent) {
$sum = $_POST["amount"] / $divide;
//do other stuff
}
``` | Divide amount by characters present in string, found via regex | [
"",
"php",
"algorithm",
"language-agnostic",
""
] |
The following instruction
```
Selenium.typeKeys("location", "gmail.com");
```
types the string `gmailcom` instead of `gmail.com`.
What's happening there?
From the comments:
I am trying to simulate autofill and the only way to do it currently on selenium is to combine type and typeKeys. eg:
```
selenium.type("assigned_to", split[0]+"@");
selenium.typeKeys("assigned_to", "gmail.com");
```
Now my question is why typeKeys doesn't type the 'dot' in between gmail.com? | Have you tried using the Native key functions and [javascript char codes](http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx)?
I couldn't get a 'period' character to work using them (char 190), but I got the decimal (char 110) to work just fine, and the text box shouldn't have a problem with either.
```
selenium.Focus("assigned_to");
selenium.Type("assigned_to", split[0]+"@");
selenium.TypeKeys("assigned_to", "gmail");
selenium.KeyPressNative("110");
selenium.TypeKeys("assigned_to", "com");
``` | Use the `type` method.
From the [javadoc for typekeys](http://release.seleniumhq.org/selenium-remote-control/1.0-beta-2/doc/java/com/thoughtworks/selenium/Selenium.html#typeKeys(java.lang.String,%20java.lang.String)):
> this command may or may not have any
> visible effect, even in cases where
> typing keys would normally have a
> visible effect
>
> ...
>
> In some cases, you may
> need to use the simple "type" command
> to set the value of the field and then
> the "typeKeys" command to send the
> keystroke events corresponding to what
> you just typed. | Selenium typeKeys strips out dot from the String being typed | [
"",
"java",
"eclipse",
"junit",
"selenium",
""
] |
I work on a very high trafficked website that uses a Smarty templating system.
When I upload a fresh copy of a template that is currently being used, the page turns blank (as if there is nothing in the template file itself). I have to shut down lighttpd, upload the template again, and start lighttpd back up.
Are there any settings in Smarty that I should be utilizing that I might not be?
Here's a list of variables that I'm setting inside Smarty itself:
> $smarty->use\_sub\_dirs = true;
>
> $smarty->compile\_check = true; | don't copy your templates directly, copy them in some temp folder and after upload finishes do a mv (move file operation) | you try clearing the cached files? If the file is not completely uploaded and someone requests it, it gets cached broken (at least this is what i think). I used to use smarty and i too use lighttpd. (decided to go XSLT)
if the page is being requested more than 2 times a second your never going to be able to actually update the file unless your turn the http server off. Or clear the smarty cached file. | Smarty templates uploaded during high trafficked site causes blank page | [
"",
"php",
"templates",
"smarty",
"lighttpd",
"templating",
""
] |
The class below raises an event for every new “dataKey” registered and raises an event when a “dataKey” is deregistered and count for that “dataKey is zero.
This class aims to be threadsafe and I am trying to make this as performant as possible.
My question is; in the Deregister method can I somehow remove the 2nd lookup when I update the value (the \_data[dataKey] = currentCountValue;)?
I can’t simple update the currentCountValue variable as the value is updated on the local stack only and not in the Dictionary.
Or can you sugguested any performance improvements? I don’t think I can remove the lock and use CAS operations (Interlocked methods) to update the count as the dictionary is not threadsafe for updates when used like this … right?
/I am using c# 3.0.
Thanks for your time.
```
public sealed class DataCounter
{
public event EventHandler NewKeyEvent;
public event EventHandler ZeroCountEvent;
private readonly Dictionary<string, int> _data = new Dictionary<string, int>();
public void Register(string dataKey)
{
lock (_data)
{
if (_data.ContainsKey(dataKey))
{
_data[dataKey]++;
}
else
{
_data.Add(dataKey, 1);
if (NewKeyEvent != null) NewKeyEvent(this, null);
}
}
}
public void Deregister(string dataKey)
{
lock (_data)
{
int currentCountValue;
if (_data.TryGetValue(dataKey, out currentCountValue))
{
if (currentCountValue > 0)
{
currentCountValue--;
_data[dataKey] = currentCountValue;
}
if (currentCountValue == 0)
{
if (ZeroCountEvent != null) ZeroCountEvent(this, null);
}
}
}
}
}
``` | As a thought - if you don't want to have to do the "set" via an indexer, you could move the counter out onto a class?
```
class CounterBox {
public int Count {get;set;}
}
```
Then have a `Dictionary<string,CounterBox>`. You can now update `Count` outside of the dictionary, and only call `Remove(dataKey)` when `.Count` is zero. This will have an extra de-reference, but you won't have to assign via the indexer.
As for which is faster: you'd need to profile.
Something like:
```
public sealed class DataCounter
{
private class CounterBox
{
public int Count { get; set; }
}
public event EventHandler NewKeyEvent;
public event EventHandler ZeroCountEvent;
private readonly Dictionary<string, CounterBox> _data
= new Dictionary<string, CounterBox>();
public void Register(string dataKey)
{
lock (_data)
{
CounterBox box;
if (_data.TryGetValue(dataKey, out box))
{
box.Count++;
}
else
{
_data.Add(dataKey, new CounterBox { Count = 1 });
EventHandler handler = NewKeyEvent;
if (handler != null) handler(this, EventArgs.Empty);
}
}
}
public void Deregister(string dataKey)
{
lock (_data)
{
CounterBox box;
if (_data.TryGetValue(dataKey, out box))
{
if (box.Count > 0)
{
box.Count--;
}
if (box.Count == 0)
{
EventHandler handler = ZeroCountEvent;
if (handler != null) handler(this, EventArgs.Empty);
_data.Remove(dataKey);
}
}
}
}
}
``` | Your event handling is not thread-safe.
```
// Execute this ...
if (NewKeyEvent != null)
// ... other threads remove all event handlers here ...
// ... NullReferenceException here.
NewKeyEvent(this, null);
```
So better do it as follows.
```
EventHandler newKeyEvent = this.newKeyEvent;
if (newKeyEvent != null)
{
newKeyEvent(this, null);
}
``` | Value types and Dictionary retrieval | [
"",
"c#",
"c#-3.0",
""
] |
I have a simple (and also trivial) banking application that I wrote in C++. I'm on ubuntu so I'm using GNOME (GTK+). I was wondering if I could write all my GUI in C/GTK+ and then somehow link it to my C++ code. Is this even possible?
**Note:** I don't want to use Qt or GTKmm, so please don't offer those as answers. | Yes, it's a very easy thing to do. All you have to do is expose some of the C++ functions as "extern C" so that the event handlers and callbacks in your UI code can call them.
In the case that you can't change the existing C++ source - no problem. just write a C++ shim for your UI, extern those functions, and call backend functions from there. | I don't see why not, with appropriate [extern "C"](http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.6) usage so your C code can call into C++. Now, granted, you're probably making it a bit harder on yourself, but it's theoretically sound. | C GUI, with a C++ backbone? | [
"",
"c++",
"c",
"gtk",
"ubuntu-9.04",
""
] |
1. My server has GMT+7, so if i move to another server has another GMT timezone, all date stored in db will incorrect?
2. Yes Q1 is correct, how about i will store date in GMT+0 timezone and display it in custom GMT timezone chosen by each member
3. How i get date with GMT+0 in java | 1) To quote from the javadocs, Java millisecond timestamps are
> the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
Therefore, as the timestamp is UTC/GMT, if you store it in the database this date will be correct no matter the time zone of the server.
2) Formatting the timestamp for display depending on the timezone would be the correct approach.
3) Creating a new java.util.Date instance and calling getTime() will get you the timestamp for GMT+0 in Java. | To add to mark's point, once you have a java.util.Date, you can "convert" it to any Timezone (as chosen by the User). Here's a code sample in Groovy (will work in Java with slight mods):
```
// This is a test to prove that in Java, you can create ONE java.util.Date
// and easily re-display it in different TimeZones
fmtStr = "MM/dd/yyyy hh:mm aa zzz"
myDate = new java.util.Date()
sdf = new java.text.SimpleDateFormat(fmtStr)
// Default TimeZone
println "Date formatted with default TimeZone: " + sdf.format(myDate)
// GMT
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
println "Date formatted with GMT TimeZone: " + sdf.format(myDate)
// America/New_York
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"))
println "Date formatted with America/New_York TimeZone: " + sdf.format(myDate)
// PST
sdf.setTimeZone(TimeZone.getTimeZone("PST"))
println "Date formatted with PST TimeZone: " + sdf.format(myDate)
``` | Java - Store GMT time | [
"",
"java",
"timezone",
"gmt",
""
] |
I'm trying to write an application that can wait on multiple resource pools at once. Each resource pool is controlled by a `Semaphor`. Can I use `WaitHandle.WaitAll()` where I pass in the entire list of semaphors? Is there a potential deadlock issue with this implementation?
My current implementation:
```
namespace XXX
{
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public class ResourcePoolManager
{
private readonly IDictionary<string, Semaphore> resourcePools = new Dictionary<string, Semaphore>();
public void AddResourcePool(string resourceName, int maxConcurrentConsumers)
{
this.resourcePools.Add(resourceName, new Semaphore(maxConcurrentConsumers, maxConcurrentConsumers));
}
public void RequestResource(string resourceName)
{
this.resourcePools[resourceName].WaitOne();
}
public void RequestMultipleResources(string[] resourceNames)
{
Semaphore[] resources = resourceNames.Select(s => this.resourcePools[s]).ToArray();
WaitHandle.WaitAll(resources);
}
public void ReleaseResource(string resourceName)
{
this.resourcePools[resourceName].Release(1);
}
}
}
``` | Sure, you can use it, but it'll only trigger if all of the semaphores are triggered at once. Depending on how the rest of your application is structured, there may indeed be starvation issues. For example, if you have two resources, A and B, and three threads:
1. Continually take resource A, work with it for one second, then release it and loop
2. Continually take resource B, work with it for one second, then release it and loop
3. Wait for both A and B to be available
You can easily wait potentially forever for both A and B to be available simultaneously.
Depending on your application, it might be better to simply take each semaphore in order, which avoids this starvation issue but introduces the traditional deadlocking issues. However, if you're sure that these locks will be available most of the time it may be safe (but might also be a ticking time bomb just waiting for your application to be under real load...)
Given your sample code, another option would be to create a global ordering over the semaphores - say, an ordering by name - and always make sure to acquire them in that order. If you do that, you can perform a multi-lock simply by locking each semaphore one-by-one in ascending order.
In this case, the order of release doesn't strictly matter - but if you release out of order, you should release all locks 'after' the lock you just released before acquiring any more (this is a rule of thumb that should give you deadlock safety. it may be possible to relax this further with detailed analysis). The recommended way is to just release in reverse order of acquisition where possible, in which case you can parley it into further acquisition at any point. For example:
1. Acquire lock A
2. Acquire lock B
3. Acquire lock C
4. Release lock C
5. Acquire lock D
6. Release B (now don't acquire anything until you release D!)
7. Release D
8. Acquire E
9. Release E
10. Release A
As long as everything follows these rules, deadlock should not be possible, as cycles of waiters cannot form.
The downside of this approach is it may delay other threads by holding a lock while waiting for another. This won't last forever; in the above example of three threads we may have this scenario for example:
1. At start, thread 2 holds B. Thread 1 holds A.
2. Thread 3 blocks on A.
3. (time passes)
4. Thread 1 releases A.
5. Thread 3 locks A, blocks on B.
6. Thread 1 blocks on A.
7. (time passes)
8. Thread 2 releases B.
9. Thread 3 locks B, does work, then unlocks.
10. Thread 1 locks A, makes progress.
As you can see, there was some downtime in which Thread 1 was blocked on A even though there was no real work to be done. However, by doing this we have greatly improved the chances for Thread 3 to make progress at all.
Whether this is a good trade-off will depend on your application - if you can definitively say that multiple threads never enter the lock, it might not even matter. But there's no one right way :) | What is your intention?
1. Do you need to wait until ALL of the semaphores are signalled?
If so, see the previous posts.
2. Do you need to wait until any 1 of the semaphores becomes signalled?
If so, use WaitAny() instead.
Notes:
WaitAny accepts an array of wait handles, and it returns the index of the handle that became signalled.
If more than one handle becomes signalled, WaitAny returns the first | Is there a way to wait on multiple semaphors | [
"",
"c#",
"multithreading",
""
] |
I have a few columns that I know won't be used initially. Is it a good practice to add columns only when needed or just leave those extra columns there?
Is it just a little more space in the header or every row? | Depends on the column type to some extent.
Variable sized columns (such as `varchar(n)`) will only use 4 extra bytes (approx) per row.
I would add columns only when required, since it is less likely that redundant columns will be added and never removed. | Yes, they do still take up space, if only a couple bytes per row (depends on the column type). If you're not going to use them until later, what good is it to keep them there? | Do extra empty columns affect sql table size significantly? | [
"",
"sql",
""
] |
I'm beginning PHP development, and I'm looking at picking brains for ideas and best practices, and also website resrouces, such as www.w3schools.com
Yes, it has to be PHP as that's the existing website technology that's being used.
I'm using Windows, although I'll be doing development on a Virtual Machine, maybe Virtual PC or Virtual Box running Windows 2000 or XP, or maybe Vista.
I'm an experienced VB6 and SQL Server developer, so I can use SQL Server as the back-end running on my host laptop, or I can use mySQL maybe. I'm thinking using SQL Server to start with would remove one layer of complexity, and allow me to concentrate on the webserver (Apache, maybe ?) and PHP and not have to worry too much about the database, as all that will be completely natural to me.
Framework recommendations, and one or two examples of what you have used them for will be appreciated.
Source and version control frameworks, tools, utilities and add-ins would also be appreciated.
I'm going to consider writing an answer to this question myself with my experiences as I get started, almost like a 'how-to' step-by-step guide so that anyone in the future who wants to do the same thing can get going even quicker.
Thanks in advance, gurus. | First thing I suggest you do is read [How Is PHP Done the Right Way?](https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way/694309#694309)
For source control, Subversion is a decent place to start.
You will need Firefox plus Firebug. Also look at [What’s in your web-developer toolbox?](https://stackoverflow.com/questions/188938/whats-in-your-web-developer-toolbox) and [Free tools to speed up web development](https://stackoverflow.com/questions/495339/free-tools-to-speed-up-web-development).
In regards to frameworks, start with [Choosing the right PHP framework](https://stackoverflow.com/questions/838028/choosing-the-right-php-framework).
You probably should consider Javascript frameworks too, in which case start with [JavaScript frameworks and CSS frameworks: JQuery, YUI, neither, or something else?](https://stackoverflow.com/questions/846538/javascript-frameworks-and-css-frameworks-jquery-yui-neither-or-something-else) and [Which Javascript framework (jQuery vs Dojo vs … )?](https://stackoverflow.com/questions/394601/which-javascript-framework-jquery-vs-dojo-vs) | Ignore frameworks to begin with. Once you have an idea about what php is/can, you can pick a framework. But don't do it as the first thing.
As for setup, I would strongly recommend that you use a standard stack. That means Apache and MySql. You can run it on Windows for development mode. The differences between Windows and \*nix are rather small for most PHP applications.
For revision control you should probably use SVN, as it is the de-facto standard at the moment, and is fairly easy to use. You can download [TortoiseSVN](http://tortoisesvn.tigris.org/) for Windows, if you don't like to use the command line.
Use [PDO](http://www.php.net/pdo) for database connectivity, rather than the older `mysql_*` functions. It's the new standard in php5. Make sure that [magic-quotes](http://www.php.net/magic_quotes) are disabled, and use prepared statements/bound parameters for binding data to queries. | Beginning PHP development - programming stack recommendation and web site resources | [
"",
"php",
""
] |
Hi guys I wish to get information for entries I have in my database from wikipedia like for example some stadiums and country information. I'm using Zend Framework and also how would I be able to handle queries that return multiple ambiguous entries or the like.. I would like all the help I can get here... | Do a simple [HTTP request](http://en.wikipedia.org/wiki/Wikipedia_database) to the article you are looking to import. [Here's a good library](http://www.onderstekop.nl/articles/114/) which might help with parsing the HTML, though there are dozens of solutions for that as well, [including using the standard DOM model which is provided by php](https://www.php.net/dom).
```
<?php
require_once "HTTP/Request.php";
$req =& new HTTP_Request("http://www.yahoo.com/");
if (!PEAR::isError($req->sendRequest())) {
echo $req->getResponseBody();
}
?>
```
Note, you will be locked out of the site if your traffic levels are deemed too high. (If you want a HUGE number of articles, [download the database](http://en.wikipedia.org/wiki/Wikipedia_database)) | Wikipedia is based on MediaWiki, offering an Application Programmable Interface (API).
You can check out MediaWiki API on Wikipedia - <http://en.wikipedia.org/w/api.php>
Documentation for MediaWiki API - <http://www.mediawiki.org/wiki/API> | How do I get information from wikipedia into my application | [
"",
"php",
"zend-framework",
"wikipedia",
""
] |
I am looking for a Java class where I can specify a set of date rules, such as "every 3rd sunday" and "the first occurrence of a monday every second month". I want to be able to get something like an infinite iterator out of it (.next() would return the next date matching the rules set).
I think I'd be able to build it myself - but calendars are a hassle, and it feels like something similar should exist already. I hate being the one to reinvent a crappier wheel.
Is anyone aware of something like this? I have been looking at JODA, and it seems to lay the groundwork for it, but does not appear to give the full functionality I want.. | I don't think there's any readily made iterators for joda-time or Java Calendar API for that matter, however with joda it's so easy that you should just go with it. For example after re-familiarizing myself with joda after a few months pause I made this in about 10 minutes:
```
public class InstantIterator implements Iterator<Instant>,
Iterable<Instant> {
private Instant current;
private final Instant original;
private Duration skip;
private List<Instant> skipThese;
public InstantIterator(Instant startFrom, Duration skip) {
this.current = original = startFrom;
this.skip = skip;
skipThese = new Vector<Instant>();
}
public boolean hasNext() {
return true;
}
public Instant next() {
Instant currentNext = current.toInstant();
current = current.plus(skip);
while (skipThese.contains(currentNext)) {
currentNext = current.toInstant();
current = current.plus(skip);
}
return currentNext;
}
public void remove() {
skipThese.add(current.toInstant());
}
public Iterator<Instant> iterator() {
return this;
}
public void rewind() {
current = original.toInstant();
}
public void resetRemoved() {
skipThese.clear();
}
public void resetIterator() {
rewind();
resetRemoved();
}
}
```
Joda Time is awesome :-) | My company has [something very much like you want](http://precisionsoftware.blogspot.com/2009/03/natural-language-net-date-parser.html) but it's for .NET so it probably won't do you any good. | Java date iterator factory, with rules specifying how to calculate the intervals | [
"",
"java",
"date",
"iterator",
"rules",
""
] |
If I have a joining table with two columns, TeamA and TeamB, how can I ensure that each pair is unique?
Obviously I can put a unique composite index on these columns but that will only ensure uniqueness in the order A,B but not B,A correct?
```
TeamA | TeamB
-------------
red | blue
pink | blue
blue | red
```
As you can see, Red vs. Blue has already been specified as the first record and then it is specified again as the last. This should be illegal since they will already be facing each other.
**Edit:** Also, is there a way to handle the SELECT case as well? Or the UPDATE? DELETE? Etc..
Also, the idea of Home or Away team has been brought up which may be important here. This initial concept came to me while thinking about how to build a bracketing system on the DB side. | If your RDBMS (you didn't specify) supports Triggers, then create a trigger on that table to enforce your constraint.
Create a trigger that fires on INSERT, that checks if a pair already exists with order reversed. If it does ROLLBACK, else allow the insert. | Define a constraint such that, for example, the value in the A column must be (alphabetically or numerically) smaller than the value in the B column: thus you'd be allowed to insert {blue,red} but not {red,blue} because blue is less than red. | Unique column pairs as A,B or B,A | [
"",
"sql",
"mysql",
""
] |
I want to store a set of integers that get auto incremented at build time:
```
int MajorVersion = 0;
int MinorVersion = 1;
int Revision = 92;
```
When I compile, it would auto-increment `Revision`. When I build the setup project, it would increment `MinorVersion` (I'm OK with doing this manually). `MajorVersion` would only be incremented manually.
Then I could display a version number in menu Help/About to the user as:
```
Version: 0.1.92
```
How can this be achieved?
This question asks not only how to have an auto-incrementing version number, but also how to use that in code which is a more complete answer than others. | If you add an [AssemblyInfo](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx) class to your project and amend the `AssemblyVersion` attribute to end with an asterisk, for example:
```
[assembly: AssemblyVersion("2.10.*")]
```
Visual studio will increment the final number for you according to [these rules](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx) (thanks galets, I had that completely wrong!)
To reference this version in code, so you can display it to the user, you use `reflection`. For example,
```
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
.AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $"{version} ({buildDate})";
```
## Three important gotchas that you should know
### From @ashes999:
It's also worth noting that if both `AssemblyVersion` and `AssemblyFileVersion` are specified, you won't see this on your .exe.
### From @BrainSlugs83:
Setting only the 4th number to be `*` can be bad, as the version won't always increment.
**The 3rd number is the number of days since the year 2000**, and **the 4th number is the number of seconds since midnight (divided by 2) [IT IS NOT RANDOM]**. So if you built the solution late in a day one day, and early in a day the next day, the later build would have an earlier version number. I recommend always using `X.Y.*` instead of `X.Y.Z.*` because your version number will ALWAYS increase this way.
### Newer versions of Visual Studio give this error:
> **(this thread begun in 2009)**
>
> The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation.
>
> See this SO answer which explains how to [remove determinism](https://stackoverflow.com/a/58101474/1555612) (<https://stackoverflow.com/a/58101474/1555612>) | You could use the [T4 templating mechanism in Visual Studio to generate the required source code from a simple text file](https://vagifabilov.wordpress.com/2010/04/24/using-t4-templates-to-manage-assembly-version-information/) :
> I wanted to configure version information generation for some .NET
> projects. It’s been a long time since I investigated available
> options, so I searched around hoping to find some simple way of doing
> this. What I’ve found didn’t look very encouraging: people write
> Visual Studio add-ins and custom MsBuild tasks just to obtain one
> integer number (okay, maybe two). This felt overkill for a small
> personal project.
>
> The inspiration came from one of the StackOverflow discussions where
> somebody suggested that T4 templates could do the job. And of course
> they can. The solution requires a minimal effort and no Visual Studio
> or build process customization. Here what should be done:
>
> 1. Create a file with extension ".tt" and place there T4 template that will generate AssemblyVersion and AssemblyFileVersion attributes:
```
<#@ template language="C#" #>
//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//
using System.Reflection;
[assembly: AssemblyVersion("1.0.1.<#= this.RevisionNumber #>")]
[assembly: AssemblyFileVersion("1.0.1.<#= this.RevisionNumber #>")]
<#+
int RevisionNumber = (int)(DateTime.UtcNow - new DateTime(2010,1,1)).TotalDays;
#>
```
> You will have to decide about version number generation algorithm. For
> me it was sufficient to auto-generate a revision number that is set to
> the number of days since January 1st, 2010. As you can see, the
> version generation rule is written in plain C#, so you can easily
> adjust it to your needs.
>
> 2. The file above should be placed in one of the projects. I created a new project with just this single file to make version management
> technique clear. When I build this project (actually I don’t even need
> to build it: saving the file is enough to trigger a Visual Studio
> action), the following C# is generated:
```
//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//
using System.Reflection;
[assembly: AssemblyVersion("1.0.1.113")]
[assembly: AssemblyFileVersion("1.0.1.113")]
```
> Yes, today it’s 113 days since January 1st, 2010. Tomorrow the
> revision number will change.
>
> 3. Next step is to remove AssemblyVersion and AssemblyFileVersion attributes from AssemblyInfo.cs files in all projects that should
> share the same auto-generated version information. Instead choose “Add
> existing item” for each projects, navigate to the folder with T4
> template file, select corresponding “.cs” file and add it as a link.
> That will do!
>
> What I like about this approach is that it is lightweight (no custom
> MsBuild tasks), and auto-generated version information is not added to
> source control. And of course using C# for version generation
> algorithm opens for algorithms of any complexity. | How to have an auto incrementing version number (Visual Studio)? | [
"",
"c#",
"visual-studio",
"versioning",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.