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 often you'll have all of them before that. |
@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 that (x+1) is NOT divisible by 8. Is that what you want? (I assume it is, but just want to confirm.) |
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 good answers to this question.
(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.) |
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 query (hql vs. Criteria vs. Linq2NH), expose intention-revealing methods (`GetProductsForOrder(Order order)`, `GetCustomersThatPurchasedProduct(Product product)`, etc) on your repository interface and implement them in the best way. Simple queries may be easier with hql, while using the specification pattern you may find the Criteria API to be a better fit. That stuff just stays encapsulated in your repository, and if your tests pass it doesn't much matter how you implement.
I've found that the Criteria API is cumbersome and limiting but flexible. HQL is more my style (and it's better than SQL - it's object based, not schema based) and seems to work better for me for simple GetX methods.. |
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://stackoverflow.com/questions/48026/good-book-on-scaling-aspnet-applications#48052
[2]: http://www.strangeloopnetworks.com/ |
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 have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code. |
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 get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder.
Still, there is a small branch of number theory devoted to [Modular Arithmetic][1] which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating [magic squares][2].
So, in that vein, here's a [very low level look][3] at the math of modulus for an example of x, which should show you how simple it can be compared to division.
<pre>Maybe a better way to think about the problem is in terms of number
bases and modulo arithmetic. For example, your goal is to compute DOW
mod 7 where DOW is the 16-bit representation of the day of the
week. You can write this as:
DOW = DOW_HI*256 + DOW_LO
DOW%7 = (DOW_HI*256 + DOW_LO) % 7
= ((DOW_HI*256)%7 + (DOW_LO % 7)) %7
= ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7
= ((DOW_HI%7 * 4) + (DOW_LO%7)) %7
Expressed in this manner, you can separately compute the modulo 7
result for the high and low bytes. Multiply the result for the high by
4 and add it to the low and then finally compute result modulo 7.
Computing the mod 7 result of an 8-bit number can be performed in a
similar fashion. You can write an 8-bit number in octal like so:
X = a*64 + b*8 + c
Where a, b, and c are 3-bit numbers.
X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7
= (a%7 + b%7 + c%7) % 7
= (a + b + c) % 7
since 64%7 = 8%7 = 1
Of course, a, b, and c are
c = X & 7
b = (X>>3) & 7
a = (X>>6) & 7 (actually, a is only 2-bits).
The largest possible value for a+b+c is 7+7+3 = 17. So, you'll need
one more octal step. The complete (untested) C version could be
written like:
unsigned char Mod7Byte(unsigned char X)
{
X = (X&7) + ((X>>3)&7) + (X>>6);
X = (X&7) + (X>>3);
return X==7 ? 0 : X;
}
I spent a few moments writing a PIC version. The actual implementation
is slightly different than described above
Mod7Byte:
movwf temp1 ;
andlw 7 ;W=c
movwf temp2 ;temp2=c
rlncf temp1,F ;
swapf temp1,W ;W= a*8+b
andlw 0x1F
addwf temp2,W ;W= a*8+b+c
movwf temp2 ;temp2 is now a 6-bit number
andlw 0x38 ;get the high 3 bits == a'
xorwf temp2,F ;temp2 now has the 3 low bits == b'
rlncf WREG,F ;shift the high bits right 4
swapf WREG,F ;
addwf temp2,W ;W = a' + b'
; at this point, W is between 0 and 10
addlw -7
bc Mod7Byte_L2
Mod7Byte_L1:
addlw 7
Mod7Byte_L2:
return
Here's a liitle routine to test the algorithm
clrf x
clrf count
TestLoop:
movf x,W
RCALL Mod7Byte
cpfseq count
bra fail
incf count,W
xorlw 7
skpz
xorlw 7
movwf count
incfsz x,F
bra TestLoop
passed:
Finally, for the 16-bit result (which I have not tested), you could
write:
uint16 Mod7Word(uint16 X)
{
return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4);
}
Scott</pre>
[1]: http://en.wikibooks.org/wiki/Discrete_mathematics/Modular_arithmetic
[2]: http://www.math.utah.edu/~carlson/mathcircles/magic.pdf
[3]: http://piclist.org/techref/postbot.asp?by=time&id=piclist/2006/08/03/065022a |
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 have some control over.
Yay for Enterprise :( |
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 use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.
In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having <i>any</i> standard is the key. |
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 Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
|
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. Your queries should return very few rows but contain (potentially) many datapoints.
Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things.
For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article: [Matching Impedance: When to use HBase][1] by Bryan Duxbury.
[1]: http://blog.rapleaf.com/dev/?p=26 |
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 and use that?
Edit: beaten! |
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 to deal with *huge* files, but some text editors may not be able to handle them. How big are we talking about? |
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 decoding and then unzipping them. This can be done as follows on Ubuntu:
sudo apt-get install uudeview uudeview -i yourform.xfdl gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xfdl
The first command will install uudeview, a package that can decode base64, among others. You can skip this step once it is installed.
Assuming your form is saved as 'yourform.xfdl', the uudeview command will decode the contents as 'UNKNOWN.001', since the xfdl file doesn't contain a file name. The '-i' option makes uudeview uninteractive, remove that option for more control.
The last command gunzips the decoded file into a file named 'yourform-unpacked.xfdl'.
"
**Another** possible solution - [here](http://www.chilkatsoft.com/p/p_531.asp)
*Side Note: Block quoted < code > doesn't work for long strings of code*
[1]: http://www.suares.an/ |
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 work off of is that if you can see it as a component that has a clear separation of concerns then a different project could be prudent. But I would think that folders versus projects could just be a preference or philosophy.
I personally feel that if reusable code is split into projects it is simpler to use other places than if it is just in folders. |
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 @query varchar(8000)
/*Test code to implement
Select @OldDB = 'Pubs'
Select @NewDB = 'Pubs2'
Select @vchBackupPath = '\\dbserver\C$\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\pubs.bak'
*/
SET NOCOUNT ON;
Select @query = 'Create Database ' + @NewDB
exec(@query)
Select @query = '
Declare @vBAKPath varchar(256)
declare @oldMDFName varchar(100)
declare @oldLDFName varchar(100)
declare @newMDFPath varchar(100)
declare @newLDFPath varchar(100)
declare @restQuery varchar(800)
select @vBAKPath = ''' + @vchBackupPath + '''
select @oldLDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.ldf%''
select @oldMDFName = name from ' + @OldDB +'.dbo.sysfiles where filename like ''%.mdf%''
select @newMDFPath = physical_name from ' + @NewDB +'.sys.database_files where type_desc = ''ROWS''
select @newLDFPath = physical_name from ' + @NewDB +'.sys.database_files where type_desc = ''LOG''
select @restQuery = ''RESTORE DATABASE ' + @NewDB +
' FROM DISK = N'' + '''''''' + @vBAKpath + '''''''' +
'' WITH MOVE N'' + '''''''' + @oldMDFName + '''''''' +
'' TO N'' + '''''''' + @newMDFPath + '''''''' +
'', MOVE N'' + '''''''' + @oldLDFName + '''''''' +
'' TO N'' + '''''''' + @newLDFPath + '''''''' +
'', NOUNLOAD, REPLACE, STATS = 10''
exec(@restQuery)
--print @restQuery'
exec(@query)
</code></pre> |
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 the IE6 expanding box/float drop problem which is typically caused by content inside the float, not the floats themselves). So in this case, there was nothing wrong with your page.
Debugging this is simply a matter of walking through your HTML in Firebug and figuring out which children of a block is exceeding the block's width. Firebug provides plenty of information for this purpose, although sometimes I need to use a calculator. I think what you described about being able to see which elements constrain other elements would simply be too complex and overwhelming, especially for elements that are removed from normal flow (such as floats or positioned elements).
Also, a deeper understanding of how CSS layout helps a lot as well. It can get pretty complicated.
For example, it is generally recommended to assign explicit widths to floated elements -- the W3C CSS2 spec states that floats need to have an explicit width, and does not provide instructions of what to do without it. I think most modern browsers use the "shrink to fit" method, and will constrain themselves to the width of the content. However, this is not guaranteed in older browsers, and in something like a 3-column layout, you'll be at the mercy of at the width of content inside the floats.
Also, if you're striving for IE6 compatibility, there are a number of [float related bugs](http://www.positioniseverything.net/explorer/expandingboxbug.html) that could also cause similar problems. |
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 about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative? |
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(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
I know that this code is scary...But it works alright. |
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(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
I know that this code is scary...But it works alright. (I should implement a loop...) |
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 already used up depends on what your app (and the libraries your app uses) has previously done - this is often impossible to predict
* How much of the stack each call requires depends on what you do in your function. If you only allocate say 1 integer on the stack, you may be able to recurse an enourmous amount of times, but if you are allocating a 200k buffer on the stack, not so much.
The only times I've ever hit one is in an infinite loop, or using the aforementioned 200k buffer.
I find it far more prefereable for my app to just crash, than for it to loop forever using 100% CPU and have to be forcefully killed (this is a right PITA on a remote server over a bad connection as windows lacks SSH)
A rough guideline: Do you think your recursive function is likely to call itself more than say 10,000 times consecutively? Or are you doing something dumb like allocating 200k buffers on the stack?
If yes, worry about it.
If no, carry on with more important things. |
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 [0xb91fe000..0xb91ff7d4]
at java.lang.Class.getDeclaredConstructors0(Native Method)
or
"pool-2-thread-2547" prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554]
at sun.misc.Unsafe.defineClass(Native Method)
Especially puzzling to me is this one:
"HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4]
at java.lang.Thread.dumpThreads(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1383)
The threads remain stuck until the VM is restarted.
Can anyone give me an idea as to what is happening here, what might be causing the native methods to block?
The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor?
Any suggestions or advice will be greatly appreciated!
Thanks,
David |
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-menu-items 25)
> (global-set-key "\C-x\ \C-r" 'recentf-open-files)
>
> Then, when you launch emacs, hit
> CTRL-X CTRL-R. It will show a list of
> the recently-opened files in a buffer.
> Move the cursor to a line and press
> ENTER. That will open the file in
> question, and move it to the top of
> your recent-file list.
>
> (Note: Emacs records file names.
> Therefore, if you move or rename a
> file outside of Emacs, it won't
> automatically update the list. You'll
> have to open the renamed file with the
> normal CTRL-X CTRL-F method.)
>
> Jayakrishnan Varnam has a [page
> including screenshots][2] of how this
> package works.
[1]: http://www.joegrossberg.com/archives/000182.html
[2]: http://varnam.org/e-recentf.html |
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 to start reimplementation of what I do right now... Well, I felt obligued to post the link to this project anyway, just for further reference.
[1]: http://sourceforge.net/projects/rwhois/ |
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 would be to create a COM assembly from the C# code and use J-Interop to invoke it.
http://sourceforge.net/projects/j-interop/
|
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 contains this little piece of code
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file
webapp.template.register_template_library('django_hack')
and in your template view add this template instead of the usual code
{{ user|hash:item }}
And its should work perfectly =) |
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 client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers.
Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active? |
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 is to sell hardware solutions to senior management but it is always a good idea to at least get management to accept listening to the hardware's sales rep. I am much rather putting some hardware that will present me with an immediate solution because it allows me (or buy me some time) to get some other real job done.
I understand, it really sucks but the alternative is to change your code for optimization and that would maybe cost a lot more than getting an appliance.
Let me know if you find another software based solution.
[1]: http://www.strangeloopnetworks.com/products/AS1000/default.aspx
[2]: http://www.scaleoutsoftware.com/ |
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. It was very clear and very much industry-standard for the language so we had great buyoff on it by the team.
When setting out to write this document, I asked around for some examples of great code in our repository and googled a bit to find other standards documents that smarter architects than I to construct a template. It was tough being concise and pragmatic without crossing into micro-manager territory but very much worth it; having *any* standard is indeed key.
Hope it works out! |
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(...)
{
}
All switches/selects have a default case. The default case logs an error if it's not a valid path.
For the same reason as above, any if...elseif... control structures MUST end with a default else that also logs an error if it's not a valid path. A single if statement does not require this.
In the occasional case where a loop or control structure is intentionally empty, a semicolon is always placed within to indicate that this is intentional.
while(stillwaiting())
{
;
}
Naming standards have very different styles for typedefs, defined constants, module global variables, etc. Variable names include type. You can look at the name and have a good idea of what module it pertains to, its scope, and type. This makes it easy to detect errors related to types, etc.
There are others, but these are the top off my head.
-Adam |
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 controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1"
Then this works:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var shop1namespace = new RouteValueDictionary();
shop1namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop1",
"MyWebShop.Controllers"
}));
routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop1namespace
});
var shop2namespace = new RouteValueDictionary();
shop2namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop2",
"MyWebShop.Controllers"
}));
routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop2namespace
});
routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" })
});
}
The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller.
[1]: http://forums.asp.net/t/1296928.aspx?PageIndex=1 |
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 need be!)
But from here, you can put in a directory under your controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1"
Then this works:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var shop1namespace = new RouteValueDictionary();
shop1namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop1"
}));
routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop1namespace
});
var shop2namespace = new RouteValueDictionary();
shop2namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop2"
}));
routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop2namespace
});
var defaultnamespace = new RouteValueDictionary();
defaultnamespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers"
}));
routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
DataTokens = defaultnamespace
});
}
The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller.
[1]: http://forums.asp.net/t/1296928.aspx?PageIndex=1 |
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 the hierarchy? How do you model an address within a university vs an address that's not within one? You'll end up with a ragged hierarchy which will force you to traverse the tree every time you need to display an address in your application. If you have an "address book" page the performance hit could be significant.
2. I'm not sure that you even have just one hierarchy. Brown University has facilities in Providence, RI and Bristol, RI. The only clean solution would be to have a double hierarchy with two campuses that each belong to their respective cities in one hierarchy but that both belong to Brown University on the other hierarchy. (A university is fundamentally unlike a political region. You shouldn't really mix them.)
3. What about zip codes? Some zip codes encompass multiple towns, other times a city is broken into multiple zip codes. And (rarely) some zip codes even cross state lines. (According to Wikipedia, at least...)
4. How will you enter the data? Building out the database by parsing conventionally-formatted addresses can be difficult when you take into account vanity addresses, alternate names for certain streets, different international formats, etc. And I think that entering every address hierarchically would be a PITA.
5. It sounds like you're trying to model the entire world in your application. Do you really want or need to maintain a table that could conceivable contain every city, state, province, postal code, and country in the world? (Or at least every one where you know somebody?) The only thing I can think of that this scheme would buy you is proximity, but if that's what you want I'd just store state and country separately (and maybe the zip code) and add latitude and longitude data from Google.
Sorry for the extreme pessimism, but I've gone down that road myself. It's logically beautiful and elegant, but it doesn't work so well in practice. |
[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 that Silverlight will be fully supported by Chrome by the time it goes gold. |
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 to be the same way.
|
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 just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem). |
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 string:
$string = '';
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
$random_string_length is the length of the random string.
[1]: http://php.net/range |
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 remove resolvconf`**
I found out about this when setting up vpnc on Ubuntu last week. A search for **`vpn resolv.conf`** on ubuntuforums.org has 250 results, many of which are very related! |
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
protected override PageStatePersister PageStatePersister {
get { return new SessionPageStatePersister(this); }
}
Also... this is by no means a perfect (or even good) solution to a large viewstate. As always, minimize the size of the viewstate as much as possible. However, the SessionPageStatePersister is relatively intelligent and avoids storing an unbounded number of viewstates per session as well as avoids storing only a single viewstate per session. |
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 example, Outlook 2007 uses Word's HTML rendering engine, whereas previous versions used Internet Explorer.
Do be aware that CSS support is also very limited to in emails. Most clients, especially web mail, will strip out everything outside of the <body> tag, as well as <style> tags. This means that external or embedded CSS will not work, and that inline styles are the safest bet (the style="" attribute). There is also poor support for many CSS rules in Outlook 2007. This means that a lot people have returned to using tables for laying out email.
As it was pointed out, Campaign Monitor is an excellent resource, and I especially recommend their [CSS Compatibility Chart](http://www.campaignmonitor.com/css/) |
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 that, as Brian said, it causes your object to survive a garbage collection. This can be bad. Why?
As you may or may not know, the GC is split into generations - Gen 1, 2 and 3, plus the Large Object Heap. Split is a loose term - you get one block of memory, but there are pointers of where the Gen 1 objects start and end.
The thought process is that you'll likely use lots of objects that will be short lived. So those should be easy and fast for the GC to get to - Gen 1 objects. So when there is memory pressure, the first thing it does is a Gen 1 collection.
Now, if that doesn't resolve enough pressure, then it goes back and does a Gen 2 sweep (redoing Gen 1), and then if still not enough, it does a Gen 3 sweep (redoing Gen 2 and Gen 1). So cleaning up long lived objects can take a while and be rather expensive (since your threads may be suspended during the operation).
This means that if you do something like this:
~MyClass() { }
Your object, no matter what, will live to Generation 2. This is because the GC has no way of calling the finalizer during garbage collection. So objects that have to be finalized are moved to a special queue to be cleaned out by a different thread (the finalizer thread - which if you kill makes all kinds of bad things happen). This means your objects hang around longer, and potentially force more garbage collections.
So, all of that is just to drive home the point that you want to use IDisposable to clean up resources whenever possible and seriously try to find ways around using the finalizer. It's in your application's best interests. |
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 stuff in there, so I would rather keep it tightly integrated if possible.
|
|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 stuff in there, so I would rather keep it tightly integrated if possible.
---
Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.
|
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 order).
Example:
collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).
if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.
An example I can think of that would be wrong is:
collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?
---
The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.
[1]: http://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c |
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/santoso/dbf.py.src |
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 <code>svnadmin svndump</code> on a remote machine. Restoration is really easy from that - so far. |
Adding server-side event to extender control |
|asp.net|.net-3.5| |