instruction stringlengths 0 30k ⌀ |
|---|
from the rhino book:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it[1]
[1]: http://oreilly.com/catalog/9780596000486/ |
[This post][1] addresses your question. The gist of it is:
Text Editor > C# > Advanced > Generate XML documentation comments for ///
[1]: http://forums.msdn.microsoft.com/en-US/csharpide/thread/a41e3652-efe2-4f81-ad3e-94994974fcb2/ |
How to get hashes out of arrays in Perl? |
|perl|arrays|hash| |
I want to write a little "DBQuery" function in perl so I can have one-liners which send an SQL statement and receive back and an array of hashes, i.e. a recordset. However, I'm running into an issue with Perl syntax (and probably some odd pointer/reference issue) which is preventing me from packing out the information from the hash that I'm getting from the database. The sample code below demonstrates the issue.
I can get the data "Jim" out of a hash inside an array with this syntax:
print $records[$index]{'firstName'}
returns "Jim"
but if I copy the hash record in the array to its own hash variable first, then I strangely can't access the data anymore in that hash:
<pre><code>
%row = $records[$index];
$row{'firstName'};
</code></pre>
returns "" (blank)
Here is the full sample code showing the problem. Any help is appreciated:
<pre><code>
my @records = (
{'id' => 1, 'firstName' => 'Jim'},
{'id' => 2, 'firstName' => 'Joe'}
);
my @records2 = ();
$numberOfRecords = scalar(@records);
print "number of records: " . $numberOfRecords . "\n";
for(my $index=0; $index < $numberOfRecords; $index++) {
#works
print 'you can print the records like this: ' . $records[$index]{'firstName'} . "\n";
#does NOT work
%row = $records[$index];
print 'but not like this: ' . $row{'firstName'} . "\n";
}
</code></pre> |
I have various filters in my .procmailrc file, but the most useful is this one, which I add to the very top of the file before I make any other changes.
:0 c:
mail.save
This saves a copy of everything and then continues with the rest of the recipes. If I've done something wrong, my e-mail is saved in the file "mail.save". When I'm sure my changes are working, I comment these lines out, until the next time.
--
bmb |
Using the result of a command as an argument in bash? |
|bash|command-line| |
To create a playlist for all of the music in a folder, I am using the following command in bash:
ls > list.txt
I would like to use the result of the **pwd** (print working directory) command for the name of the playlist.
Something like:
ls > ${pwd}.txt
That doesn't work though - can anyone tell me what syntax I need to use to do something like this? |
To create a playlist for all of the music in a folder, I am using the following command in bash:
ls > list.txt
I would like to use the result of the **pwd** (print working directory) command for the name of the playlist.
Something like:
ls > ${pwd}.txt
That doesn't work though - can anyone tell me what syntax I need to use to do something like this?
**Edit:** As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went! |
With the [ByteArray][1] you can do pretty much what you want. Before starting playback you can analyze the bytes of the FLV header (use byteArray.readByte() and refer to the specs) to determine to check if the audio flag is on. Since the FLV header is loaded almost instantly this shouldn't cause any inconvenient delay for the user.
With SWF's it's a lot tricker -- i'm pretty sure there's no easy way to determine in advance if a swf plays audio somewhere. A way to do it could be to look at what assets the SWF has defined in the library but also then the swf could just load an external audio file (or even generate it with some hacks or the new apis in Flash player 10). If the swf's are user submitted (or something similar that's out of your immediate control) I think this is a risky road..
[1]: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/ByteArray.html |
The objects in my apps tend to relate one-to-one to the database, but I'm finding using Linq To Sql rather than sprocs makes it much easier writing complicated queries, especially being able to build them up using the deferred execution. e.g. from r in Images.User.Ratings where etc. This saves me trying to work out several join statements in sql, and having Skip & Take for paging also simplifies the code rather than having to embed the row_number & 'over' code. |
To do literally what you said, you could try:
ls > `pwd`.txt
which will use the full pathname, which should be fine.
Note that if you do this in your home directory, which might
be in /home/hoboben, you will be trying the create /home/hoboben.txt,
a text file in the directory above.
Is this what you wanted?
If you wanted the directory to contain a file named after it, you would get
the basename of the current directory and append that with .txt to the pwd.
Now, rather than use the pwd command... why not use the PWD environment variable?
For example:
ls > $PWD.txt
or
ls > ${PWD}.txt
is probably when you were trying to remember with your second example.
If you're in /home/hoboben and you want to create /home/hoboben/hoboben.txt, try:
ls > ${PWD}/${PWD##*/}.txt
If you do this, the file will contain its own name, so most often, you would remedy this in one of a few ways. You could redirect to somewhere else and move the file or name the file beginning with a dot to hide it from the ls command as long as you don't use the -a flag (and then optionally rename the resulting file).
I write my own scripts to manage a directory hierarchy of music files and I use subdirectories named ".info", for example, to contain track data in some spare files (basically, I "hide" metadata this way). It works out okay because my needs are simple and my collection small. |
To me the fundamental difference is that Java Iterators point between items, whereas C++ STL iterators point at items.
|
It's not built-in. Maybe try a macro? You should be able to make almost any keyboard short you want that way. |
It's not built-in. I would try a macro - AutoKeys? You should be able to make almost any keyboard short you want that way. |
Converting scripts from ksh to bash. |
|unix|bash|ksh| |
I have some ksh scripts which I'd like to convert to run with bash instead.
Are there any useful on-line resources for this?
I'm really looking for a list of differences between the two shells and any gotchas I might encounter, although all information is welcome :-) |
Congratulations on the new job!
Relax and keep your cool. Read something on [Refactoring][1].
I guess, the process itself will make sure you are productive as long as you apply common sense :)
[1]: http://www.refactoring.com/sources.html |
The difference between the connections strings in SQLCLR |
|sqlclr| |
I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used
Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)
instead of
DIM conn As New SqlConnection("context connection=true")
I'm wondering what the difference since it's localhost on the first?
|
Great question!
I would say the first thing to do is get the daily scrums going. Your part in the scrum will be learning the code. It will provide you a way to ask questions and get a feel for who can help you learn the code.
Once you have that guy (or guys) picked out start pair programming with them. Let them drive but ask questions. You will be surprised how much you can pick up that way. Given their bend on Agile, that should be an easy sell. :)
Once you have that established, be sure to swap partners every so often so you get a feel for the enitre code base. Just sticking woth one guy who is doing one part won't give you a big picture but jumping between people will get you a better big picture view of the code.
Just my 2 cents. :) Good luck and have fun!! |
Yes, it’s *not possible*. You can’t add privileges to the worker process without opening the server up to potential security / DOS problems in a production environment. An installer (like a MSI) usually runs with elevated permissions, and installs / uninstalls the performance counter categories and counters as well as other locked down objects.
For example, [Windows Installer XML (WiX) has support for Performance Counters][1]...
[1]: http://wix.sourceforge.net/manual-wix2/perfmon.htm "Windows Installer XML (WiX) toolset - Performance Counter CustomActions" |
Does Alt Q Alt R (ie menu item selection) not suit? |
I think we are going to go the third party route. I like the XSL -> HTML -> PDF -> Printer flow... Winnovative's [HTML to PDF][1] looks good for the first part, but I'm running into a block finding a good PDF printing solution... any suggestions?
[1]: http://www.winnovative-software.com/ |
I think we are going to go the third party route. I like the XSL -> HTML -> PDF -> Printer flow... Winnovative's [HTML to PDF][1] looks good for the first part, but I'm running into a block finding a good PDF printing solution... any suggestions? Ideally the license would be on a developer basis, not on a deployed runtime basis.
[1]: http://www.winnovative-software.com/ |
There's [ActiveRecord the Design Pattern](http://en.wikipedia.org/wiki/Active_record_pattern) and [ActiveRecord the Rails ORM Library](http://api.rubyonrails.com/classes/ActiveRecord/Base.html), and there's also a ton of knock-offs for .NET, and other languages.
These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?"
I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it.
> @BlaM
>
> The problem that I see with Active Records is, that it's always just about one table
Code:
class Person
belongs_to :company
end
people = Person.find(:all, :include => :company )
This generates SQL with `LEFT JOIN companies on companies.id = person.company_id`, and automatically generates associated Company objects so you can do `people.first.company` and it doesn't need to hit the database because the data is already present.
> pix0r
>
> The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records
Code:
person = Person.find_by_sql("giant complicated sql query")
This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done.
> Tim Sullivan
>
> ...and you select several instances of the model, you're basically doing a "select * from ..."
Code:
people = Person.find(:all, :select=>'name, id')
This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on.
I <3 ActiveRecord :-) |
There's [ActiveRecord the Design Pattern](http://en.wikipedia.org/wiki/Active_record_pattern) and [ActiveRecord the Rails ORM Library](http://api.rubyonrails.com/classes/ActiveRecord/Base.html), and there's also a ton of knock-offs for .NET, and other languages.
These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?"
I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it.
> @BlaM
>
> The problem that I see with Active Records is, that it's always just about one table
Code:
class Person
belongs_to :company
end
people = Person.find(:all, :include => :company )
This generates SQL with `LEFT JOIN companies on companies.id = person.company_id`, and automatically generates associated Company objects so you can do `people.first.company` and it doesn't need to hit the database because the data is already present.
> @pix0r
>
> The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records
Code:
person = Person.find_by_sql("giant complicated sql query")
This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done.
> @Tim Sullivan
>
> ...and you select several instances of the model, you're basically doing a "select * from ..."
Code:
people = Person.find(:all, :select=>'name, id')
This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. |
I don't know if it's best practice but I have written similar code in the not so recent past because I too felt that I could improve the separation of concerns by using my own classes instead of the LINQ-designer-generated ones within my application.
You may want to consider just returning an IQueryable<Customer> instead of an IList<Customer> from your data-access method. Since IQueryable<T> inherits from IEnumerable<T> the rest of your app should be able to deal with it quite well. You can also convert it to a List when you really need to.
The advantage of this is that you can dynamically modify your query quite easily and minimze the amount of data returned from SQL Server.
E.g. if your method signature is
IQueryable<Customer> GetCustomers() you could get a single customer by calling GetCustomers().Where(c => c.CustomerID == 101).Single();
In this example only one record would be returned from the database whereas I imagine currently your code would return either all customers or you'd be required to write separate methods (and thus very repetitive code) to cater for all the different things you may want to filter by. |
Performance tip:
If you have to concatenate large strings, put the string parts into an array and use the Array.Join() method to get the overall string. This can be many times faster for concatenating a large number of strings.
No StringBuilder in javascript. |
In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes. For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method. A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.
I try to be judicious about this particular use, though. If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.
|
log4j is a much nicer package overall, and doesn't have some of the hiccups that java.util.logging contains. I'd second that using log4j directly is easier than using the commons logging. |
Can a STP template be hidden from subsite creation page? |
|sharepoint|templates|moss| |
When a template is added using the addtemplate stsadm command, it becomes available to everyone when creating a subsite. Is there any way to make it only available when a site collection is being created? |
Parasoft has a tool called Insure++ (link: http://www.parasoft.com/jsp/products/quick_facts.jsp?product=Insure) which says it'll do that.
I've used Insure++ on 32-bit and 64-bit apps on Linux and it worked okay. It sometimes got confused when it was trying to parse template/stl code and would fall over.
That url says it works on 32- and 64-bit windows, good luck! |
To do literally what you said, you could try:
ls > `pwd`.txt
which will use the full pathname, which should be fine.
Note that if you do this in your home directory, which might
be in /home/hoboben, you will be trying the create /home/hoboben.txt,
a text file in the directory above.
Is this what you wanted?
If you wanted the directory to contain a file named after it, you would get
the basename of the current directory and append that with .txt to the pwd.
Now, rather than use the pwd command... why not use the PWD environment variable?
For example:
ls > $PWD.txt
or
ls > ${PWD}.txt
is probably what you were trying to remember with your second example.
If you're in /home/hoboben and you want to create /home/hoboben/hoboben.txt, try:
ls > ${PWD}/${PWD##*/}.txt
If you do this, the file will contain its own name, so most often, you would remedy this in one of a few ways. You could redirect to somewhere else and move the file or name the file beginning with a dot to hide it from the ls command as long as you don't use the -a flag (and then optionally rename the resulting file).
I write my own scripts to manage a directory hierarchy of music files and I use subdirectories named ".info", for example, to contain track data in some spare files (basically, I "hide" metadata this way). It works out okay because my needs are simple and my collection small. |
Showing a tooltip for a MenuItem |
|.net|winforms| |
I've got a menu that contains, among other things, some most-recently-used file paths. The paths to these files can be long, so the text sometimes gets clipped like "C:\Progra...\foo.txt"
I'd like to pop a tooltip with the full path when the user hovers over the item, but this doesn't seem possible with the [Tooltip][1] class in .NET 2.0.
Am I missing something obvious?
[1]: http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx |
Compiling code on an external drive |
|visual-studio|hardware| |
To make things easier when switching between machines (my workstation at the office and my personal laptop) I have thought about trying an external hard drive to store my working directory on. Specifically I am looking at Firewire 800 drives (most are 5400 rpm 8mb cache). What I am wondering is if anyone has experience with doing this with Visual Studio projects and what sort of performance hit they see. |
Safari is really standards compliant. Unless you're using some really esoteric browser features, in general if something works in Firefox, I've found it works without modification in Windows Safari.
Apple has [a developer center for web developers][1], but I didn't find anything too useful there.
[1]: http://developer.apple.com/internet/safari/ |
I use vmware and the virtual machines are on an external usb drive. Performance is fine. You might have some issues with the drive name changing - not an issue if you use virtual machines. |
Granted I work in an industry were Personal Information and Intellectual Property are king, but I don't like that idea at all. That hard drive disappears and you have a big problem.
Why not Remote Desktop into the work machine?
**EDIT** Stipud Spelingg |
I've seen some people having a play with [distributed JUnit][1]. I can't particularly vouch for how effective it is, but the other teams I've seen seemed to think it was straight forward enough. Hope that helps.
[1]: http://216.93.179.140:8080/wiki/display/GG15UG/Distributed+JUnit+Overview |
You could import the CSV file into a table as is, then write an SQL query that does all the required transformations on the imported table and inserts the result into the target table.
So something like:
> <(load the CSV file into temp_table - n, city_name)>
> insert into target_table
> select t.n, c.city_id as city
> from temp_table t, cities c
> where t.city_name = c.city_name
Nice tip about using Excel, but I also suggest getting comfortable with a scripting language like Python, because for some task it's easier to just write a quick python script to do the job than trying to find the function you need in Excel or a pre-made tool that does the job. |
My understanding is that the connection pooling is automatically handled for you when using the SqlConnection object. This is purposefully designed to work with MSSQL and will ensure connections are pooled efficiently. You just need to be sure you close them when you are finished with them (and ensure they are disposed of).
I have never heard of people needing to roll their own myself. But I admit my experience is kind of limited there. |
Fabio,
I've done what Vaibhav has done many times, and it's a good "quick and dirty" way to get data into a database.
If you need to do this a few times, or on some type of schedule, then a more reliable way is to load the CSV data "as-is" into a work table (i.e customer_dataload) and then use standard SQL statements to populate the missing fields.
(I don't know Firebird syntax - but something like...)
UPDATE person
SET id = (SELECT newguid() FROM createguid)
UPDATE person
SET cityid = (SELECT cityid FROM cities WHERE person.cityname = cities.cityname)
etc.
Usually, it's much faster (and more reliable) to get the data INTO the database and then fix the data than to try to fix the data during the upload. You also get the benefit of transactions to allow you to ROLLBACK if it does not work!! |
Well, it is going to go away as the answer to all these questions will be LINQ. Incidentally, we have never needed custom connection pooling for any of our applications, so I am not sure what all the noise is about. |
The connection pooling built-in to ADO.Net is robust and mature. I would recommend against attempting to write your own version. |
@BlaM:
Sometimes I justed implemented an active record for a result of a join. Doesn't always have to be the relation Table <--> Active Record. Why not "Result of a Join statement" <--> Active Record ? |
My guess here is that because the data was able to import that the field is actually a varchar or some character field, because importing to a numeric field might have failed. Here was a test case I ran purely a MySQL, SQL solution.
1. The table is just a single column (alpha) that is a varchar.
mysql> desc t;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| alpha | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2. Add a record
mysql> insert into t values('"1,000,000"');
Query OK, 1 row affected (0.00 sec)
mysql> select * from t;
+-------------+
| alpha |
+-------------+
| "1,000,000" |
+-------------+
3. Update statement.
mysql> update t set alpha = replace( replace(alpha, ',', ''), '"', '' );
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from t;
+---------+
| alpha |
+---------+
| 1000000 |
+---------+
So in the end the statement I used was:
UPDATE table
SET field_name = replace( replace(field_name, ',', ''), '"', '' );
I looked at the [MySQL Documentation](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace) and it didn't look like I could do the regular expressions find _and replace_. Although you could, like Eldila use a regular expression for a find and then an alternative solution for replace.
[@Eldila](http://stackoverflow.com/questions/7917/remove-quotes-and-commas-from-a-string-in-mysql#8135): I didn't quite understand your remark about I said. Did you mean to say "Please _take_ joe seriously?" Or did you mean something else? |
The nested data structure contains a hash *reference*, not a hash.
# Will work (the -> dereferences the reference)
$row = $records[$index];
print "This will work: ", $row->{firstName}, "\n";
# This will also work, by promoting the hash reference into a hash
%row = %{ $records[$index] };
print "This will work: ", $row{firstName}, "\n";
If you're ever presented with a deep Perl data structure, you may profit from printing it using <a href="http://search.cpan.org/perldoc?Data::Dumper">Data::Dumper</a> to print it into human-readable (and Perl-parsable) form. |
what you actually have in your array is a hashref, not a hash. If you don't understand this concept, its probably worth reading the [perlref][1] documentation.
to get the hash you need to do
my %hash = %{@records[$index]};
Eg.
my @records = (
{'id' => 1, 'firstName' => 'Jim'},
{'id' => 2, 'firstName' => 'Joe'}
);
my %hash = %{$records[1]};
print $hash{id}."\n";
Although. I'm not sure why you would want to do this, unless its for academic purposes. Otherwise, I'd recommend either fetchall_hashref/fetchall_arrayref in the DBI module or using something like Class::DBI.
[1]: http://perldoc.perl.org/perlref.html |
**Suggestion:** If you post each of your recommended podcasts as a *separate* answer then people can vote for your "answer".
BTW, Joel discussed this on the SO Podcast (can't find the reference in the Transcript wiki) and suggested something like:
- Post your suggested "favorite" (tech podcast, in this case) as a question: "Do you like < > podcast and tag it with "technology podcast".
The beauty of this is that we get a simple poll. Yes, it would be nice to actually *have* a poll but that's not yet SO feature. |
Nice question although to avoid distractions about _right_ and _wrong_ I'd consider asking for the pros and cons of each approach -- I think that's what you meant by which is better or worse and why. Anyway ....
##The First Approach aka Inheritance
Pros:
* Allows polymorphic behavior.
* Is _initially_ simple and convenient.
Cons:
* _May_ become complex or clumsy over time _if_ more behavior and relations are added.
## The Second Approach aka Composition
Pros:
* Maps well to non-oop scenarios like relational tables, structured programing, etc
* Is straightforward (if not necessarily convenient) to _incrementally_ extend relations and behavior.
Cons:
* No polymorphism therefore it's less convenient to use related information and behavior
Lists like these + the questions [Jon Limjap](http://stackoverflow.com/users/372/jon-limjap) mentioned will help you make decisions and get started -- then you can find what the _right_ answers should have been ;-) |
The array of hashes doesn't actually contain hashes, but rather an *references* to a hash.
This line:
%row = $records[$index];
assigns %row with one entry. The key is the *scalar*:
{'id' => 1, 'firstName' => 'Jim'},
Which is a reference to the hash, while the value is blank.
What you really want to do is this:
$row = $records[$index];
$row->{'firstName'};
or else:
$row = %{$records[$index];}
$row{'firstName'};
|
Best way to deal with RoutingError in Rails 2.1.x? |
How do I start threads in plain C? |
|c|multithreading| |
I have used fork() in C to start another process. How do I start a new thread? |
Have you tried looking at [this][1] page? It has a useful matrix of features and links to elsewhere.
Also [this][2] link, search for:
> C2) How does bash differ from the Korn shell
[1]: http://www.faqs.org/faqs/unix-faq/shell/shell-differences/
[2]: http://www.faqs.org/faqs/unix-faq/shell/bash/ |
Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
private static final ThreadLocal<DocumentBuilder> builderLocal =
new ThreadLocal<DocumentBuilder>() {
@Override protected DocumentBuilder initialValue() {
return
DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
}
};
(Disclaimer: Not so much as attempted to compile the code.) |
I assume when you say 'the unit test calls methodB()', you mean not directly and via methodA().
So, is it possible methodB() is being called elsewhere, by another unit test or methodC() maybe? |
pthreads is a good start, look [here][1]
[1]: https://computing.llnl.gov/tutorials/pthreads/ |
Check out the [pthread][1] (POSIX thread) library.
[1]: https://computing.llnl.gov/tutorials/pthreads/ |
# Shuffle card deck evenly in C++
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
|
# Shuffle card deck evenly in C++
#include <algorithm>
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
**Testing**:
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< "freq=" << j->second << std::endl;
}
|
I have a huge web app that is having issues with memory leak in IE 6.
Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy.
But if I have a very huge application, where should a start from? |
|internet-explorer-6|memory-leaks| |
Using Lucene to search for email addresses |
|lucene|lucene.net|.net|search| |
I want to use Lucene (in particular, Lucene.NET) to search for email address domains.
E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.
Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches.
How can I do this? |
|.net|search|lucene|lucene.net| |
I want to use Lucene (in particular, Lucene.NET) to search for email address domains.
E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.
Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word.
How can I do this? |
|.net|search|lucene| |
Accessing mp3 Meta-Data with Python |
|python|mp3|metadata| |
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas? |
|python|mp3|meta-data| |
I'm guessing that the problem is recognizing whether the property is nullable or not. In C# you do this with this code:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
... but I'm not sure what the equivalent of that last clause is in VB.NET. |
Remove Meta Data from .NET applications? |
|metadata|.net|decompiling| |
Is this possible? Does the .NET framework depend on the meta data in the bytecode? I'd like to have an application i write not work in reflector or a similar .NET decompiler.
Any help would be super :D |
|.net|metadata|decompiling| |
|.net|decompiling|meta-data| |
Migrating from MySQL to PostgreSQL |
|mysql|postgresql|migrating|database| |
We are currently using MySQL for a product we are building, and are keen to move to PostgreSQL as soon as possible, primarily for licensing reasons.
Has anyone else done such a move? Our database is the lifeblood of the application and will eventually be storing TBs of data, so I'm keen to hear about experiences of performance improvements/losses, major hurdles in converting SQL and stored procedures, etc. |
|ruby|ruby-on-rails|routes| |
So. I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.
This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.
Then there's subtle routing problems, where we do want to be notified: /artists/<badid> for example, or /<year>/<month>/<day>. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.
In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist? |
Append the following RewriteCond:
RewriteCond %{HTTP:Host} ^[^.]\.[a-z]{2,5}$ [NC]
That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.
You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.] is more permissive).
All in all I think in this case that wouldn't be necessary |
Append the following RewriteCond:
RewriteCond %{HTTP:Host} ^[^.]+\.[a-z]{2,5}$ [NC]
That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.
You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).
All in all I think in this case that wouldn't be necessary.
EDIT: sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+ |
You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'. |
If you use the `curses` package, you have much greater control of the console. It also comes at a higher cost in code complexity and is probably unnecessary unless you are developing a large console-based app.
For a simple solution, you can always put the spinning wheel at the end of the status messge (the sequence of characters `|, \, -, /` which actually looks nice under blinking cursor. |
Regarding your question (in your comment to Ash's response) about the StringBuilder in ASP.NET Ajax the experts seem to disagree on this one.
Christian Wenz says in his book *Programming ASP.NET AJAX* (O'Reilly) that "this approach does not have any measurable effect on memory (in fact, the implementation seems to be a tick slower than the standard approach)."
On the other hand Gallo et al say in their book *ASP.NET AJAX in Action* (Manning) that "When the number of strings to concatenate is larger, the string builder becomes an essential object to avoid huge performance drops."
I guess you'd need to do your own benchmarking and results might differ between browsers, too. However, even if it doesn't improve performance it might still be considered "useful" for programmers who are used to coding with StringBuilders in languages like C# or Java. |