Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?...
There is an actual Data Type called KeyValuePair, use like this ``` KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue"); ```
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications: ``` public class TokenTree : Dictionary<string, string> { public IDictionary<string, string> SubPairs; } ``` This gives you the advantage of not having to enforce the rules of ...
Best implementation for Key Value Pair Data Structure?
[ "", "c#", "data-structures", "collections", "" ]
It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when woul...
Hank Shiffman from SGI said (a long time ago, but it's till true): > There are three advantages of Java > using byte code instead of going to > the native code of the system: > > 1. **Portability**: Each kind of computer has its unique instruction > set. While some processors include the > instructions for their...
The performance of essentially any program will improve if it is compiled, executed with profiling, and the results fed back into the compiler for a second pass. The code paths which are actually used will be more aggressively optimized, loops unrolled to exactly the right degree, and the hot instruction paths arranged...
What are advantages of bytecode over native code?
[ "", "java", ".net", "bytecode", "" ]
I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation? > Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGm...
In C# `#define` macros, like some of Bernard's examples, are not allowed. The only common use of `#define`/`#if`s in C# is for adding optional debug only code. For example: ``` static void Main(string[] args) { #if DEBUG //this only compiles if in DEBUG Console.WriteLine("DEBUG"...
#define is used to define compile-time constants that you can use with #if to include or exclude bits of code. ``` #define USEFOREACH #if USEFOREACH foreach(var item in items) { #else for(int i=0; i < items.Length; ++i) { var item = items[i]; //take item #endif doSomethingWithItem(item);...
How do you use #define?
[ "", "c#", "" ]
I'm setting up a web application with a FreeBSD PostgreSQL back-end. I'm looking for some database performance optimization tool/technique.
[pgfouine](http://pgfouine.projects.postgresql.org/) works fairly well for me. And it looks like there's a [FreeBSD port](http://portsmon.freebsd.org/portoverview.py?category=databases&portname=pgfouine) for it.
Database optimization is usually a combination of two things 1. Reduce the number of queries to the database 2. Reduce the amount of data that needs to be looked at to answer queries Reducing the amount of queries is usually done by caching non-volatile/less important data (e.g. "Which users are online" or "What are ...
PostgreSQL performance monitoring tool
[ "", "sql", "database", "optimization", "postgresql", "freebsd", "" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class Downlo...
You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do ``` class Foo(object): class __metaclass__(type): .... ``` instead of defining a metaclass separately, if you're o...
I don't know Python, but your question seems very general. Ignore me if it's specific to Python. Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class. It is a common pattern make helper c...
Is there a benefit to defining a class inside another class in Python?
[ "", "python", "oop", "" ]
Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results. What's a good algorithm to implement this pattern without bringing the entire table to the cl...
On MS SQL Server 2005 and above, [ROW\_NUMBER()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) seems to work: [T-SQL: Paging with ROW\_NUMBER()](http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx) ``` DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN...
I'd recommend either using LINQ, or try to copy what it does. I've got an app where I use the LINQ Take and Skip methods to retrieve paged data. The code looks something like this: ``` MyDataContext db = new MyDataContext(); var results = db.Products .Skip((pageNumber - 1) * pageSize) .Take(pageSize); ``` Run...
How to return a page of results from SQL?
[ "", ".net", "sql", "linq", "pagination", "" ]
I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below: <http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx> <http://blogs.msdn.com/larryosterman/ar...
Not really, at least, not last time I looked. I mean, boost::thread\_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think. Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is goin...
I haven't seen anything in boost that helps with the structure that you tend to end up with when using IO Completion Ports, but then I haven't looked that recently... However, slightly off-topic, you might like to take a look at the IOCP based thread pool that is part of my free IOCP server framework. It might give you...
Task oriented thread pooling
[ "", "c++", "multithreading", "boost", "" ]
When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume th...
To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. ``` void SomethingHappened(object se...
Here are the salient points: 1. You can't make UI control calls from a different thread than the one they were created on (the form's thread). 2. Delegate invocations (ie, event hooks) are triggered on the same thread as the object that is firing the event. So, if you have a separate "engine" thread doing some work a...
How do I make event callbacks into my win forms thread safe?
[ "", "c#", ".net", "winforms", "multithreading", "events", "" ]
When I call `socket.getsockname()` on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?
This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.
The only way I can think of that's guaranteed to give it to you is to hit a service like <http://whatismyip.com/> to get it.
How do I get the external IP of a socket in Python?
[ "", "python", "sockets", "" ]
How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, b...
You can use [serialization](http://msdn.microsoft.com/en-us/library/ms973893.aspx) - it allows you to store your object at least in 3 forms: binary (suitable for BLOBs), XML (take advantage of MSSQL's XML data type) or just plain text (store in varchar or text column)
Before you head down this road towards your own eventual insanity, you should take a look at this (or one day repeat it): <http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx> Persisting objects in a database is not a good idea. It kills all the good things that a database is designed to do.
vb.net object persisted in database
[ "", "sql", "vb.net", "serialization", "" ]
If I remove all the ' characters from a SQL query, is there some other way to do a SQL injection attack on the database? How can it be done? Can anyone give me examples?
Yes, there is. An excerpt from [Wikipedia](http://en.wikipedia.org/wiki/SQL_injection) `"SELECT * FROM data WHERE id = " + a_variable + ";"` It is clear from this statement that the author intended a\_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manip...
Yes, depending on the statement you are using. You are better off protecting yourself either by using Stored Procedures, or at least parameterised queries. See [Wikipedia](http://en.wikipedia.org/wiki/SQL_injection#Preventing_SQL_Injection) for prevention samples.
Is there some way to inject SQL even if the ' character is deleted?
[ "", "sql", "database", "sql-injection", "" ]
Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
The [`dis`](https://docs.python.org/3/library/dis.html) module disassembles the byte code for a function and is useful to see the difference between tuples and lists. In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list. ``` >>> ...
## Summary *Tuples tend to perform better than lists* in almost every category: 1. Tuples can be [constant folded](https://en.wikipedia.org/wiki/Constant_folding). 2. Tuples can be reused instead of copied. 3. Tuples are compact and don't over-allocate. 4. Tuples directly reference their elements. ## Tuples can be c...
Are tuples more efficient than lists in Python?
[ "", "python", "performance", "list", "tuples", "python-internals", "" ]
I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer. ...
Have you considered matching the actual possible keywords? such as: ``` (?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)* ``` It might be a bit more likely to match correctly, though it might also make the regex harder to read...
``` (public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;]) ``` I think that the above regexp can match almost all possible combinations of Java method declarations, even those including generics and arrays are return arguments, which the regexp provided by the original author did not match...
Regex that Will Match a Java Method Declaration
[ "", "java", "regex", "methods", "" ]
Why is `Array.Length` an int, and not a `uint`. This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use f...
Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a `UInt`. See here: Framework 1.1 > [Introduction to the .NET Framework Class Library](http://msdn.microsoft.com/en-us/library/hfa3fa08(VS.71).aspx) Framework 2.0 > [.NET Framework Class Library...
Many reasons: * uint is not CLS compliant, thus making a built in type (array) dependent on it would have been problematic * The runtime as originally designed prohibits any object on the heap occupying more than 2GB of memory. Since the maximum sized array that would less than or equal to this limit would be new byte...
Why is Array.Length an int, and not an uint
[ "", "c#", ".net", "int", "uint", "" ]
Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness.
Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8). To quote: > <http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx> > > The CLS was designed to b...
Part of the issue, I suspect, revolves around the fact that unsigned integer types in C are required to behave as members of an abstract algebraic ring rather than as numbers [meaning, for example, that if an unsigned 16-bit integer variable equals zero, decrementing it is *required* to yield 65,535, and if it's equal ...
Why are unsigned int's not CLS compliant?
[ "", "c#", ".net", "unsigned-integer", "cls-compliant", "" ]
I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING\_DETAILS table that all re...
You defined the primary key twice. Try: ``` CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL ...
> Can you provide the definition of the > VENDOR table I figured it out. The VENDOR table was MyISAM... (edited your answer to tell me to make them both INNODB ;) ) (any reason *not* to just switch the VENDOR type over to INNODB?)
Multiple foreign keys?
[ "", "sql", "mysql", "foreign-keys", "" ]
As everyone knows, the [Visual C++](http://en.wikipedia.org/wiki/Visual_C%2B%2B) runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null...
It is not the responsibility of `delete` to reset all the pointers to the object to `NULL`. Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like `boost::shared_ptr<>` for pointers any way. That said, if you really want to **shoot your self in the foot** you...
When you create a pointer, explicity initialize it to `NULL`. Likewise after a `delete`. Depending on the value of uninitialized data (except in a few specific cases) is asking for trouble. You can save yourself a lot of headaches by using a smart pointer class (such as [`boost::shared_ptr`](http://www.boost.org/doc/l...
Uninitialized memory blocks in VC++
[ "", "c++", "memory", "allocation", "" ]
I want to generate a thumbnail preview of videos in Java. I'm mostly JMF and video manipulation alienated. * Is there an easy way to do it? * What about codecs? Will I have to deal with it? * Any video type is suported? (including Quicktime)
There seems to be a few examples out there that are far better than [what I was going to send you.](http://code.google.com/p/vitalopensource/source/browse/trunk/src/com/vtls/opensource/image/VideoImageSource.java) See <http://krishnabhargav.blogspot.com/2008/02/processing-videos-in-java.html>. I'd agree with Stu, how...
Well, since you're not stuck with JMF, have you considered [Xuggler](http://www.xuggle.com/xuggler)? Xuggler is a Java API that uses FFmpeg under the covers to do all video decoding and encoding. It's free and LGPL licensed. In fact, we have a tutorial that shows [How to Make Thumbnails of an Existing File](http://bui...
Video Thumbnails in Java
[ "", "java", "video", "jmf", "" ]
I'm looking at parsing a delimited string, something on the order of a,b,c But this is a very simple example, and parsing delimited data can get complex; for instance 1,"Your simple algorithm, it fails",True would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy an...
I use this to read from a file ``` string filename = @textBox1.Text; string[] fields; string[] delimiter = new string[] {"|"}; using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) { parser.Delimiters = delimiter; parser.HasFieldsEnclose...
I am not aware of any framework, but a simple state machine works: * State 1: Read every char until you hit a " or a , + In case of a ": Move to State 2 + In case of a ,: Move to State 3 + In case of the end of file: Move to state 4 * State 2: Read every char until you hit a " + In case of a ": Move to State 1...
Delimited string parsing?
[ "", "c#", "text-parsing", "csv", "" ]
I've been looking for this information for my commercial desktop product, with no avail. Specifically, what I'm look for, is deployment statistics of the .NET framework for end-users (both granny "I'm just browsing the internet" XP, and high-end users, if possible), and in the commercial/business sector. Edit: Other ...
Some statistics from 2005 I found at [Scott Wiltamuth's blog](http://blogs.msdn.com/scottwil/archive/2005/03/09/391199.aspx) (you can be sure these numbers are much higher now): * More than 120M copies of the .NET Framework have been downloaded and installed using either Microsoft downloads or Windows Update * More th...
I don't have any hard numbers, but these days, it is pretty safe to assume most Windows XP and Vista users have at least .NET 2.0. I believe this was actually dropped via Windows Update for XP, and Vista came with at least 2.0 (apparently with 3.0 as pointed out in the comments to this answer).
What is the deployment rate of the .NET framework?
[ "", "c#", ".net", "deployment", "statistics", "" ]
Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?
Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap. Structs can also contain class definitions as members (inner classes). Here's some really useless code that at least compiles and runs to show that i...
The class content gets stored on the heap. A reference to the class (which is almost the same as a pointer) gets stored with the struct content. Where the struct content is stored depends on whether it's a local variable, method parameter, or member of a class, and whether it's been boxed or captured by a closure.
Can you have a class in a struct?
[ "", "c#", "class", "struct", "value-type", "reference-type", "" ]
How do I create class (i.e. [static](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods)) variables or methods in Python?
Variables declared inside the class definition, but not inside a method are class or static variables: ``` >>> class MyClass: ... i = 3 ... >>> MyClass.i 3 ``` As @[millerdev](https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067) points out, this creates a class-level `i` variab...
@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables: ``` >>> class Test(object): ... i = 3 ... >>> Test.i 3 ``` There are a few gotcha's here. Carrying on from the example above: ``` >>> t = Test() >>> t.i # "static" variable acces...
Class (static) variables and methods
[ "", "python", "class", "static", "class-variables", "" ]
If I pass request fields or cookies with a period/dot in their names, PHP auto-replaces them with underscores. For example, if I put this code at `https://example.com/test.php?x.y=a.b`: ``` <?php echo $_SERVER['REQUEST_URI']; echo $_GET['x.y']; echo $_GET['x_y']; ``` the output is: ``` /test.php?x.y=a.b a.b ``` Is...
Here's PHP.net's explanation of why it does it: > ### Dots in incoming variable names > > Typically, PHP does not alter the > names of variables when they are > passed into a script. However, it > should be noted that the dot (period, > full stop) is not a valid character in > a PHP variable name. For the reason, > lo...
Long-since answered question, but there is actually a better answer (or work-around). PHP lets you at the [raw input stream](http://php.net/manual/en/wrappers.php.php), so you can do something like this: ``` $query_string = file_get_contents('php://input'); ``` which will give you the $\_POST array in query string fo...
How to stop PHP replacing dot characters in GET, POST, or COOKIE names?
[ "", "php", "" ]
Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. Consider this code... ``` fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } ``` compared to simply using... ``` Array....
It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory. If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom mars...
I've used unsafe-blocks to manipulate Bitmap-data. Raw pointer-access is significantly faster than SetPixel/GetPixel. ``` unsafe { BitmapData bmData = bm.LockBits(...) byte *bits = (byte*)pixels.ToPointer(); // Do stuff with bits } ``` "fixed" and "unsafe" is typically used when doing interop, or when ext...
C# Unsafe/Fixed Code
[ "", "c#", ".net", "unsafe", "fixed", "" ]
Is there a way to get the tests inside of a `TestCase` to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests.
Maybe there is a design problem in your tests. Usually each test must not depend on any other tests, so they can run in any order. Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests. Can you be more specif...
PHPUnit supports test dependencies via the [@depends](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.test-dependencies) annotation. Here is an example from the documentation where tests will be run in an order that satisfies dependencies, with each dependent test passing ...
Run PHPUnit Tests in Certain Order
[ "", "php", "unit-testing", "phpunit", "" ]
I have recently written an application(vb.net) that stores and allows searching for old council plans. Now while the application works well, the other day I was having a look at the routine that I use to generate the SQL string to pass the database and frankly, it was bad. I was just posting a question here to see if...
When programming complex ad-hoc query type things, attributes can be your best friend. Take a more declarative approach and decorate your classes, interfaces, and/or properties with some custom attributes, then write some generic "glue" code that binds your UI to your model. This will allow your model and presentation ...
You could maybe wrap each control in a usercontrol that can take in IQueryable and tack on to the query if it is warranted. So your page code might go something like ``` var qry = from t in _db.TableName select t; ``` then pass qry to a method on each user control ``` IQueryable<t> addToQueryIfNeeded(IQueryab...
Generate LINQ query from multiple controls
[ "", "sql", "linq", "" ]
Simply, are there any Java Developer specific Linux distros?
A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as...
Dont listen to any of these noobs suggesting one distro over another. Java is Java and just about all distros can install java as such: ``` [package manager command to install] jdk ``` If the question was about creating RPM's, then obviously RH/CentOS/Fedora would be desirable over deb distros, source distros, or wha...
Linux distros for Java Development
[ "", "java", "linux", "distro", "" ]
What does the option “convert to web application” do if I select it in visual studio? If I do convert my site to a web application what are the advantages? Can I go back?
Well, it converts your web site to a web application project. As for the advantages, here is some further reading: MSDN comparison -- [Comparing Web Site Projects and Web Application Projects](http://msdn.microsoft.com/en-us/library/aa730880(VS.80).aspx#wapp_topic5) Webcast on ASP.NET -- [Web Application Projects vs....
[Also Answered Here](https://stackoverflow.com/questions/43019/what-does-vs-2008s-convert-to-website-mean) so go vote that answer up, not this one. **Don't give me credit** > There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here:...
What does the option "convert to web application" do if I select it in visual studio?
[ "", "c#", "asp.net", "visual-studio", "" ]
Is there an incantation of mysqldump or a similar tool that will produce a piece of SQL2003 code to create and fill the same databases in an arbitrary SQL2003 compliant RDBMS? (The one I'm trying right now is MonetDB)
DDL statements are inherently database-vendor specific. Although they have the same basic structure, each vendor has their own take on how to define types, indexes, constraints, etc. DML statements on the other hand are fairly portable. Therefore I suggest: * Dump the database without any data (mysqldump --no-data) t...
This one is kind of tough. Unless you've got a very simple DB structure with vanilla types (varchar, integer, etc), you're probably going to get the best results writing a migration tool. In a language like Perl (via the DBI), this is pretty straight-forward. The program is basically an echo loop that reads from one da...
Migrating from MySQL to arbitrary standards-compliant SQL2003 server
[ "", "sql", "mysql", "" ]
I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete. Any suggestions would be much appreciated.
Assuming this is running on a Linux machine, I've always handled it like this: ``` exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile)); ``` This launches the command `$cmd`, redirects the command output to `$outputfile`, and writes the process id to `$pidfile`. That lets you easily monitor wha...
Write the process as a server-side script in whatever language (php/bash/perl/etc) is handy and then call it from the process control functions in your php script. The function probably detects if standard io is used as the output stream and if it is then that will set the return value..if not then it ends ``` proc_c...
php execute a background process
[ "", "php", "" ]
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
Analizing MIPS binaries: is there a Python library for parsing binary data?
[ "", "python", "x86", "mips", "elf", "dwarf", "" ]
I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better? When I build the site (using [Web Deployment Projects](http://msdn.microsoft.com/en-us/asp.n...
Here's an example of a Web Deployment Project scripting this sort of task in the .wdproj file: ``` <Target Name="AfterBuild"> <!-- ============================ Script Compression============================ --> <MakeDir Directories="$(OutputPath)\compressed" /> <Exec Command="java -jar c:\yuicompressor-2...
MaseBase, you can use [Web Deployment Projects](http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx) to build and package Web Sites. We do that all the time for projects with a web application aspect. After you assign a WDP to a Web Site, you can open up the **.wdproj** file as plain-text XML file. At the end...
How do I automate repetitive tasks post-build?
[ "", "c#", "asp.net", "visual-studio-2005", "msbuild", "web-deployment-project", "" ]
I am calling a vendor's Java API, and on some servers it appears that the JVM goes into a low priority polling loop after logging into the API (CPU at 100% usage). The same app on other servers does not exhibit this behavior. This happens on WebSphere and Tomcat. The environment is tricky to set up so it is difficult t...
If you are using Java 5 or later, you can connect to your application using [jconsole](http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html) to view all running threads. jstack also will do a stack dump. I think this should still work even inside a container like Tomcat. Both of these tools a...
Facing the same problem I used [YourKit profiler](http://www.yourkit.com/overview/index.jsp). It's loader doesn't activate unless you actually connect to it (though it does open a port to listen for connections). The profiler itself has a nice "get amount of time spent in each method" while working in it's less obtrusi...
If you have a Java application that is consuming CPU when it isn't doing anything, how do you determine what it is doing?
[ "", "java", "profiling", "" ]
How do I multiply 10 to an `Integer` object and get back the `Integer` object? I am looking for the neatest way of doing this. I would probably do it this way: Get int from `Integer` object, multiply it with the other int and create another Integer object with this int value. Code will be something like ... ``` int...
With Java 5's [autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html), you can simply do: ``` Integer a = new Integer(2); // or even just Integer a = 2; a *= 10; System.out.println(a); ```
The string approach is amusing, but almost certainly a bad way to do it. Getting the int value of an Integer, and creating a new one will be very fast, where as parseInt would be fairly expensive to call. Overall, I'd agree with your original approach (which, as others have pointed out, can be done without so much cl...
How to multiply 10 to an "Integer" object in Java?
[ "", "java", "types", "casting", "" ]
Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing `Func<T, bool>` vs. `Predicate<T>` I would imagine there is no difference as both take a generic parameter and return bool?
They share the same signature, but they're still different types.
Robert S. is completely correct; for example:- ``` class A { static void Main() { Func<int, bool> func = i => i > 100; Predicate<int> pred = i => i > 100; Test<int>(pred, 150); Test<int>(func, 150); // Error } static void Test<T>(Predicate<T> pred, T val) { Console.WriteLine(pred(val) ? "tr...
Isn't Func<T, bool> and Predicate<T> the same thing after compilation?
[ "", "c#", ".net", "predicate", "func", "" ]
I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the ne...
I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets. In our projects we move the compiled dlls into lib folders and put the files into the proper locations ...
> Is there a way I can define a macro for a directory and use it in the output path Have you looked at the pre-build and post-build events of a project?
Out-of-place builds with C#
[ "", "c#", "msbuild", "build-process", "" ]
How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running .NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) ...
[SetTimeZoneInformation](http://msdn.microsoft.com/en-us/library/ms724944.aspx) should do what you need. You'll need to use [P/Invoke](http://pinvoke.net/default.aspx/kernel32/SetTimeZoneInformation.html) to get at it. Note also that you'll need to possess and enable the SE\_TIME\_ZONE\_NAME privilege.
This is not working in Windows 7. I have tried with the following environment windows 7 VSTS-2008 It is opening Change Time Zone Window as we do it manually
Setting time zone remotely in C#
[ "", "c#", ".net", "windows", "localization", "timezone", "" ]
Does anybody have experience working with PHP accelerators such as [MMCache](http://turck-mmcache.sourceforge.net/) or [Zend Accelerator](http://www.zend.com/en/)? I'd like to know if using either of these makes PHP comparable to *faster* web-technologies. Also, are there trade offs for using these?
Note that Zend Optimizer and MMCache (or similar applications) are totally different things. While Zend Optimizer tries to optimize the program opcode MMCache will cache the scripts in memory and reuse the precompiled code. I did some benchmarks some time ago and you can find the [results](http://blogs.interdose.com/d...
MMCache has been deprecated. I recommend either <http://pecl.php.net/package/APC> or <http://xcache.lighttpd.net/>, both of which also give you variable storage (like Memcache).
Is using PHP accelerators such as MMCache or Zend Accelerator making PHP faster?
[ "", "php", "caching", "zend-optimizer", "" ]
I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets...
I was trying to find the final word on mmap / read performance on Linux and I came across a nice post ([link](http://marc.info/?l=linux-kernel&m=95496636207616&w=2)) on the Linux kernel mailing list. It's from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely ex...
There are lots of good answers here already that cover many of the salient points, so I'll just add a couple of issues I didn't see addressed directly above. That is, this answer shouldn't be considered a comprehensive of the pros and cons, but rather an addendum to other answers here. ## mmap seems like magic Taking...
mmap() vs. reading blocks
[ "", "c++", "file-io", "fstream", "mmap", "" ]
After cleaning a folder full of HTML files with TIDY, how can the tables content be extracted for further processing?
Depends on what sort of processing you want to do. You can tell Tidy to generate XHTML, which is a type of XML, which means you can use all the usual XML tools like XSLT and XQuery on the results. If you want to process them in Microsoft Excel, then you should be able to slice the table out of the HTML and put it in a...
I've used BeautifulSoup for such things in the past with great success.
What's the best way to extract table content from a group of HTML files?
[ "", "java", "html", "excel", "csv", "extract", "" ]
When should I **not** use the ThreadPool in .Net? It looks like the best option is to use a ThreadPool, in which case, why is it not the only option? What are your experiences around this?
The only reason why I wouldn't use the `ThreadPool` for cheap multithreading is if I need to… 1. interract with the method running (e.g., to kill it) 2. run code on a [STA thread](http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx "Single-Threaded Apartment thread; see e.g. this MSDN reference page...
@Eric, I'm going to have to agree with Dean. Threads are expensive. You can't assume that your program is the only one running. When everyone is greedy with resources, the problem multiplies. > I prefer to create my threads manually and control them myself. It keeps the code very easy to understand. That's fine when ...
When should I not use the ThreadPool in .Net?
[ "", "c#", ".net", "multithreading", "design-decisions", "" ]
In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using `System.Windows.Forms.FolderBrowserDialog` but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC p...
Don't create it yourself! It's been done. You can use [FolderBrowserDialogEx](http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677) - a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with ...
Unfortunately there are no dialogs other than FolderBrowserDialog for folder selection. You need to create this dialog yourself or use PInvoke.
Choosing a folder with .NET 3.5
[ "", "c#", ".net", "wpf", "winforms", "" ]
I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active. Of course...
I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though. It's a hack, not an elegant solution. ``` import java.awt.*; import java.util.*; public class Hal{ public static void main(String[] args) throws Exception{ ...
On Windows, use the [SystemParametersInfo](http://msdn.microsoft.com/en-us/library/ms724947.aspx) function. It's a Swiss army-style function that lets you get/set all sorts of system settings. To disable the screen shutting off, for instance: ``` SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 ); ``` Just be...
How do you keep the machine awake?
[ "", "java", "windows", "macos", "cross-platform", "operating-system", "" ]
I'm looking around for a Java [code signing](http://en.wikipedia.org/wiki/Code_signing) certificate so my Java applets don't throw up such scary security warnings. However, all the places I've found offering them charge (in my opinion) way too much, like over USD200 per year. While doing research, a code signing certif...
Short answer: No, they're different. Long answer: It's the same sort of certificate and it uses the same crypto software, but the certificate has flags indicating what it is allowed to be used for. Code signing and web server are different uses.
When I import a new CA certificate in Firefox (etc.) I have the option of choosing which certificate uses I trust: * Sign servers * Sign code (like your applet) * Sign email certificates So to me the answer is: Yes, they're the same. Furthermore, why not generate your own with [OpenSSL](http://en.wikipedia.org/wiki/O...
Are Java code signing certificates the same as SSL certificates?
[ "", "java", "ssl", "certificate", "code-signing", "" ]
any idea how if the following is possible in PHP as a single line ?: ``` <?php $firstElement = functionThatReturnsAnArray()[0]; ``` ... It doesn't seem to 'take'. I need to do this as a 2-stepper: ``` <?php $allElements = functionThatReturnsAnArray(); $firstElement = $allElements[0]; ``` ... just curious - other la...
Try: ``` <?php $firstElement = reset(functionThatReturnsAnArray()); ``` If you're just looking for the first element of the array.
@Scott Reynen that's not true. This will work: ``` list(,,$thirdElement) = $myArray; ```
PHP: Can I reference a single member of an array that is returned by a function?
[ "", "php", "arrays", "function", "" ]
By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?
Sure there is. This is all you need to do: * Go to ``` File -> Settings -> Global Code Style -> General ``` * Disable the checkbox next to 'Use same settings for all file types' * The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.
In IntelliJ IDEA 10.0.3 it's File > Settings > Code Style > General
How do I change XML indentation in IntelliJ IDEA?
[ "", "java", "xml", "ide", "intellij-idea", "" ]
I'm a front-end developer and I was looking for opinions about the best all-round online documentation for javascript/css/html/xhtml/dom/browser quirks and support. I've tried Sitepoint, Quirksmode, W3Schools but all of these seem to be lacking in certain aspects and have been using them in combination.
I like gotapi.com (Update 2: Site is apparently offline -- Use another resource such as [MDN](https://developer.mozilla.org/en-US/)) **Update:** the original answer was from 2008 -- today I would say to check out [Mozilla Developer Network](https://developer.mozilla.org/en-US/) (as many others have also said).
I like Mozilla's references: <http://developer.mozilla.org/en/JavaScript> <http://developer.mozilla.org/en/DOM> These are not at all the one stop site you want, but they help me.
What is the best online javascript/css/html/xhtml/dom reference?
[ "", "javascript", "html", "css", "ajax", "xhtml", "" ]
Struts 1.3 application. Main website is NOT served by struts/Java. I need to forward the result of a struts action to a page in the website, that is outside of the struts context. Currently, I forward to a JSP in context and use a meta-refresh to forward to the real location. That seems kinda sucky. Is there a better w...
You can't "forward", in the strict sense. Just call `sendRedirect()` on the `HttpServletResponse` object in your `Action` class's `execute()` method and then, `return null`. Alternately, either call `setModule()` on the `ActionForward` object (that you are going to return) or set the path to an absolute URI.
I ended up doing response.sendRedirect().
Struts 1.3: forward outside the application context?
[ "", "java", "struts", "" ]
I have a few scripts on a site I recently started maintaining. I get those Object Not Found errors in IE6 (which Firefox fails to report in its Error Console?). What's the best way to debug these- any good cross-browser-compatible IDEs, or javascript debugging libraries of some sort?
There's no cross-browser JS debugger that I know of (because most browsers use different JS engines). For firefox, I'd definitely recommend firebug (<http://www.getfirebug.com>) For IE, the best I've found is Microsoft Script Debugger (<http://www.microsoft.com/downloads/details.aspx?familyid=2f465be0-94fd-4569-b3c4-...
You could also use [Firebug Lite](http://getfirebug.com/lite.html) - which will work in IE & Opera. It's an external lib that will help you track down problems. It's sometimes more convenient than dealing with the MS Script Debugger.
Cross-browser JavaScript debugging
[ "", "javascript", "" ]
I'm looking for a way to check within `pageLoad()` if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to `Page.IsPostback` property within code behind page. TIA, Ricky
One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running: ``` Sys.Application.add_init(AppInit); function AppInit() { Sys.Application.add_load(RunOnce); } function RunOnce() { // This will only happen once per GET request to the p...
@Darren: Thanks for the answer. I had tried to create pageLoad with event argument [ApplicationLoadEventArgs](http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/ApplicationLoadEventArgsClass/ApplicationLoadEventArgsIsPartialLoadProperty.aspx) as parameter (see below). However according to [this](http://msdn.mic...
How to check if page is postback within reserved function pageLoad on ASP.NET AJAX
[ "", "javascript", "asp.net-ajax", "postback", "lifecycle", "" ]
I would like to intercept the event in a .NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it). Do you have any idea of how I can do that?
The MouseDoubleClick event of the TabControl seems to respond just fine to double-clicking. The only additional step I would do is set a short timer after the TabIndexChanged event to track that a new tab has been selected and ignore any double-clicks that happen outside the timer. This will prevent double-clicking on ...
For some reason, MouseDoubleClick, as suggested by Jason Z is only firing when clicking on the tabs and clicking on the tab panel does not do anything, so that's exactly what I was looking for.
.NET : Double-click event in TabControl
[ "", "c#", ".net", "vb.net", "winforms", "tabcontrol", "" ]
First off, there's a bit of background to this issue available on my blog: * <http://www.codebork.com/coding/2008/06/25/message-passing-a-plug-framework.html> * <http://www.codebork.com/coding/2008/07/31/message-passing-2.html> I'm aware that the descriptions aren't hugely clear, so I'll try to summarise what I'm att...
This is my understanding of your question: You have a plugin object that may have to listen for events on x data objects - you don't want to subscribe to the event on each data object though. I'm assuming that several plugins may want to listen to events on the same data object. You could create a session type object....
Wow! Big question! :) Correct me if I'm wrong. Your basic solution now is kind of an Observer pattern, where the data object (Account, etc) notifies about changes in their states. You think that the problem is that the subscribing plugin has to register in every object to be able to handle notifications. That's not a...
Message passing in a plug-in framework
[ "", "c#", "plugins", "message-passing", "" ]
This should hopefully be a simple one. I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class. How should this extension method look? My first intuitive thought is something like this: ``` namespace System.Web.Mvc { public static class ViewPageExtensions { public static st...
I don't have VS installed on my current machine, but I think the syntax would be: ``` namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle<T>(this ViewPage<T> v) { return ""; } } } ```
Thanks leddt. Doing that yielded the error: > The type 'TModel' must be a reference > type in order to use it as parameter > 'TModel' in the generic type or method which pointed me to [this page](http://forums.asp.net/p/1311022/2581563.aspx), which yielded this solution: ``` namespace System.Web.Mvc { public sta...
How do you write a C# Extension Method for a Generically Typed Class
[ "", "c#", "asp.net-mvc", "generics", "extension-methods", "" ]
I've seen there are a few of them. [opencvdotnet](http://code.google.com/p/opencvdotnet/), [SharperCV](http://www.cs.ru.ac.za/research/groups/SharperCV/), [EmguCV](http://sourceforge.net/projects/emgucv), [One on Code Project](http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx#install). Does anyone have any experience...
I started out with opencvdotnet but it's not really actively developed any more. Further, support for the feature I needed (facedetection) was patchy. I'm using [EmguCV](http://www.emgu.com/wiki/index.php/Main_Page) now: It wraps a much greater part of the API and the guy behind it is very responsive to suggestions and...
[NuGetMustHaves](https://nugetmusthaves.com/Tag/opencv) has a good summary of packages on NuGet with their build dates and OpenCV revs. As of 8/8/2023: * [EmguCV](http://www.emgu.com) is updated for OpenCV v4.7.0.5276 * [OpenCvSharp](https://github.com/shimat/opencvsharp) is updated for OpenCV v4.8.0.20230708 EmguCV...
.Net (dotNet) wrappers for OpenCV?
[ "", "c#", ".net", "opencv", "mono", "cross-platform", "" ]
How do I avoid read locks in my database? Answers for multiple databases welcome!
In Oracle the default mode of operation is the *Read committed* isolation level where a select statement is not blocked by another transaction modifying the data it's reading. From [Data Concurrency and Consistency](http://download.oracle.com/docs/cd/B10501_01/server.920/a96524/c21cnsis.htm): > Each query executed by ...
PostgreSQL also uses MVCC (Multi-Version Concurrency Control), so using the default transaction isolation level (read-committed), you should never block, unless somebody is doing maintainace on th DB (dropping / adding columns / tables / indexes / etc).
How do I avoid read locks in my database?
[ "", "sql", "database", "performance", "locking", "" ]
I have the following HTML `<select>` element: ``` <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option> </select> ``` Using a JavaScript function with th...
You can use this function: ``` function selectElement(id, valueToSelect) { let element = document.getElementById(id); element.value = valueToSelect; } selectElement('leaveCode', '11'); ``` ``` <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical...
If you are using jQuery you can also do this: ``` $('#leaveCode').val('14'); ``` This will select the `<option>` with the value of 14. --- With plain Javascript, this can also be achieved with two [`Document` methods](https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods): * With [`document.querySelect...
How do I programmatically set the value of a select box element using JavaScript?
[ "", "javascript", "html", "dom", "" ]
(I'm using Visual C++ 2008) I've always heard that main() is *required* to return an integer, but here I didn't put in `return 0;` and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complain...
> # 3.6.1 Main function > > .... > > 2 An implementation shall not predefine the `main` function. This function shall not be overloaded. It shall have a return type of type `int`, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: > > ``` > int m...
This is part of the C++ language standard. An implicit return 0 is generated for you if there's no explicit return statement in main.
Why does int main() {} compile?
[ "", "c++", "return-value", "program-entry-point", "" ]
I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?
You need [ARP](http://en.wikipedia.org/wiki/Address_Resolution_Protocol). Python's standard library doesn't include any code for that, so you either need to call an external program (your OS may have an 'arp' utility) or you need to build the packets yourself (possibly with a tool like [Scapy](http://www.secdev.org/pro...
I don't think there is a built in way to get it from Python itself. My question is, how are you getting the IP information from your network? To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty.
Search for host with MAC-address using Python
[ "", "python", "network-programming", "" ]
I have a line of C# in my ASP.NET code behind that looks like this: ``` DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); ``` The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this l...
If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32... Check to make sure you're passing in sane data into, say...
Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method is not capable of throwing an ArithmeticException. Of course, I've been known to be wrong before... :)
FindControl() method throws ArithmeticException?
[ "", "c#", "asp.net", "" ]
How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. *Note: an answer from kro...
``` DateTime.Now.ToString("M/d/yyyy"); ``` <http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx>
Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:- ``` using System.Globalization; using System.Threading; ... var currentCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.Cur...
How do I get today's date in C# in mm/dd/yyyy format?
[ "", "c#", "date", "" ]
I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: * [Lightweight IDE for linux](https://stackoverflow.com/questions/2756/lightweight-ide-for-linux) and * [What tools do you use to develop C++ applicatio...
## Initially: confusion When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed. ## Epiphany: UNIX is an IDE. *All of it.*1 And then I re...
My personal favorite is the **CodeLite 2.x** IDE. see: [http://www.codelite.org](http://www.codelite.org/ "codelite website") The decision to use CodeLite was based on a research regarding the following C++ IDE for Linux: * Eclipse Galileo with CDT Plugin * NetBeans 6.7 (which is also the base for the SunStudio IDE)...
C++ IDE for Linux?
[ "", "c++", "linux", "ide", "" ]
I want to allow users to upload avatar-type images in a variety of formats (**GIF, JPEG, and PNG at least**), but to save them all as **PNG database BLOBs**. If the images are oversized, pixelwise, I want to resize them before DB-insertion. **What is the best way to use GD to do the resizing and PNG conversion?** Edi...
``` <?php /* Resizes an image and converts it to PNG returning the PNG data as a string */ function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_or...
Your process steps should look like this: 1. [Verify](http://www.php.net/manual/en/function.exif-imagetype.php) the [filetype](http://www.php.net/manual/en/function.imagetypes.php) 2. Load the image if it is a supported filetype into GD using [imagecreatefrom\*](http://www.php.net/manual/en/function.imagecreatefromjpe...
How do I resize and convert an uploaded image to a PNG using GD?
[ "", "php", "database", "image", "png", "gd", "" ]
How do I open the default mail program with a Subject and Body in a cross-platform way? Unfortunately, this is for a a client app written in Java, not a website. I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in...
In Java 1.6 you have a stardard way to open the default mailer of the platform: [the Desktop.mail(URI) method](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).The URI can be used to set all the fields of the mail (sender, recipients, body, subject). You can check a full example of desktop integration in Ja...
Never use `Runtime.exec(String)` on Mac OS X or any other operating system. If you do that, you'll have to figure out how to properly quote all argument strings and so on; it's a pain and very error-prone. Instead, use `Runtime.exec(String[])` which takes an array of already-separated arguments. This is much more appr...
How do I open the default mail program with a Subject and Body in a cross-platform way?
[ "", "java", "windows", "macos", "email", "" ]
I have a PHP script that runs as a CGI program and the HTTP `Authenticate` header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored. I am very open to having a master username and password. I just ...
A few ways you could do this. 1. [htaccess](http://fragments.turtlemeat.com/htaccess.php) -- have your webserver handle securing the pages in question (not exactly cgi form based though). 2. Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the...
If you're currently using Authenticate, then you may already have an *htpasswd* file. If you would like to continue using that file, but switch to using FORM based authentication rather than via the Authenticate header, you can use a PHP script to use the same htpasswd file and use sessions to maintain the authenticati...
How would you implement FORM based authentication without a backing database?
[ "", "php", "http", "authentication", "cookies", "cgi", "" ]
Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
Believe it or not, you can actually use [`java.awt.Robot`](http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)) to "create an image containing pixels read from the screen." You can then write that image to a file on disk. I just tried it, and the whole thing ends up like: ...
I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects: ``` public static final void makeScreenshot(JFrame argFrame) { Rectangle rec = argFrame.getBounds(); BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB); argFr...
Is there a way to take a screenshot using Java and save it to some sort of image?
[ "", "java", "image", "screenshot", "" ]
I was testing on a customer's box this afternoon which has Windows Vista (He had home, but I am testing on a Business Edition with same results). We make use of a .DLL that gets the Hardware ID of the computer. It's usage is very simple and the sample program I have created works. The Dll is [This from AzSdk](http://w...
@[Martín](https://stackoverflow.com/questions/29284/windows-vista-unable-to-load-dll-xdll-invalid-access-to-memory-location-dllnotf#29400) The reason you were not getting the UAC prompt is because UAC can only change how a process is **started**, once the process is running it must stay at the same elevation level. Th...
> Unable to load DLL 'HardwareID.dll': > Invalid access to memory location. > (Exception from HRESULT: 0x800703E6) The name of DllNotFoundException is confusing you - this isn't a problem with finding or loading the DLL file, the problem is that when the DLL is loaded, it does an illegal memory access which causes the...
Windows Vista: Unable to load DLL 'x.dll': Invalid access to memory location. (DllNotFoundException)
[ "", "c#", ".net", "windows-vista", "dllnotfoundexception", "" ]
Out of the box SSRS reports cannot have data exposed in the page header. Is there a way to get this data to show?
One of the things I want in my reports is to have nice headers for my reports. I like to have a logo and the user's report parameters along with other data to show to give more information for the business needs the report needs to clarify. One of the things that Microsoft SQL Server 2005 Reporting Services cannot do n...
You have to do it through Parameters. Add a parameter for each piece of data you would like to display, then set the parameter to Hidden. Then set the default value to "From Query" and set the Dataset and Value field to the appropriate values.
How do I show data in the header of a SQL 2005 Reporting Services report?
[ "", "sql", "reporting-services", "header", "report", "" ]
I'm using a `Dictionary<string, int>` where the `int` is a count of the key. Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt: ``` int LastCount = mydict[mydict.keys[mydict.keys.Count]]; ``` does not work, because `Dictionary.Keys` does not impl...
As @Falanwe points out in a comment, doing something like this is ***incorrect***: ``` int LastCount = mydict.Keys.ElementAt(mydict.Count -1); ``` You **should not** depend on the order of keys in a Dictionary. If you need ordering, you should use an [OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/sy...
You can use an [OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary). > Represents a collection of key/value > pairs that are accessible by the key > or index.
Accessing a Dictionary.Keys Key through a numeric index
[ "", "c#", ".net", "dictionary", "" ]
My site has a drop-down menu built in CSS and JavaScript that drops down over a Flash animation. In IE (6&7) the drop-down menus drop over the Flash animation, however, in Firefox (2&3) the menus appear underneath the Flash animation. Is there any way to get this dynamic menu to flow OVER the Flash in Firefox? ![alt t...
Try setting wmode to transparent - see [here](http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_15523)
wmode=opaque seemed to work for me I did it here:www.toolgal.com, hover over the products menu on the top navigation Dan
CSS / JavaScript Navigation Menu on top of Flash in Firefox
[ "", "javascript", "css", "flash", "navigation", "" ]
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file: ``` header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/octet-stream"); header("Content-Length: " . filesize($File)); header("Connection: close"); ``` [@grom](https://stackoverflow.com/users/486/grom)...
Here is an example of sending back a pdf. ``` header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); readfile($filename); ``` [@Swish](https://stackoverflow.com/questions/40943/how-to-automatically-start-...
How to Automatically Start a Download in PHP?
[ "", "php", "automation", "download", "" ]
I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: ``` IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...); ``` In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine...
What you are looking for is MakeGenericType ``` string elementTypeName = Console.ReadLine(); Type elementType = Type.GetType(elementTypeName); Type[] types = new Type[] { elementType }; Type listType = typeof(List<>); Type genericType = listType.MakeGenericType(types); IProxy proxy = (IProxy)Activator.CreateInstance...
You should look at this post from Ayende: [WCF, Mocking and IoC: Oh MY!](http://www.ayende.com/Blog/archive/2007/02/10/WCF-Mocking-and-IoC-Oh-MY.aspx). Somewhere near the bottom is a method called GetCreationDelegate which should help. It basically does this: ``` string typeName = ...; Type proxyType = Type.GetType(ty...
Dynamically Create a generic type for template
[ "", "c#", "generics", "" ]
I want to have a "select-only" `ComboBox` that provides a list of items for the user to select from. Typing should be disabled in the text portion of the `ComboBox` control. My initial googling of this turned up an overly complex, misguided suggestion to capture the `KeyPress` event.
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: ``` stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList; ``` Link to the documentatio...
To add a Visual Studio GUI reference, you can find the `DropDownStyle` options under the Properties of the selected ComboBox: ![enter image description here](https://i.stack.imgur.com/2K5dT.png) Which will automatically add the line mentioned in the first answer to the Form.Designer.cs `InitializeComponent()`, like s...
How can I make a ComboBox non-editable in .NET?
[ "", "c#", ".net", "winforms", "combobox", "" ]
I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?
Opening sockets in python is pretty simple. You really just need something like this: ``` import socket sock = socket.socket() sock.connect((address, port)) ``` and then you can `send()` and `recv()` like any other socket
OK, this code worked ``` s = socket.socket() s.connect((ip,port)) s.send("my request\r") print s.recv(256) s.close() ``` It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.
Best way to open a socket in Python
[ "", "python", "networking", "tcp", "" ]
Is there a free or open source library to read Excel files (.xls) directly from a C# program? It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to elim...
``` var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory()); var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds...
If it is just simple data contained in the Excel file you can read the data via ADO.NET. See the connection strings listed here: <http://www.connectionstrings.com/?carrier=excel2007> or [http://www.connectionstrings.com/?carrier=excel](http://www.connectionstrings.com/?carrier=excel2007) -Ryan Update: then you can j...
Reading Excel files from C#
[ "", "c#", ".net", "excel", "ms-office", "" ]
Say I have two strings, ``` String s1 = "AbBaCca"; String s2 = "bac"; ``` I want to perform a check returning that `s2` is contained within `s1`. I can do this with: ``` return s1.contains(s2); ``` I am pretty sure that `contains()` is case sensitive, however I can't determine this for sure from reading the documen...
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE\_INSENSITIVE flag for case insensitive matching: ``` Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find(); ``` **EDIT:** If s2 contains regex special characters (of which there are many) it's impor...
One problem with [the answer by Dave L.](https://stackoverflow.com/questions/86780/is-the-contains-method-in-java-lang-string-case-sensitive/86832#86832) is when s2 contains regex markup such as `\d`, etc. You want to call Pattern.quote() on s2: ``` Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher...
How to check if a String contains another String in a case insensitive manner in Java?
[ "", "java", "string", "" ]
Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this. ``` // Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -> name = $name; $this -> heigh...
The "class" that you've constructed above is what most people would use a *struct* for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit. That being said, if the cost is relatively low, it IS a...
It depends exactly what you mean by 'better'. I'd go for the object oriented way (using classes) because I find it makes for cleaner code (at least in my opinion). However, I'm not sure what the speed penalties might be for that option.
Classes vs 2D arrays
[ "", "php", "arrays", "class", "" ]
How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time. *Edit: These users do want to...
this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab. ``` newExcitingAlerts = (function () { var oldTitle = document.title; var msg = "New!"; var timeout...
I've made a [jQuery plugin](http://heyman.info/jquery-title-alert/ "jQuery Title Alert") for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in ...
Make browser window blink in task Bar
[ "", "javascript", "browser", "" ]
So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that...
I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem. Basically, call ShowWindow() then SetForegroundWindow(). ``` using System.Diagnostics; using System.Runtime.InteropServices; // Sets the window to be fore...
Here is some code that I've used on one form or another for a few years. There are a few gotchas to making a window in another app pop up. Once you have the window handle do this: ``` if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE); ShowWindowAsync(hWnd, SW_SHOW); SetForegroundWindow(...
C# Force Form Focus
[ "", "c#", "winforms", "" ]
The problem: I have a class which contains a template method `execute` which calls another method `_execute`. Subclasses are supposed to overwrite `_execute` to implement some specific functionality. This functionality should be documented in the docstring of `_execute`. Advanced users can create their own subclasses t...
Well, if you don't mind copying the original method in the subclass, you can use the following technique. ``` import new def copyfunc(func): return new.function(func.func_code, func.func_globals, func.func_name, func.func_defaults, func.func_closure) class Metaclass(type): def __new__...
Is there a reason you can't override the base class's `execute` function directly? ``` class Base(object): def execute(self): ... class Derived(Base): def execute(self): """Docstring for derived class""" Base.execute(self) ...stuff specific to Derived... ``` If you don't want ...
Using the docstring from one method to automatically overwrite that of another method
[ "", "python", "metaclass", "" ]
Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using [CBL ActiveRecord](http://31tools.com/cbl_activerecord/), but I was wondering if there were any viable alternatives.
Depends! ;) For example there is [ADODB's Active Record implementation](http://phplens.com/lens/adodb/docs-active-record.htm), then there is Zend\_Db\_DataTable and [Doctrine](http://www.phpdoctrine.org/). Those are the ones I know of, I am sure there are more implementations. Out of those three I'd recommend Doctrin...
I realize this is old, but there is an absolutely fabulous PHP Activecord library called, appropriately, PHP Activerecord. I've used it for several months and it blows away the other libraries. Check it out: <http://www.phpactiverecord.org/>
Recommendations for implementations of ActiveRecord
[ "", "php", "" ]
I am looking for a best practice for End to End Authentication for internal Web Applications to the Database layer. The most common scenario I have seen is to use a single SQL account with the permissions set to what is required by the application. This account is used by all application calls. Then when people requir...
Dale - That's it exactly. If you want to provide access to the underlying data store to those users then do it via services. And in my experience, it is those experienced computer users coming out of Uni/College that damage things the most. As the saying goes, they know just enough to be dangerous. If they want to aut...
Personally, I don't want normal end users in the database. For an intranet application (especially one which resides on a Domain) I would provide a single account for application access to the database which only has those rights which are needed for the application to function. Access to the application would then be...
Database Authentication for Intranet Applications
[ "", "asp.net", "sql", "nhibernate", "" ]
What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this? And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each...
``` Map map = new HashMap(); Hashtable ht = new Hashtable(); ``` Both classes can be found from the java.util package. The difference between the 2 is explained in the following [jGuru FAQ entry](http://www.jguru.com/faq/view.jsp?EID=430247).
You can use double-braces to set up the data. You still call add, or put, but it's less ugly: ``` private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{ put("foo", 1); put("bar", 256); put("data", 3); put("moredata", 27); put("hello", 32); pu...
How do I create a hash table in Java?
[ "", "java", "hash", "hashmap", "" ]
I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?
When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.
I ran across this blog entry that looks like it will work and it uses the Event Handler concept from D2VIANT Answer <http://www.dotnetcurry.com/ShowArticle.aspx?ID=125> Summary: Step 1: Create a new Windows application. Open Visual Studio 2005 or 2008. Go to File > New > Project > Choose Visual Basic or Visual C# in ...
How do I close a parent Form from child form in Windows Forms 2.0?
[ "", "c#", "winforms", "" ]
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the se...
Definitely use `onload`. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better. ``` $(document).ready(function(){ // manipulate the DOM all you want here }); ``` The advantages are: 1. Call $(document).ready() as many times as you want to regis...
Should I use window.onload or script block?
[ "", "javascript", "dom", "" ]
After I was convinced that labeled breaks/continues are a total "nono" over [here](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501), I need help to remove the label out of my code. I have a square matrix and a vector that has the same length. The vector has alr...
Looking at the solutions presented so far: * They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself * Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite...
This question was not about optimizing the algorithm - but thanks anyway ;-) At the time I wrote it, I considered the labeled continue as a readable solution. I asked SO a [question](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501) about the convention (having...
Refactoring away labeled loops
[ "", "java", "refactoring", "label", "" ]
Is there any way to get the ID of the element that fires an event? I'm thinking something like: ``` $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); ``` ``` <script type="text/javascript" src="starterkit/jquery.js"></script> <form class="it...
In jQuery `event.target` always refers to the element that triggered the event, where `event` is the parameter passed to the function. <http://api.jquery.com/category/events/event-object/> ``` $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); ``` Note also t...
For reference, try this! It works! ``` jQuery("classNameofDiv").click(function() { var contentPanelId = jQuery(this).attr("id"); alert(contentPanelId); }); ```
Getting the ID of the element that fired an event
[ "", "javascript", "jquery", "dom-events", "" ]
Is there a simple way to cache `MySQL queries` in `PHP` or failing that, is there a small class set that someone has written and made available that will do it? I can cache a whole page but that won't work as some data changes but some do not, I want to cache the part that does not.
This is a great overview of how to cache queries in MySQL: * [The MySQL Query Cache](http://www.petefreitag.com/item/390.cfm)
You can use [Zend Cache](http://framework.zend.com/manual/en/zend.cache.html) to cache results of your queries among other things.
Caching MySQL queries
[ "", "php", "mysql", "caching", "" ]
Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot
I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on [SunSpider JavaScript Benchmark](http://www2.webkit.org/perf/sunspider-0.9/sunspider.html) with the following results: * Firefox - total: 2900.0ms +/- 1.8% * Chrome - total: **1549.2ms +/- 1.7%** and on [V8 Benchmark Suite](http://code.google.com/a...
Perhaps a bit anecdotal but comparing runs between Firefox and Chrome showed a significant difference in benchmarks. <http://www2.webkit.org/perf/sunspider-0.9/sunspider.html> Try for yourself.
Is Google Chrome's V8 engine really that good?
[ "", "javascript", "google-chrome", "v8", "" ]
Here's a quick question I've been banging my head against today. I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: ``` string transformXML = @"pathToXslDocument"; XmlDocument origin...
I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it. **EDIT**: Just tried following code and it worked perfectly: ``...
You must select the root node. This doesn't use Datasets, but I use this function everyday and it works great. ``` System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument(); orgDoc.LoadXml(orgXML); // MUST SELECT THE ROOT NODE XmlNode transNode = orgDoc.SelectSingleNode("/"); System.Text.StringBuilder sb = new Sys...
How to Convert a StreamReader into an XMLReader object in .Net 2.0/C#
[ "", "c#", ".net", "xml", "xslt", "stream", "" ]
I have an absolutely positioned `div` that I want to show when the user clicks a link. The `onclick` of the link calls a js function that sets the display of the div to block (also tried: "", `inline`, `table-cell`, `inline-table`, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, O...
Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript...
Can you provide some markup that reproduce the error? Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5: ``` function show() { var d = document.getElementById('testdiv'); d.style.display = 'block'; } ``` ``` #testdiv { position: absolute; heigh...
Style display not working in Firefox, Opera, Safari - (IE7 is OK)
[ "", "javascript", "html", "css", "" ]
So my company stores alot of data in a foxpro database and trying to get around the performance hit of touching it directly I was thinking of messaging anything that can be done asynchronously for a snappier user experience. I started looking at [ActiveMQ](http://activemq.apache.org/) but don't know how well C# will ho...
ActiveMQ works well with C# using the Spring.NET integrations and NMS. A post with some links to get you started in that direction [is here](http://thefreakparade.com/2008/04/15/two-message-exchange-patterns-using-activemq-and-nms-via-springnet/). Also consider using MSMQ (The System.Messaging namespace) or a .NET base...
MSMQ (Microsoft Message Queueing) may be a great choice. It is part of the OS and present as an optional component (can be installed via Add/Remove Programs / Windows Components), meaning it's free (as long you already paid for Windows, of course). MSMQ provides Win32/COM and [System.Messaging](https://learn.microsoft....
What to use for Messaging with C#
[ "", "c#", "messaging", "" ]
I want to convert a primitive to a string, and I tried: ``` myInt.toString(); ``` This fails with the error: ``` int cannot be dereferenced ``` Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I ne...
Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows `myInt` as a primitive. There's a paper about this issue at [jcp.org](http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html). Autoboxing is mainly useful duri...
Ditto on what Justin said, but you should do this instead: ``` Integer.toString(myInt); ``` It saves an allocation or two and is more readable.
Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?
[ "", "java", "autoboxing", "" ]
I have a `byte[]` array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the `BinaryWriter` object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multi...
**Edit:** The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly. I think you need to write to your MemeoryStream first. As if my memory (no pun intended) serves me correctly this: ``` MemoryStream ms = new MemoryStr...
OK, I found the issue, and it was from a part of the code unrelated to the part of the code I was asking about. The data was being passed as a string, I was converting it to a byte array (this was a test rig so I was trying to simulate the byte array that I get in the main app), then converting that to a MemoryStream, ...
How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object?
[ "", "c#", ".net", "image", "tiff", "" ]
I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using `System.Data.OracleClient` to connect to oracle database. Name of database is `myDB`. Below the the connection string I am using: ``` Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(P...
This looks like an issue with name resolution, try creating a public synonym on the table: CREATE PUBLIC SYNONYM *MyTempTable* for *MyTempTable*; Also, what exactly do you mean by **wrong result**, incorrect data, error message? --- Edit: What is the name of the schema that the required table belongs to? It sounds ...
Upon connecting to the database issue am ``` ALTER SESSION SET CURRENT_SCHEMA=abc; ``` where abc is the user that owns the tables.
Referencing same table name in different schemas
[ "", ".net", "sql", "oracle", "" ]
I have a project where I would like to generate a report export in MS Word format. The report will include images/graphs, tables, and text. What is the best way to do this? Third party tools? What are your experiences?
The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when [using Office Automation on a server](http://supp...
[DocX free library](http://docx.codeplex.com/) for creating DocX documents, actively developed and very easy and intuitive to use. Since CodePlex is dying, project has moved to [github](https://github.com/WordDocX/DocX).
How can a Word document be created in C#?
[ "", "c#", ".net", "ms-word", "openxml", "" ]
I have a blogengine.net install that requires privatization. I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met. How can I privatize my blogEngine.net install so that readers must log in to read my posts?
I use this extension. Just save the file as RequireLogin.cs in your App\_Code\Extensions folder and make sure the extension is activated. ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using Sys...
From: [BlogEngine.NET 2.5 - Private Blogs](http://blogengine.codeplex.com/discussions/267878) If you go into the control panel, Users tab, Roles sub-tab (right side), for "Anonymous" on the right-side Tools area, hover over that and select "Rights". You are now on the Rights page for the Anonymous role. Uncheck every...
Privatizing a BlogEngine.Net Installation
[ "", "c#", ".net", "asp.net", "blogs", "" ]
Why in this millennium should Python [PEP-8](http://www.python.org/dev/peps/pep-0008/) specify a [maximum line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) of 79 characters? Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of t...
Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices ar...
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side. Readability is also one of the reasons for enforced line indentatio...
Why does PEP-8 specify a maximum line length of 79 characters?
[ "", "python", "coding-style", "pep8", "" ]
When `{0}` is used to initialize an object, what does it mean? I can't find any references to `{0}` anywhere, and because of the curly braces Google searches are not helpful. Example code: ``` SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE...
What's happening here is called **aggregate** initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec: > An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions. N...
One thing to be aware of is that this technique will not set padding bytes to zero. For example: ``` struct foo { char c; int i; }; foo a = {0}; ``` Is not the same as: ``` foo a; memset(&a,0,sizeof(a)); ``` In the first case, pad bytes between c and i are uninitialized. Why would you care? Well, if you'r...
What does {0} mean when initializing an object?
[ "", "c++", "c", "" ]
I want to be able to get an estimate of how much code & static data is used by my C++ program? Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime? Will objdump & readelf help?
"size" is the traditional tool. "readelf" has a lot of options. ``` $ size /bin/sh text data bss dec hex filename 712739 37524 21832 772095 bc7ff /bin/sh ```
If you want to take the next step of identifying the functions and data structures to focus on for footprint reduction, the --size-sort argument to nm can show you: ``` $ nm --size-sort /usr/bin/fld | tail -10 000000ae T FontLoadFontx 000000b0 T CodingByRegistry 000000b1 t ShmFont 000000ec t FontLoadw 000000ef T LoadF...
Linux: What is the best way to estimate the code & static data size of program?
[ "", "c++", "linux", "unix", "" ]
The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus. Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answe...
I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen. So instead of this: ``` webBrowser1.DocumentText = "<h1>Hello, world!</h1>"; ``` try this: ``` webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write("<h1>Hello, world!</h1>"); ```
``` const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21; const int SET_FEATURE_ON_PROCESS = 0x00000002; [DllImport("urlmon.dll")] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] static extern int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType.U4...
HowTo Disable WebBrowser 'Click Sound' in your app only
[ "", "c#", ".net", "winforms", "" ]