instruction
stringlengths
0
30k
Select a random N elements from List<T> in C#
|c#|generics|
I need a quick algorithm to select a random 5 elements from a generic list. For example, I'd like to get a random 5 elements from a List<string>.
Iterate through and for each element make the probability of selection = (number needed)/(number left) So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and oft...
@Matthew is right. Try this: int main() { int i; for(i = 0; i<=1024; i++) { if (!(i & 0xFF)) printf("& i = %d\n", i); if (!(i % 0x100)) printf("mod i = %d\n", i); } }
@Jeff V: I see a problem with it! (Beyond that your original code was looking for a mod 6 and now you are essentially looking for a mod 8). You keep doing an extra +1! Hopefully your compiler optimizes that away, but why not just test start at 2 and go to MAXCOUNT inclusive? Finally, you are returning true every time t...
You should really check the embedded device you need. All the assembly language I have seen (x86, 68000) implement the modulus using a division. Actually, the division assembly operation returns the result of the division and the remaining in two different registers.
C++ deleting a pointer to a pointer
|c++|pointers|
So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any ...
I think you're going to have to loop over I'm afraid.
The examples you provided are reason enough to <i>not</i> use flow-control from finally. Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....
To rid yourself of the XML, try [Fluent NHibernate](http://code.google.com/p/fluent-nhibernate/) Linq2NH isn't fully baked yet. The core team is working on a different implementation than the one in NH Contrib. It works fine for simple queries though. Use sparingly if at all for best results. As for how to quer...
Pointers are pretty much just memory references and not spiffy little self-cleaning .net objects. Creating proper destructors for each class will make the deletion a little cleaner than massive loops throughout the code.
You're productivity will increase if you decide to put the time in to program your text editor. Of the two editors, emacs presents a better framework or constant customization. If you don't program your text editor, just stay with what is comfortable.
As [previously stated][1], I have used the database to store the ViewState in the past. Although this works for us, we don't come close to 2 million unique visitors per hour. I think a hardware solution is definitely the way to go, whether using the [StrangeLoop][2] products or another product. [1]: http://s...
Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't ...
Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can...
Due to the typical organizational bloat, requesting new hardware takes eons, and requesting hardware that would involve a complete rewire of our current setup would probably get some severe resistance from the engineering department. I really need to come up with a software solution, because that's the only world I ...
First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review. If you're using a language with an existing standard (e.g. Java, C#), it's easiest to ...
SQL: Select like column from two tables
|sql|query|
I have a database with two tables (Table1 and Table2). They both have a common column [ColumnA] which is an nvarchar. How can I select this column from both tables and return it as a single column in my result set? So I'm looking for something like: ColumnA in Table1: a b c ColumnA in Ta...
I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. ...
When Management Studio does it, it's creating a temporary table, copying everything across, dropping your original table and renaming the temporary table. There's no simple equivalent T-SQL statement. If you don't fancy doing that, you could always create a view of the table with the columns in the order you'd like...
XML Editing/Viewing Software
|windows|linux|xml|
What software is recommended for working with and editing large XML schemas? I'm looking for both Windows and Linux software (doesn't have to be cross platform, just want suggestions for both) that help with dealing with huge XML files.
I may be old fashioned, but I prefer my text editor. I use emacs, and it has a fairly decent xml mode. Most good text editors will have decent syntax hi-lighting and tag matching facilities. Your IDE might already do it (IntelliJ idea does, and I believe Eclipse does as well). Good text editors will be able...
If the encoding is **base64** then this is the solution I've stumbled upon on the web [link][1] : "Decoding XDFL files saved with 'encoding=base64'. Files saved with: application/vnd.xfdl;content-encoding="base64-gzip" are simple base64-encoded gzip files. They can be easily restored to XML by first deco...
I usually do a project for the GUI a project for the business logic a project for data access and a project for unit tests. But sometimes it is prudent to have separation based upon services (if you are using a service oriented architecture) Such as Authentication, Sales, etc. I guess the rule of thumb that I wo...
Here's a dynamic sql script I've used in the past. It can be further modified but it will give you the basics. I prefer scripting it to avoid the mistakes you can make using the Management Studio: <pre><code> Declare @OldDB varchar(100) Declare @NewDB varchar(100) Declare @vchBackupPath varchar(255) Declare @q...
It would be nice to have a tool that could tell you exactly what all your layout problems are, but in this case the browser rendered the page exactly how it should have -- the combined width of the floats exceeded the width of the containing block, so the last one drops to a new line (this is slightly different than th...
Flex and .NET - What's a good way to get data into Flex, WebORB? Web Services?
|.net|apache-flex|
Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a .NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little ...
Java: Flash a window to grab user's attention
|java|user-interface|
Is there a better way to flash a window in Java than this: public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(f...
Is there a better way to flash a window in Java than this: public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(f...
If you are having trouble working out if the file is locked, try using [Unlocker][1] - it's a really useful free utility that shows you the process that has locked the file and lets you force an unlock if you need to. [1]: http://ccollomb.free.fr/unlocker/
> Is there a way to determine at what point I would encounter a stack overflow? Not really. A stack overflow happens when you exhaust the stack space - however... * The initial stack size can be changed programatically and may default to different amounts depending on your OS/compiler/etc * How much of it is alr...
Recursion is almost essential to traverse File structures like folder/directories. Traversing a tree like structure is very easy if recursion is used.
Sample code for reading and writing audio data here: <http://developer.apple.com/samplecode/SimplePlayThru/index.html#//apple_ref/doc/uid/DTS10003350> And of course lots of good information at <http://developer.apple.com/audio/>
Multiple threads stuck in native calls (Java)
|java|multithreading|blocked|native-methods|
I have a problem with an application running on Fedora Core 6 with JDK 1.5.0_08. After some amount of uptime (usually some days) threads begin getting stuck in native methods. The threads are locked in something like this: "pool-2-thread-2571" prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb...
Does silverlight work on chrome?
|silverlight|google-chrome|
Does anyone know if silverlight plugs into chrome, or when they plan to support it?
From [Joe Grossberg's blog][1]: > But if you're using GNU Emacs 21.2 > (the latest version, which includes > this as part of the standard distro), > you can just put the following lines > into your .emacs file > > ;; recentf stuff > (require 'recentf) > (recentf-mode 1) > (setq recentf-max-...
Parsing another webpage woulnd't be as bad (assuming their html woulnd't be very bad), but it would actually tie me to them - if they're down, I'm down :) Actually I found some old project on sourceforge: [rwhois.py][1]. What scares me a bit is that their last update is from 2003. But, it might seem as a good place...
You would use the Java Native Interface to call your C# code compiled into a DLL. If its a small amount of C#, it would be much easier to port it to Java. If its a lot, this might be a good way to do it. Here is a highlevel overview of it: http://en.wikipedia.org/wiki/Java_Native_Interface Your other option...
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works. You install a custom filter into django which gets the key of your dict as a parameter To make it work in google app-engine you need to add a file to your main directory, I called mine *django_hack.py* which c...
Unit Testing - PHPUnit [phpunit.de][1] ORM - Doctrine [phpdoctrine.org][2], Propel [propel.phpdb.org][3] [1]: http://www.phpunit.de/ [2]: http://www.phpdoctrine.org/ [3]: http://propel.phpdb.org/
DHCP overwrites Cisco VPN resolv.conf on Linux
|linux|vpn|cisco|
I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found <a href="http://projects.tuxx-home.at/?id=cisco_vpn_client">patches to update the client to compile on kernels released in the last two years</a>.) This all works great, until my DHCP ...
A lot of this is already available via JMX. With Java 5, JMX is built-in and they include a JMX console viewer with the JDK. You can use JMX to monitor manually, or invoke JMX commands from Java if you need this information in your own run-time.
I've tried to find some of the products I had researched in the past that works just like [StrangeLoops][1] (but software based) It looks like they went all out of business, the only thing from my list that still up there is [ScaleOut][2] but they are specialized in session state caching. I understand how hard it i...
I'm going to second Jason's suggestion. I just completed a standards document for a team of 10-12 that work mostly in perl. The document says to use "perltidy-like indentation for complex data structures." We also provided everyone with example perltidy settings that would clean up their code to meet this standard. ...
Coming from the automotive industry, here's a few style standards used for concrete reasons: Always used braces in control structures, and place them on separate lines. This eliminates problems with people adding code and including it or not including it mistakenly inside a control structure. if(...) { ...
I actually found it not even by searching, but by scanning through the ASP .NET forums in [this question][1]. Now, one thing of note is, if you give it one namespace and don't also include the second one that references higher, it doesn't seem to work. But from here, you can put in a directory under your controll...
I actually found it not even by searching, but by scanning through the ASP .NET forums in [this question][1]. Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you ne...
I think you might be overthinking this. There's a reason most systems just store addresses and maybe a table of countries. Here are some things to look out for: 1. Would an address in the Bronx include the borough as a level in the hierarchy? Would an address in an unincorporated area eliminate the "city" level of t...
[Beyond Compare][1] has been suggested a number of times to me. [1]: http://www.scootersoftware.com/
Someone else said this somewhere on here a few days ago, and I concur - use javascript to simply *hide* the button instead of disabling it; you could show a "spinner" image in its place, which lets the user know what is going on.
Silverlight already works with web-kit, and since Google's Chrome is based on web-kit, it shouldn't be too much effort to get it working. Indeed, <a href="http://bits.samiq.net/2008/09/silverlight-and-flash-running-on-google.html">this</a> gentleman seems to have had some success. Based on this, I would suspect t...
One thing - if speed is important and your code doesn't need to be portable, then it may be worth it to use the native libraries. I don't know much about SQL Server, but I do know that the Oracle OCI calls are faster than using ODBC. But, they tie you to Oracle's version of SQL. It would make sense for SQL Server t...
Calling C# code from Java?
Glade or no glade: What is the best way to use PyGtk?
|python|gtk|pygtk|glade|
I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm...
First make a string with all your possible characters: $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; You could also use [range()][1] to do this more quickly. Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your s...
PHP + MySql + Stored Procedures, how do I get access an "out" value?
|php|mysql|stored-procedures|mysqli|
Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?
I'm going to see if I can come up with a way to leverage our current State server to contain the viewstate in memory, I should be able to use the user session ID to keep things synched up between machines. If I come up with a good solution, I'll remove any IP protected code and put it out for public use.
If you are running without NetworkManager handling the connections, use the resolvconf package to act as an intermediary to programs tweaking /etc/resolv.conf: **`sudo apt-get install resolvconf`** If you are using NetworkManager it will handle this for you, so get rid of the resolvconf package: **`sudo apt-get remo...
How do you handle Session State? There is a built-in "store the viewstate in the session state" provider. If you are storing the session state in some fast, out of proc system, that might be the best option for the viewstate. edit: to do this add the following code to the your Page classes / global page base class...
You'll want to use absolute URLs to link out to images on a server. Users won't want to download your attachments. Also most email clients will not displays images by default, so it's a good idea to keep the really important content as text. Email clients generally all use very different rendering methods. For examp...
C++ and SOAP
|java|c++|soap|
I have a C++ app that needs to connect to a JAVA web app, are there any good, open source SOAP packages for this, or would it be easier to just roll my own?
I want to emphasize Brian's point in his comment, because it is important. Finalizers are not deterministic destructors like in C++. As others have pointed out, there is no guarantee of when it will be called, and indeed if you have enough memory, if it will *ever* be called. But the bad thing about finalizers is...
This is not a design document, per se, but our **unit tests** serve the dual purpose of "describing" how the code they test is supposed to function. The nice part about this is that they **never get out of date**, since our unit tests must pass for our build to succeed.
|java|c#|java-native-interface|
Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stu...
|c#|java|java-native-interface|
Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stu...
See this example for disabling control on postback. It should help you do what you're trying to achieve. http://encosia.com/2007/04/17/disable-a-button-control-during-postback/
There is an IL to Java Bytecode compiler [GrassHopper][1] which may be of use to you. I've never tried it though. I'd look at rewriting your code in Java though [1]: http://dev.mainsoft.com/Default.aspx?tabid=130
The attributes... position: fixed; left: 0; bottom: 0; ...should do the job in every browser except IE. If supporting IE users is important for your site, you need to add some ugly Javascript.
Comparing two collections for equality
|collections|comparison|equality|
I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently. I've read the other thread about [Enumerable.SequenceEqual][1], but it's not exactly what I'm looking for. In my case, two collections would be equal if they both contain the same items (no matter the ...
You can try this [recipe on Active State][1]. There is also a [DBFReader module][2] which you can try. For support for [memo fields][3]. [1]: http://code.activestate.com/recipes/362715/ [2]: http://www.garshol.priv.no/download/software/python/dbfreader.py [3]: http://www.physics.ox.ac.uk/users/santo...
as others have said, hot-backup.py from the Subversion team has some nice features over just plain <code>svnadmin hotcopy</code> I run a scheduled task on a python script that spiders for all my repositories on the machine, and uses hotbackup to keep several days worth of hotcopies (paranoid of corruption) and an <c...
Adding server-side event to extender control
|asp.net|.net-3.5|