Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
We have a system with an Oracle backend to which we have access (though possibly not administrative access) and a front end to which we do not have the source code. The database is quite large and not easily understood - we have no documentation. I'm also not particularly knowledgable about Oracle in general. One aspe...
Clearly there are many methods. The one that I find easiest is: (1) Connect to the database as SYS or SYSTEM (2) Query V$SESSION to identify the database session you are interested in. Record the SID and SERIAL# values. (3) Execute the following commands to activate tracing for the session: ``` exec sys.dbms_system...
Start with querying Oracle system views like V$SQL, v$sqlarea and v$sqltext.
How to determine an Oracle query without access to source code?
[ "", "sql", "oracle", "networking", "" ]
Is there any RDBMS that implements something like `SELECT * EXCEPT`? What I'm after is getting all of the fields except a specific TEXT/BLOB field, and I'd like to just select everything else. Almost daily I complain to my coworkers that someone should implement this... It's terribly annoying that it doesn't exist. *...
As others have said, it is not a good idea to do this in a query because it is prone to issues when someone changes the table structure in the future. However, there is a way to do this... and I can't believe I'm actually suggesting this, but in the spirit of answering the ACTUAL question... Do it with dynamic SQL... ...
Create a view on the table which doesn't include the blob columns
SELECT * EXCEPT
[ "", "sql", "sql-except", "" ]
Is it safe to assume that event subscribers are called in order of subscription? Example: ``` void One(object sender, EventArgs e) {} void Two(object sender, EventArgs e) {} event EventHandler foo; foo += One; foo += Two; ``` Is One() always called before Two() when the event is fired? Edit: You should ofcours...
Given that implementation, yes, they will always be called in that order. If the event actually uses some weird and wonderful way of handling subscriptions, it could do different things - but "normal" implementations will do the right thing. To be clear, subscribing to an event handler just means invoking the appropr...
Pay very close attention to the caveats given by Jon Skeet - "Given that implementation...". In other words, make the slightest change (multiple threads, other handlers, etc.) and you risk losing the order-of-execution invariance. *Do **NOT** rely on event ordering*. All event dispatches should be logically independen...
Are event subscribers called in order of subscription?
[ "", "c#", ".net", "events", ".net-2.0", "c#-2.0", "" ]
In C++, I can't think of a case in which I would like to inherit private/protected from a base class: ``` class Base; class Derived1 : private Base; class Derived2 : protected Base; ``` Is it really useful?
It is useful when you want to have access to some members of the base class, but without exposing them in your class interface. Private inheritance can also be seen as some kind of composition: the [C++ faq-lite](http://www.parashift.com/c++-faq-lite/private-inheritance.html) gives the following example to illustrate t...
Private can be useful in quite a few circumstances. Just one of them are policies: [Is partial class template specialization the answer to this design problem?](https://stackoverflow.com/questions/356294/is-partial-class-template-specialization-the-answer-to-this-design-problem#356576). Another occasion where it is u...
Why do we actually need Private or Protected inheritance in C++?
[ "", "c++", "inheritance", "private", "protected", "c++-faq", "" ]
In JavaScript the % operator seems to behave in a very weird manner. I tried the following: ``` >>> (0 - 11) % 12 -11 ``` Why does it return -11 instead of 1 (as in Python)? I am sure I am doing or expecting something wrong, but the docs don't tell me what.
fmod from the math module behaves correctly in python: ``` >>> from math import * >>> fmod(-11, 12) -11.0 ``` -11 is the correct answer..
It's behaving correctly according to the way the language is specified (e.g. [ECMA 262](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)), where it's called the remainder operator rather than the modulus operator. From the spec: > The result of an ECMAScript floating-point remainder operation...
What is the correct way to use the modulus (%) operator in JavaScript?
[ "", "javascript", "modulo", "" ]
we have this scenario: A server which contains needed data and client component which these data wants. On the server are stored 2 types of data: - some information - just a couple of strings basically - binary data We have a problem with getting binary data. Both sides are written in Java 5 so we have couple of way...
I think the only way to do LARGE amounts of data is going to be with raw socket access. You will hit the Out of Memory issues on large files with most other methods. Socket handling is really pretty straight forward in Java, and it will let you stream the data without loading the entire file into memory (which is wha...
Take a look at the W3C standard MTOM to transfer binary data as part of a SOAP service. It is efficient in that it sends as a binary and can also send as buffered chunks. It will also interop with other clients or providers: [How to do MTOM Interop](http://blogs.msdn.com/smguest/archive/2005/06/30/434218.aspx) [Serve...
Large amount of data - what is the best way to send them?
[ "", "java", "networking", "data-transfer", "" ]
Is there a way at all of altering the clipboard of the user via JavaScript? I want it that they click a given point on a map, and it adds the coordinates of the position to their clipboard. I do however assume that this is not possible for JavaScript to achieve.
You could try using the [zeroclipboard](http://code.google.com/p/zeroclipboard/ "zeroclipboard") library, which involves placing an invisible flash element on the page to do the actual copy of text to the clipboard.
It is in Internet Explorer, but not in other browsers although support can be [hacked together](http://www.webtips.co.in/javascript/copy-to-clipboard-with-javascript-on-mozilla-firefox-and-ie.aspx) in other browsers by inserting a [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) file each time you want to do a copy. N...
Copy to clipboard in JavaScript
[ "", "javascript", "clipboard", "" ]
HI, I am doing ERP solution in C#(2.0) windows application and SQL2005 Database.The network application communicate through Database.I used normal technique for user login and logout, keeping a status bit.My problem is that when my application interrupted with any other reason user status might not change.That will cau...
If your intention is to disallow sharing of one username on different computers, after logging with valid password, log the unique token on that computer to **staff.last\_logged\_at** = **@unique\_token**. On logout, set staff.last\_logged\_at = ''. This way even if the computer was interrupted(program crash due to vir...
How about keeping track of user logins by maintaining a session for each login? The quick-and-dirty solution is to then offer an option to have them login from a "new location" and invalidate the old session. Then when you go to perform an operation, first check if the session is still valid. The better implementation...
User Login technique C# Win App
[ "", "c#", "winforms", "" ]
There are times when I want to test new code from the forums or when I need to help my friends with specific C# problem. The problem is I don't want to create new "project" in Visual Studio each time just to code/run only this small code. Java & Eclipse IDE comes up with "Scrapbook" feature which allows the execution ...
~~[Snippet Compiler](http://www.sliver.com/dotnet/SnippetCompiler/) is great for this.~~ [LINQPad](http://www.linqpad.net/) is also good for testing out all sorts of C#, F# or VB code, not just LINQ queries. --- **EDIT** I suppose it's time that I mention that Snippet Compiler hasn't been updated in over five years...
A bit late to the party, but I came here while searching for this myself. The best suitable solution for me was using the `C# Interactive`-window inside **Visual Studio** 2015 or later. You can access it by opening it via `View` > `Other Windows` > `C# Interactive`, or by selecting some c# code and clicking on `Execut...
How to quickly code and run small C# code
[ "", "c#", "visual-studio", "testing", "" ]
Anyone have a link to what the C++ standard says regarding a compiler removing global and static symbols? I thought you weren't guaranteed that the compiler will remove global symbols if they're not referenced. A colleague of mine asserts that if your global symbols are included in the main translation unit, those symb...
Interestingly, all I can find on this in the C++2003 standard is this: > 3.7.1 Static storage duration [basic.stc.static] > > All objects which neither have dynamic > storage duration nor are local have > static storage duration. The storage > for these objects shall last for the > duration of the program (3.6.2, > 3....
You're asking a question about linking, and although the C++ Standard says that linking should occur as the final phase of translation, it says nothing about *how* that should happen. For example, it says that function references are resolved, but it doesn't require them to be resolved by name, and it doesn't say what ...
C++ Standard and Global Symbol Removal
[ "", "c++", "compiler-construction", "linker", "" ]
Even something very rudimentary is fine. Like entering and evaluating something like x+1, where x is a variable I get to specify. I was thinking of writing my own using Strings for each formula, regex for parsing them, etc., but let's assume my goal is to be as lazy as I can possibly get away with, and that if there's...
You can think about using [scripting](http://java.sun.com/javase/6/docs/technotes/guides/scripting/) from Java 6. The reference JDK comes with a JavaScript implementation, and you can plug in other languages too.
I know the following libraries: * [Symja Parser](https://github.com/axkr/symja_android_library) (GPL License) supports Mathematica like syntax * [Jep - Java Math Expression Parser](http://www.singularsys.com/jep/) (commercial - older versions under GNU Public License?) * [JFormula](http://www.japisoft.com/formula/) (c...
Java: Is there a tool available that can allow me input, store, and evaluate math formulas?
[ "", "java", "math", "formulas", "" ]
Is there any java chart library that supports OLAP data, like [ChartFX Olap](http://www.softwarefx.com/Extensions/filmsLarge.aspx?movieName=olapAxesLarge&movieWidth=749&movieHeight=565) or [Dundas Chart](http://www.dundas.com/Gallery/Chart/NET/index.aspx?Img=OLAP6) ? Thanks
In order to display any data as a chart, it will need to be reduced to a 2D recordset - which is what OLAP gives you when you run an MDX query. If you've got that 2D data, you can pass it to any chart/graph code really. I used to use ASP to run the MDX, and write out XML. This was turned into a chart with client-side...
[JFreeChart](http://www.jfree.org/jfreechart/) or [JasperReports](http://jasperforge.org/plugins/project/project_home.php?group_id=102) would be my recommendations.
Java Chart library for OLAP
[ "", "java", "charts", "olap", "" ]
I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing. Are there any tutorials out there that can show me a simple exa...
In C++, your `main()` function can have `argc` and `argv` parameters, which contain the arguments passed on the command line. The `argc` is the count of arguments (including the executable name itself), and `argv` is an array of pointers to null-terminated strings of length `argc`. For example, this program prints its...
You can use boost::program\_options to do this, If you don't want to use boost library, you must parse main function arguments by yourself.
Adding parameters for a program at launch
[ "", "c++", "parameters", "" ]
I want to capture the screen in my code to get an image - like using the 'print screen' button on the keyboard . Does anyone have an idea how to do this? I have no starting point.
You can use the [`Graphics.CopyFromScreen()`](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.copyfromscreen) method. ``` //Create a new bitmap. var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, ...
I had two problems with the accepted answer. 1. It doesn't capture all screens in a multi-monitor setup. 2. The width and height returned by the `Screen` class are incorrect when display scaling is used and your application is not declared per monitor [dpiAware](https://learn.microsoft.com/en-us/windows/win32/hidpi/se...
Capture the Screen into a Bitmap
[ "", "c#", ".net", "screenshot", "" ]
I'm a C# developer looking to get into home automation as a hobby. I have done a little research, but was wondering if anyone knows of a good .NET library that supports Insteon hardware. I'd rather use Insteon than X10 due to reliability issues. My ultimate objective at this point is to have a simple home automation s...
We found there really wasn't much developer support for Insteon unless you wanted to buy their SDK and agree to their rather heavy-handed license agreement. Rather than go that route, we wrote our own .NET library called [FluentDwelling](http://soapboxautomation.com/products/fluentdwelling/) and we open-sourced it. You...
I would avoid X10 like the plague. Between things like modern TV's and power strips, bridged power junction boxes and just plain strange wiring, X10 signals tend to just "disappear" and never get to their destination. If you really want to give X10 a shot, I've got a box of X10 stuff in the garage that was worth $250+...
Home Automation Library
[ "", "c#", "asp.net", ".net", "home-automation", "" ]
Quick question: what is the compiler flag to allow g++ to spawn multiple instances of itself in order to compile large projects quicker (for example 4 source files at a time for a multi-core CPU)?
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine). For example if you want 4 parallel jobs from make: ``` make -j 4 ``` You can also run gcc in a pipe with ``` gcc -pipe ``` This will pipeline the compile stages, which will also help keep the cores busy. I...
There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la ``` make -j4 ``` Or you can use p...
Compiling with g++ using multiple cores
[ "", "c++", "compiler-construction", "makefile", "g++", "multicore", "" ]
I want to be able to get the projects I have in Sourcesafe and their total lines of code (perhaps also with total number of classes, etc). Is there an SDK for Sourcesafe (I use 2005 edition) which will allow me to do this? Or is there a document in Sourcesafe which lists all the projects in SS? Using this, I could wor...
There is no specific line counting API. There is an API to access the files but its way too slow. It would probably be better if you set up a shadow folder on the root project (this is done via the admin tool). A simple app could then open all the source files recursively from the shadow folder and do some line counti...
I realize this is not exactly what you're asking for, but you might be able to adapt the following to suit your needs: <http://richnewman.wordpress.com/2007/07/01/c-and-vbnet-line-count-utility/> I've used this before, and works very well. It differentiates between comments and auto-generated code as well.
Is there a Sourcesafe API to get total lines of code in source control?
[ "", "c#", "visual-sourcesafe", "" ]
I have a function called: ``` void initializeJSP(string Experiment) ``` And in my MyJSP.h file I have: ``` 2: void initializeJSP(string Experiment); ``` And when I compile I get this error: > MyJSP.h:2 error: variable or field initializeJSP declared void Where is the problem?
It for example happens in this case here: ``` void initializeJSP(unknownType Experiment); ``` Try using `std::string` instead of just `string` (and include the `<string>` header). C++ Standard library classes are within the namespace `std::`.
This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message. EDIT: As in the accepted answer, the fix is to use `std::string` instead of just `string`.
variable or field declared void
[ "", "c++", "string", "void", "" ]
Some of my script are using different encoding, and when I try to combine them, this has becom an issue. But I can't change the encoding they use, instead I want to change the encodig of the result from script A, and use it as parameter in script B. So: is there any simple way to change a string from UTF-8 to ISO-885...
Have a look at [`iconv()`](http://php.net/function.iconv) or [`mb_convert_encoding()`](http://php.net/function.mb-convert-encoding). Just by the way: why don't [`utf8_encode()`](http://php.net/function.utf8-encode) and [`utf8_decode()`](http://php.net/function.utf8-decode) work for you? > **utf8\_decode** — Converts a...
First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere. Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use [iconv](http://php.net/manual/function.iconv.php) or [`mb_convert_encodin...
Convert utf8-characters to iso-88591 and back in PHP
[ "", "php", "encoding", "utf-8", "iso-8859-1", "" ]
I have three tables. This query will write down the right answer (x-lines for btv.id\_user with appropriate btv.cas and race.id\_zavod ``` SELECT `btv.id_user`, `btv.id_zavod`,`btv.cas` FROM `btv` JOIN `btu` ON `btv.id_user` = `btu.id_user` JOIN `race` ON 'btv.id_zavod' = `race.id_zavod` WHERE `race.type` = '8' AND `b...
When you use GROUP BY, the columns in the select-list must satisfy one of the following: * Column is named in the GROUP BY (e.g. `btv.id_user` in your example) * Column is inside an aggregate function (e.g. `MIN( btv.cas )` ) * Column is a *functional dependency* of the column(s) you named in the GROUP BY. This is th...
The query you have written: ``` SELECT `btv.id_user`, `btv.id_zavod`, MIN( `btv.cas` ) FROM `btv` JOIN `btu` ON `btv.id_user` = `btu.id_user` JOIN `race` ON 'btv.id_zavod' = `race.id_zavod` WHERE `race.type` = '8' AND `btv.id_user` = '607' GROUP BY `btv.id_user` ``` won't run. You need a group by id\_zavod or somethi...
Problem with table JOIN in MySQL and aggregation
[ "", "sql", "mysql", "join", "" ]
I want to open a ZIP-file, that have no entries with java.util.zip.ZipFile. But on the constructor I get the following exception: 'java.util.zip.ZipException: error in opening zip file'. How can I open the empty ZIP? That ZIP-file is created by the commandline zip-program under linux. I simply deleted all entries from...
My solution for this problem is now, that I simply use ZipInputStream instead of ZipFile. This class works well with empty ZIP-files. I don't know about the reason, why one works and the other not.
hack: you can assume that all empty ZIPs are the same and just hardcode it's length/chechsum to validate against.
Why I get an Exception on opening an empty ZIP-file with java.util.zip.ZipFile?
[ "", "java", "exception", "zip", "" ]
I'm sure I've done this before, but can't find any example of it! Grrr... For example, I want to convert an `IList<T>` into a `BindingList<T>`: ``` public class ListHelper { public static BindingList<T> ToBindingList(IList<T> data) { BindingList<T> output = new BindingList<T>(); foreach (T it...
``` ToBindingList <T> (...) ``` --- ``` public class ListHelper { public static BindingList<T> ToBindingList<T>(IList<T> data) { BindingList<T> output = new BindingList<T>(); foreach (T item in data) { output.Add(item); } return output; } } ```
Wouldn't this be simpler? ``` public static class Extensions { public static BindingList<T> ToBindingList<T>(this IList<T> list) { return new BindingList<T>(list); } } ``` It's so simple that we don't need an extension method ... Am I missing something?
Generic method in a non-generic class?
[ "", "c#", "generics", "" ]
I have this scenario where I need data integrity in the physical database. For example, I have a variable of `@email_address VARCHAR(200)` and I want to check if the value of `@email_address` is of email format. Anyone has any idea how to check format in T-SQL? Many thanks!
I tested the following query with many different wrong and valid email addresses. It should do the job. ``` IF ( CHARINDEX(' ',LTRIM(RTRIM(@email_address))) = 0 AND LEFT(LTRIM(@email_address),1) <> '@' AND RIGHT(RTRIM(@email_address),1) <> '.' AND CHARINDEX('.',@email_address ,CHARINDEX('@',@email_address))...
AFAIK there is no good way to do this. The email format standard is so complex parsers have been known to run to thousands of lines of code, but even if you were to use a simpler form which would fail some obscure but valid addresses you'd have to do it without regular expressions which are not natively supported by T...
T-SQL: checking for email format
[ "", "sql", "sql-server", "t-sql", "email", "" ]
My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.
Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy. ``` public class AllowedAccess { ...
A private static inner class is exactly what you want. Nothing dumb about it. ``` public class Creator { private static class Created { } } ``` Otherwise you can only protect instantiation on the package level. ``` public class Created { Created() { } } ``` Which gives only classes from the same package acc...
Quick Java Question: Instantiating a given class only from another?
[ "", "java", "class", "instantiation", "" ]
I want to write a script in Ruby to clean up some messed up keys in several copies of the same MySQL schema. I'd like to do something like SHOW CREATE TABLE, then look at what comes back and delete keys if they exist. I know in the Rails environment you can do this... ``` ActiveRecord::Base.connection.execute( some s...
You could check the [mysql-ruby](http://rubyforge.org/projects/mysql-ruby/) gem. Here is a write-up on how to use it: [Using the Ruby MySQL Module](http://www.kitebird.com/articles/ruby-mysql.html) More can be found via google
This should help you: ``` >> result = ActiveRecord::Base.connection.execute("SHOW TABLES") => #<Mysql::Result:0x37ecb30> >> result.class.instance_methods - Object.instance_methods => ["all_hashes", "field_seek", "row_tell", "fetch_field_direct", "free", "field_tell", "fetch_lengths", "num_fields", "data_seek", "fetch...
How do you talk SQL directly to MySQL from Ruby?
[ "", "sql", "mysql", "ruby-on-rails", "ruby", "activerecord", "" ]
How do you declare a method in C# that should be overridden (or overridable) by a dereived class - possibly even outside your assembly - but that should be callable only from within the actual class? (i.e. like a private virtual function in C++) **[edit]** *`private`* `virtual` is exactly what I intend: "Here's a w...
C# makes a stronger guarantee for "private" than C++ does. In C++, you can indeed override a private virtual method. But that means that code in a base class can execute code in a derived class. Breaking the promise that the private method is truly private and can only be called by methods in the same class. Something...
When you say it should only be callable "within the actual class" do you mean the base class or the derived class? Neither of these is feasible on its own. The closest is to use a protected method, which means it can be called from the declaring class, the derived class, and any further-derived class.
override but don't call
[ "", "c#", "inheritance", "virtual", "access-modifiers", "" ]
I'm using JUnit 4.4 and Maven and I have a large number of long-running integration tests. When it comes to parallelizing test suites there are a few solutions that allow me to run each test method in a single test-class in parallel. But all of these require that I change the tests in one way or another. I really thi...
From junit 4.7 it's now possible to run tests in parallel without using TestNG. Actually it has been possible since 4.6, but there are a number of fixes being made in 4.7 that will make it a viable option. You may also run parallel tests with spring, which you can read about [here](http://incodewetrustinc.blogspot.com/...
Use maven plugin: ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.7.1</version> <configuration> <parallel>classes</parallel> <threadCount>5</threadCount> </config...
Running junit tests in parallel in a Maven build?
[ "", "java", "maven", "junit", "" ]
How do YOU reduce compile time, and linking time for VC++ projects (native C++)? Please specify if each suggestion applies to debug, release, or both.
It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in: ``` // Forward declaration stuff namespace plotter { namespace logic { class Plotter; } } // Real stuff namespace plotter { namespace samples { ...
Use [the Handle/Body pattern](http://c2.com/cgi/wiki?HandleBodyPattern) (also sometimes known as "pimpl", "adapter", "decorator", "bridge" or "wrapper"). By isolating the implementation of your classes into your .cpp files, they need only be compiled once. Most changes do not require changes to the header file so it me...
How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)?
[ "", "c++", "visual-c++", "compilation", "" ]
I need to write a component for an application that interacts tightly with a command line application. The command line application asks a series of questions, performs some computations, then terminates (which i need to detect). Essentially, i want to wrap up this interaction in a wrapper class. Has any one achieved ...
You would need to redirect both the input and output streams, using `Process`; it is slightly trickier handling both, since you need to be careful that things aren't lost in the buffers (causing deadlock). * MSDN : [Redirecting input](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirect...
I get dinged when my responses are just links to elsewhere. I don't see where the link to the C# Corner article helps much. The question is 10 years old today but it should have been clarified. The question does not specify whether there are line endings (CrLf) at the end of each question. Assuming there are, as in th...
Best way to interact with Command Line application
[ "", "c#", "windows", ".net-3.5", "" ]
Starting to build web applications for mobile devices (any phone). What would be the best approach using ASP.NET 3.5/ASP.NET 4.0 and C#? UPDATE (feb2010) Any news using windows mobile 7?
It depends if you really want to **support every cell phone** or only high end or new phone like the iPhone which don't have many limitations rendering web pages. If you could ask for real **HTML rendering, Javascript and cookies support on the phone as requirement**, then the real constraint is the **limited size of t...
A couple things I should mention since I work on a wireless network in Canada. Try and keep any images small (or even non existent) to increase load times and reduce data charges. On our network, if the user is not subscribed to a plan, our network charges $15/mb. Some unoptimized images a phone tries to download could...
Web for mobile devices - best practices for ASP.NET
[ "", "c#", "mobile", "windows-phone-7", "windows-phone", "" ]
In PHP, if you define a class, and then instantiate an object of that class, it's possible to later arbitrarily add new members to that class. For example: ``` class foo { public $bar = 5; } $A = new foo; $A->temp = 10; ``` However, I'd like the ability to make it impossible to add new members this way. Basicall...
No. There's no better way than `__set` in a base class — yet. This is a known problem and is [planned to be addressed in the future](http://wiki.php.net/todo/php53): > Introduce concept of “strict classes” that do not permit dynamic property creation
Nop, only \_\_set. Perhaps you can use inheritance to avoid rewriting it everywhere.
Locking class members in PHP
[ "", "php", "oop", "class", "" ]
Currently I am using FOP to generate a pdf from java code and an xslt document. The FOP spits out a PDF file that is displayed (embeded) into a webpage. The documents can range between one and several thousand pages long, and it can take some time to generate them. Is there a better tool that and do this? Is FOP the b...
This answer is too late for you, but in case it helps other searchers, [Docmosis](http://www.docmosis.com) can generate documents at a fairly hefty rate, and can spread a high load across multiple machines. It uses OpenOffice as the underlying format conversion engine, adding document population and manipulation facili...
We use [iText](http://www.lowagie.com/iText/). Here is a blog entry [Comparing Apache FOP with iText](http://blog.xebia.com/2008/03/03/comparing-apache-fop-with-itext/). Judging by your usage (generate a pdf from java code and an xslt document) it seems like FOP is the better choice for you. EDIT: This forum post ab...
Creating a PDF from Java and Displaying it in a webpage
[ "", "java", "pdf-generation", "apache-fop", "" ]
I have a view which is derived from CEditView. It is read only. I would like to set the text as a kind of logging, but nothing shows up on the screen. If I inspect `temp` in the debugger after `GetEditCtrl().GetWindowText(temp);` I can see that the text is indeed changing internally, but I see nothing on the screen. `...
Turns out that a third-party UI toolkit was reconstructing the View (who knows why?) so my pointer to it was stale. Thus, I was actually refreshing a different view!
The problem seems to lie somewhere other than in the code you posted. I created a new MFC app with the view derived from CEditView, and the code you're using to add the text worked ok, although I did have to wrap the literal `"\r\n"` inside an explicit temporary `CString`, as in: ``` GetEditCtrl().SetWindowText(temp +...
CEditView not showing text
[ "", "c++", "mfc", "" ]
If i have an interface: ``` interface IFoo { int Offset {get;} } ``` can i have this: ``` interface IBar: IFoo { int Offset {set;} } ``` so consumers of IBar will be able to set or get?
No, you can't! (I was about to write "Yes", but after reading Anthony's post, and trying out a few tweaks, I found the answer to be NO!) ``` class FooBar : IFoo, IBar { public int Offset{get;set;} } ``` (Will generate a warning as Anthony points out, which can be fixed by adding the "new" keyword.) When trying ...
This is close but no banana. ``` interface IFoo { int Offset { get; } } interface IBar : IFoo { new int Offset { set; } } class Thing : IBar { public int Offset { get; set; } } ``` Note the `new` keyword in IBar, but this overrides the get accessor of IFoo so IBar doesn't have a get. Hence no you can't ...
Interface inheritance
[ "", "c#", "interface", "" ]
How do I Deserialize this XML document: ``` <?xml version="1.0" encoding="utf-8"?> <Cars> <Car> <StockNumber>1020</StockNumber> <Make>Nissan</Make> <Model>Sentra</Model> </Car> <Car> <StockNumber>1010</StockNumber> <Make>Toyota</Make> <Model>Corolla</Model> </Car> <Car> <StockNumb...
Here's a working version. I changed the `XmlElementAttribute` labels to `XmlElement` because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the `reader.ReadToEnd();` (that [function](http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx) reads the ...
How about you just save the xml to a file, and use [xsd](http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx) to generate C# classes? 1. Write the file to disk (I named it foo.xml) 2. Generate the xsd: `xsd foo.xml` 3. Generate the C#: `xsd foo.xsd /classes` Et voila - and C# code file that should be able to read t...
How to Deserialize XML document
[ "", "c#", "asp.net", "xml", "serialization", "xml-deserialization", "" ]
How can I implement the following in python? ``` #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } ``` Output: > What is your name? Nick > > You said: Nick
Call ``` name = raw_input('What is your name?') ``` and ``` print 'You said', name ```
Look at the `print` statement and the `raw_input()` function. Or look at `sys.stdin.read()` and `sys.stdout.write()`. When using `sys.stdout`, don't forget to flush.
How can the user communicate with my python script using the shell?
[ "", "python", "" ]
How do I convert a PIL `Image` back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's `PixelAccess` allows? I can convert it to a NumPy array via: ``` pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) ``` But how do I load it back ...
You're not saying how exactly `putdata()` is not behaving. I'm assuming you're doing ``` >>> pic.putdata(a) Traceback (most recent call last): File "...blablabla.../PIL/Image.py", line 1185, in putdata self.im.putdata(data, scale, offset) SystemError: new style getargs format but argument is not a tuple ``` Thi...
Open `I` as an array: ``` >>> I = numpy.asarray(PIL.Image.open('test.jpg')) ``` Do some stuff to `I`, then, convert it back to an image: ``` >>> im = PIL.Image.fromarray(numpy.uint8(I)) ``` Source: [Filter numpy images with FFT, Python](http://barnesc.blogspot.com/2007/09/filter-numpy-images-with-fft-python.html) ...
How do I convert a PIL Image into a NumPy array?
[ "", "python", "image", "numpy", "python-imaging-library", "numpy-ndarray", "" ]
Suppose I have a database table that has a timedate column of the last time it was updated or inserted. Which would be preferable: 1. Have a trigger update the field. 2. Have the program that's doing the insertion/update set the field. The first option seems to be the easiest since I don't even have to recompile to d...
The first option can be more robust because the database will be maintaining the field. This comes with the possible overhead of using triggers. If you could have other apps writing to this table in the future, via their own interfaces, I'd go with a trigger so you're not repeating that logic anywhere else. If your a...
You didn't mention **3. Use a stored procedure to update the table.** The procedure can set timestamps as desired. Perhaps that's not feasible for you, but I didn't see it mentioned.
What is the best way to maintain a LastUpdatedDate column in SQL?
[ "", "sql", "sql-server", "database", "sql-server-2005", "triggers", "" ]
We are just starting to migrate/reimplement an ERP system to Java with Hibernate, targeting a concurrent user count of 50-100 users using the system. We use MS SQL Server as database server, which is good enough for the load. The old system doesn't use transactions and relies for critical parts (e.g. stock changes) on...
99 times out of 100, read committed is the right answer. That ensures that you only see changes that have been committed by the other session (and, thus, results that are consistent, assuming you've designed your transactions correctly). But it doesn't impose the locking overhead (particularly in non-Oracle databases) ...
It really depends a lot on how you design your application, the easy answer is just run at READ\_COMMITTED. You can make an argument that if you design your system with it in mind that you could use READ\_UNCOMMITTED as the default and only increase the isolation level when you need it. The vast majority of your trans...
What is the best default transaction isolation level for an ERP, if any?
[ "", "sql", "database", "database-design", "transactions", "isolation-level", "" ]
Is there a recommended way to bounce an asp.net application besides touching web.config from inside the application? is `HttpRuntime.UnloadAppDomain()`; the preferred way to do this ? and if so where do you do this? In the unload of a page or some other place in the application?
If this is .NET 2.0 or greater, then you can add in an "App\_offline.htm" file, make a request to the server, remove it, and then make another request to the server. This sequence of events will force ASP.NET to unload the application for as long as the app\_offline.htm file exists in the folder. Scott Guthrie's blog...
Touching web.config from inside an application is a bad idea, IMO. Also, the idea of having a file that you modify is a little hackney, IMO. The documentation specifically states that [`UnloadAppDomain`](http://msdn.microsoft.com/en-us/library/system.web.httpruntime.unloadappdomain.aspx) will shut the application down...
how to restart asp.net application besides modifying web.config
[ "", "c#", "asp.net", "restart", "" ]
I'm storing some additional per-user information using the [`AUTH_PROFILE_MODULE`](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). We can access the user in a Django template using `{{ request.user }}` but how do we access fields in the profile since the profile is only a...
Use `{{ request.user.get_profile.whatever }}`. Django's templating language automatically calls things that are callable - in this case, the `.get_profile()` method.
Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.
How to access the user profile in a Django template?
[ "", "python", "django", "django-templates", "" ]
I'm currently learning the APIs related to Intel's parallelization libraries such as TBB, MKL and IPP. I was wondering, though, whether it's also worth looking at AMD's part of the puzzle. Or would that just be a waste of time? (I must confess, I have no clue about AMD's library support - at all - so would appreciate a...
The MKL and IPP libraries will perform (nearly) as well on AMD machines. My guess is that TBB will also run just fine on AMD boxes. If I had to suggest a technology that would be beneficial and useful to both, it would be to master the OpenMP libraries. The Intel compiler with the OpenMP extensions is stunningly fast a...
Only worth it if you are specifically interested in building something like Video games, Operating systems, database servers, or virtualization software. In other words: if you have a segment where you care enough about performance to take the time to do it (and do it right) in assembler. The same is true for Intel.
Is it worth learning AMD-specific APIs?
[ "", "c++", "intel", "amd-processor", "" ]
Given two sets of values: ``` var subset = new[] { 2, 4, 6, 8 }; var superset = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ``` how do I determine if `superset` contains all elements of `subset`? I have come up with this: ``` superset.Intersect(subset).Count() == subset.Count() ``` Is this the most logical and effici...
How about Not Any? ``` bool contained = !subset.Except(superset).Any(); ```
So, my other answer was pretty easy to use. But it's an O(n\*m) solution. Here's a slightly less friendly O(n+m) solution. This should be used if superset is HUGE. It avoids repeatedly enumerating superset. ``` HashSet<int> hashSet = new HashSet<int>(superset); bool contained = subset.All(i => hashSet.Contains(i)); `...
Determine if a sequence contains all elements of another sequence using Linq
[ "", "c#", "linq", "" ]
I need to use a priority queue in my Python code, and: * am looking for any **fast** implementations for priority queues * optimally, I'd like the queue to be **generic** (i.e. work well for any object with a specified comparison operator). Looking around for something efficient, I came upon [heapq](http://docs.pytho...
You can use [Queue.PriorityQueue](http://docs.python.org/library/queue.html#Queue.PriorityQueue). Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of `(priority, thing)` and you're set.
When using a priority queue, decrease-key is a must-have operation for many algorithms (Dijkstra's Algorithm, A\*, OPTICS), I wonder why Python's built-in priority queue does not support it. None of the other answers supply a solution that supports this functionality. A priority queue which also supports decrease-key ...
A generic priority queue for Python
[ "", "python", "queue", "" ]
I have a system-wide manual reset event that I create by doing the following: ``` EventWaitHandle notifyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, notifyEventName, out createdEvent); ``` Several processes create this event (e.g. it is shared amongst them). It is used for notifying when something g...
You're using the EventWaitHandle class incorrectly. A reset event shouldn't be used to signal multiple threads. Instead, you need to create a reset event for each thread and then when you're ready loop through them all and use Set(). The master thread should not be calling the Reset() method. Each thread should be resp...
I had the same problem and surprisingly couldn't find any good solution on the web for this loose-coupled / fire and forget / multiple listeners type of event, so here is what I came up with. Note the solution with the timeout between `Set()` and `Reset()` calls has also a race-condition issue (beyond the fact it reli...
Properly notifying all listeners of a system wide named manual reset event and then immediately resetting it
[ "", "c#", "windows", "multithreading", "events", "" ]
I've seen on the internet quite a few examples of binding a boolean to the Visibility property of a control in XAML. Most of the good examples use a BooleanToVisibiliy converter. I'd like to just set the Visible property on the control to bind to a System.Windows.Visibility property in the code-behind, but it doesn't ...
I think the problem is that WPF can't know that your ActionsVisible property has changed since you've not notified the fact. Your class will need to implement INotifyPropertyChanged, then in your set method for ActionsVisible you'll need to fire the PropertyChanged event with ActionsVisible as the property name that h...
Change your property to be a DependencyProperty. This will handle the updating for you. ``` public Visibility ActionsVisible { get { return (Visibility)GetValue(ActionsVisibleProperty); } set { SetValue(ActionsVisibleProperty, value); } } // Using a DependencyProperty as the backin...
Binding Visibility in XAML to a Visibility property
[ "", "c#", "xaml", "binding", "visibility", "" ]
I'm fairly new to C# programming. I am making a program for fun that adds two numbers together, than displays the sum in a message box. I have two numericUpDowns and a button on my form. When the button is pushed I want it to display a message box with the answer. The problem is, I am unsure how to add the twp values...
`this.numericUpDown1.Value + this.numericUpDown2.Value` is actually evaluating properly to a number, so you're actually very close. The problem is that the `MessageBox.Show()` function, needs a string as an argument, and you're giving it a number. To convert the result to a string, add `.ToString()` to it. Like: ``` ...
This works. ``` decimal total = this.numericUpDown1.Value + this.numericUpDown2.Value; MessageBox.Show(total.ToString()); ``` MessageBox.Show expects a string as a parameter (that's the first error message).
New C# Programmer - Adding two numericUpDown values together?
[ "", "c#", "numericupdown", "" ]
What should a small team choose for their first game, when they are low on time but have big ambitions? I'm an experienced programmer, but haven't done any game programming before this. My designer is very talented and artistic, he has worked with 3D about an year ago but hasn't done it since so it could take him some ...
You don't have to use 3D to allow for a "3D look". Things like rotations, motions or transformations can be prerecorded or prerendered as animations or image sequences and seamlessly integrated into a 2D game. The only thing that is not possible in 2D is to navigate freely within your "game space" (like walking or flyi...
You should go 2D. You have stated several reasons to take this approach: * You are a small team, and 3D takes more work. * It's your first game, so you need to keep it as simple as possible, or the project may fail (you are exposed to a lot of risk!) * The 3D artist needs to relearn the crafts! * You have a ...
Which to choose: 2D or 3D for a java game
[ "", "java", "3d", "2d", "" ]
I've got few files in resources (xsd files) that i use for validating received xml messages. The resource file i use is named **AppResources.resx** and it contains a file called **clientModels.xsd**. When i try to use the file like this: AppResources.clientModels, i get a string with the file's content. i would like to...
Could you feed the string you get into a System.IO.StringReader, perhaps? That may do what you want. You may also want to check out MemoryStream.
here is the code from the link ``` //Namespace reference using System; using System.Resources; #region ReadResourceFile /// <summary> /// method for reading a value from a resource file /// (.resx file) /// </summary> /// <param name="file">file to read from</param> /// <param name="key">key to get the value for</pa...
how to get file from resources as a stream? (.net)
[ "", "c#", ".net", "resources", "" ]
First, to make my job explaining a bit easier, here's some of my code: ``` JSpinner spin = new JSpinner(); JFormattedTextField text = getTextField(spin); text.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // Do stuff... } }); ...
I know this is not the action listener...but maybe this can work for you? ``` text.addKeyListener( new KeyAdapter() { @Override public void keyReleased( final KeyEvent e ) { if ( e.getKeyCode() == KeyEvent.VK_ENTER ) { System.out.println( "enter pressed" ...
I just ran into an issue relating to this, myself. In my case, I had a JSpinner with a `SpinnerNumberModel` setup so I could input numerical ID values, and then retrieve them from a remote database. This worked all well and good with a JButton as my trigger for the query, but I wanted to be able to switch focus to the ...
Getting ENTER to work with a JSpinner the way it does with a JTextField
[ "", "java", "swing", "jtextfield", "listeners", "jspinner", "" ]
I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block.... *EDIT* This is ...
Once you get the name of the function, use a dispatch dict to run the function: ``` def mysum(...): ... def myotherstuff(...): ... # create dispatch dict: myfunctions = {'sum': mysum, 'stuff': myotherstuff} # run your parser: function_name, parameters = parse_result(line) # run the function: myfunctions[function_na...
Check out [PyParsing](http://pyparsing.wikispaces.com/), it allows for definition of the grammar directly in Python code: Assuming a function call is just `somename()`: ``` >>> from pyparsing import * >>> grammar = Word(alphas + "_", alphanums + "_")("func_name") + "()" + StringEnd() >>> grammar.parseString("ab()\n"...
Parsing Functions
[ "", "python", "parsing", "" ]
Do you guys think internationalization should only done at the code level or should it be done in the database as well. Are there any design patterns or accepted practices for internationalizing databases? If you think it's a code problem then do you just use Resource files to look up a key returned from the database...
Internationalization extends to the database insofar as your columns will be able to hold the data. NText, NChar, NVarchar instead of Text, Char, Varchar. As far as your UI goes, for non-changing labels, resources files are a good method to use.
If you refer to making your app support multiple languages at the UI level, then there are more possibilities. If the labels never change, unless when you release a new version, then resource files that get embedded in the executable or assembly itself are your best bet, since they work faster. If your labels, on the o...
Internationalization in the database
[ "", "c#", "sql-server", "internationalization", "" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](https://stackoverflow.com/questions/287757...
There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like: ``` [Section 3] barList=item1,item2 ``` It's not pretty but it's functional for most simple lists.
I am using a combination of ConfigParser and JSON: ``` [Foo] fibs: [1,1,2,3,5,8,13] ``` just read it with: ``` >>> json.loads(config.get("Foo","fibs")) [1, 1, 2, 3, 5, 8, 13] ``` You can even break lines if your list is long (thanks @peter-smit): ``` [Bar] files_to_check = [ "/path/to/file1", "/path/to/f...
Lists in ConfigParser
[ "", "python", "configparser", "" ]
I need to find a path or paths down a complicated graph structure. The graph is built using something similar to this: ``` class Node { public string Value { get; set;} public List<Node> Nodes { get; set;} public Node() { Nodes = new List<Node>(); } } ``` What makes this complicated is th...
If you're issue is related to Pathfinding, you may want to google for "A star" or "A\*". Its a common and efficient pathfinding algorithm. See [this article](http://www.gamedev.net/reference/articles/article2003.asp) for an example directly related to your problem. You may also want to look at the [Dijsktra Algorithm]...
I'm not sure whether your intended output is *all* paths to the goal, the *best* path to the goal (by some metric, e.g. path length), or just *any* path to the goal. Assuming the latter, I'd start with the recursive strategy, including tracking of visited nodes as outlined by Brann, and make these changes: 1. Add par...
Recursive lambda expression to find the path(s) through a directed graph?
[ "", "c#", "recursion", "directed-graph", "" ]
This is a bit special: I'm loading some HTML in string form into the WebBrowser control via the DocumentText property. Now when I print the page with a PDF printer (Bullzip PDF Printer in my case) it always takes the URL as document name which is "about:blank". Is there any way to change this to another value by ...
There are a couple of options that I am aware of though my knowledge on this subject is a bit dated. The first is to change the computer settings in Internet Options. Regardless of whether this is done by hand or through a registry change script, it is simple for the developer, but obviously not the best approach from...
You can change the header and footer such that the URL property is not printed.
WebBrowser control: How to overwrite URL property
[ "", "c#", ".net", "printing", "webbrowser-control", "" ]
I downloaded the Eclipse PDT 2.0 GA release (Eclipse 3.4), however, it doesn't look like the Ant tools are included in this package. How can I install the eclipse Ant tools (editor, executable, etc...)?
So I found the answer to my own question. You need to install the Eclipse Java Development Tools. These can be found under Ganymede > Java Development > Eclipse Java Development Tools in Help > Software Updates > Available Software.
This drove me crazy a couple days ago. In Galileo the update process is slightly different, which is bad forward design if you ask me (but I digress). Here's how you do it in Eclipse 3.5. Help > Install New Software From "Work with:" dropdown choose "Galileo - <http://download.eclipse.org/releases/galileo>" Then exp...
Eclipse PDT Ant
[ "", "php", "eclipse", "development-environment", "eclipse-pdt", "" ]
I have used ValidatorEnable to disable a RequiredFieldValidator in javascript. However on postback the control being validated by the validator is still validated ... even though I disabled the validator on the client. I understand why this is happening since I've only disabled the client validation ... however is the...
Peanut, I just encounted the same issue you are. On the client-side I have javascript that disables required field validators depending on their selections in the UI. However, the server side validation was still firing. During load, I added a method to disable my validators using the same rules I have on the javascri...
You could, when you disable the client validation (presumably with JavasScript?), also set up values in a hidden input that you could query in page load method. This way you can examine the value of the hidden input (via the Request.Form{] array) to disable the validators on the server side prior to the validation even...
ASP.NET - how to stop unrequired server validation
[ "", "asp.net", "javascript", "validation", "" ]
Is there any work being done to create a C# compiler to produce native exe's? e.g. the output is a native exe and NOT a .NET assembly.
Why don't you try NGen. For exemple Paint.NET use nGen to create native images after installation.
If you want a standalone deployment (i.e. without needing the framework), there are a few options - see [here](http://www.yoda.arachsys.com/csharp/faq/#framework.required). However, I'm not aware of anything that will reliably produce purely unmanaged code. What is the use-case you have in mind? For embedded etc there ...
Is there any work being done to create a C# compiler to produce native exe's?
[ "", "c#", "compiler-construction", "native", "exe", "" ]
Backdrop: There are two forms, the main application form and a form to edit various settings for the operations of main application. What would be the proper way to show the frmSettings form and how to dispose it once clicked OK or Cancel in the actual frmSettings form?
Perhaps a Dialog would be better suited to your Settings "form." There are subtle differences between a dialog and a form that would make the dialog easier to handle. A return code indicating the button that was clicked makes dialogs useful. Supposing that you used a dialog - a using statement could be used (off the t...
fyi, using "frm" is not a recommended part of the C# coding guidelines. [Microsoft prefers you don't use hungarian notation in .NET at all.](http://blogs.msdn.com/brada/articles/361363.aspx)
C#: What is the proper way to show a form for "frmMainForm" settings and disposing?
[ "", "c#", "" ]
I'm in the process of trying to migrate my ASPNET site to Django. All my current data is tied up in MS SQL Server on a shared host that (helpfully) doesn't support python... I could use my existing code to export all the data but I've also stopped using Windows. The site is mainly compiled VB.NET so I'd need to install...
``` Select table_name from information_schema.tables ``` for any given table you can get the metadata with ``` sp_help tablename ```
You do query with : ``` SHOW TABLES; ``` (you need to select `DB` before this.)
List table names
[ "", "php", "sql-server", "" ]
In C++ you are able to compile files that are not included in the solution, with c# this is not the case. Is there a way to keep a file in a project but not have the standard SCCI provider attempt to keep checking in the file? Essentially what we are wanting to do is to create "by developer" code ability similar to h...
Well, it seems after working off the post here, and literally trying "wierd" things, I had an idea. Essentially I used the \*.csproj.user file, declared a UserConfig property, added a new Constant (for code checks), and did an ItemGroup with the condition of the UserConfig. All this fell under the DEBUG flag. The onl...
MSBuild has [Conditional Constructs](http://msdn.microsoft.com/en-us/library/ms164307.aspx). All you have to do is modify the Solution file to include what you want. The end result would look very similar to your example code. ``` <When Condition=" '$(Configuration)'=='TOM' "> <ItemGroup> <Compile Include="tomC...
How do I create compiled user files in Visual Studio 2008?
[ "", "c#", ".net", "vb.net", "visual-studio-2008", "" ]
Is there a way in C# sytax for defining a new line? (Like in VB \_ ) Example: Instead of: ``` string myStr = "very long string" + "another long string"; ``` This: ``` string myStr = "very long string \something another long string" ``` Or; does compiler handles this and does something like; "string" + "string" ->...
Compiler turns "ABC" + "DEF" into "ABCDEF" so there's no cost in using +
You can use ``` string myStr = @"very long string another long string"; ``` @" is the beginning of a string literal and this kind of string does not end until the next " character is found. There is not an exact syntax for c# which does the same thing as \_ character in vb. So if you want to avoid including a new li...
How to put a new line inside a string in C# source code?
[ "", "c#", "syntax", "" ]
I'd like to figure out (in runtime) whether or not two regular expressions intersect (i.e. if they do there exist one or more string the matches both regular expressions). Algorithm needs to be pretty fast as I need to loop through a database and check existing values. Found some theory on this but no implementations...
The obvious solution would be to convert the regexes to DFAs, compute the intersection of the DFAs (trivial) and see if there's anything the resulting DFA can accept (also trivial). The only hard part is converting the regexes to DFAs, which requires some work.
Here's an [implementation in Haskell](http://sulzmann.blogspot.com/2008/11/playing-with-regular-expressions.html) using partial derivatives of regexps. A comment to that post points out an issue with the approach in Chris Dodd's answer.
Algorithm: Intersection of two regexps
[ "", "c#", "algorithm", "" ]
I am wondering if there are any additional optimizations I can implement to improve the speed of reflective invocations in Java. Not that the performance is prohibitive, but I get the willies when thinking about some piece of code in a library I am writing being implemented in a tight loop somewhere. Consider a utilit...
The comments below relate to Sun's implementation, in particular OpenJDK 6. Your mileage may vary with other Java platform implementations. `java.lang.Class` does some caching itself, so implementing your own cache may not improve things very much. Do timing tests with and without manual caching. The actual invocatio...
I ran some tests around Chris Jester-Young's answer and using the **verbose** options, I definitely observed the compiler take some action around the 15th invocation. Hard to say if there's much performance differential without a more sophisticated test, but it is persuasive. Here's the output: ``` Test# 0 Test# 1 Tes...
Any way to further optimize Java reflective method invocation?
[ "", "java", "performance", "reflection", "" ]
Say, for example, I have many web applications using the same class library compiled into a dll in C# and I want to update a specific method of a class for a particular application. I don't want to change the existing code because it will affect everyone, and I don't want to inherit from a class to create a new one. I ...
Polymorphism seems to be the best solution for this. This way base classes can be compiled and left alone and inherited classes can be changed for individual applications without changing the way the original is used (unless necessary). BaseClasses.cs ``` public class BaseUser { public BaseUser() {} public ...
Maybe extension methods would work?
What's the best way to add custom functionality to existing code in C#?
[ "", "c#", "inheritance", "" ]
I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how. I'm writing a Django application, and so far have only created the models (and customi...
**Is a function to test each model within the ModelTests class a good way of writing tests?** No. **What exactly should I be testing for?** * That creating a model with all of the fields completed works? * That a half complete model fails? * That any special cases are tested (like a null and is\_required=False)? * I...
I'm not exactly sure of the specifics of what you're trying to test here, I'd need more code snippets for this, but I can give you some general advice. First, read the unit testing chapter of "Dive into Python" (it's free online! <https://diveintopython3.net/unit-testing.html>), it's a great explanation of unit testin...
Writing unit tests in Django / Python
[ "", "python", "django", "unit-testing", "" ]
Im looing for a way to have a simple "on mouse over"-effect. (I want the page to show a dialogbox)
Use some Javascript. Jquery makes thoose things quite easy. Do you already have the information or is it something you want to pull from the server when the mouse is hovering? With Jquery you could do something like this ``` <script type="javascript"> $(document).ready( function(){ $("divToShow").hide(); ...
I'd go for the [jQuery Tooltip plug-in](http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/) from Jörn Zaefferer
Ajax in ASP.NET MVC Framework
[ "", "javascript", "ajax", "asp.net-mvc", "" ]
I need to build an assembler for a CPU architecture that I've built. The architecture is similar to MIPS, but this is of no importance. I started using C#, although C++ would be more appropriate. (C# means faster development time for me). My only problem is that I can't come with a good design for this application. I...
I've written three or four simple assemblers. Without using a parser generator, what I did was model the [S-C assembler](http://stjarnhimlen.se/apple2/) that I knew best for 6502. To do this, I used a simple syntax - a line was one of the following: ``` nothing [label] [instruction] [comment] [label] [directive] [com...
Look at this Assembler Development Kit from Randy Hyde's author of the famous "The Art of Assembly Language": [The Assembler Developer's Kit](http://www.plantation-productions.com/Webster/RollYourOwn/)
Building an assembler
[ "", "c#", "assembly", "" ]
Is it necessary to register a compiled DLL (written in C# .NET) on a target machine. The target machine will have .NET installed, is it enough to simply drop the DLL onto the target machine?
I think you're confusing things a little. Registering a dll has never been needed in order to use it. Using a dll requires only to load it (given a known location or if the library is in the system path) and get the address of the function you wanted to use. Registering the dll was used when distributing COM or Activ...
You need to "drop" it into a directory where the application needing it will find it. If there are multiple applications, or you want to "drop" the file somewhere other than the application directory, you generally need to either adjust the PATH variable, or register the assembly in the Global Assembly Cache (GAC).
In .NET, is there a need to register the DLL?
[ "", "c#", ".net", "dllregistration", "" ]
what is the best way to deploy a winforms app if you know you are going to be doing frequent releases
Click Once is your best bet.
Click Once is great if you know the customer base will always have access to an internet connection and they only ever need a single version installed. This is probably true for the majority of apps. But if that is not the case then I recommend you ensure that people can install different versions of your application ...
deployment of winforms applications
[ "", "c#", "deployment", "" ]
I am messing around with different PHP logging frameworks. I am currently trying PEAR::Log. I figured that I would use its `singleton` function to make sure there was only one instance of the class around. I have a small daemon-like script I wanted to add logging to because it was probably the simplest script in the s...
I don't know much about PEAR::Log, but why not create another singleton that wraps/simplifies logging. ``` class Logger { private static $log; private function __construct() { } public static function init(Log $log) { self::$log = $log; } public static function get() { return se...
Better yet, if your end goal is to just be able to blindly call ``` Logger::Write("Something happened"); ``` wherever you need it, you can take Michal's solution one step further with ``` class Logger { private static $log = null; public static function init(Log $log) { self::$log = $log; } ...
What's the best to way to manage a singleton?
[ "", "php", "design-patterns", "singleton", "" ]
It was hinted in a [comment to an answer to this question](https://stackoverflow.com/questions/433525/choosing-asp-net-over-php-or-perl#433610) that PHP can not reverse Unicode strings. > As for Unicode, it works in PHP > because most apps process it as > binary. Yes, PHP is 8-bit clean. Try > the equivalent of this i...
Grapheme functions handle UTF-8 string more correctly than mbstring and PCRE functions/ Mbstring and PCRE may break characters. You can see the defference between them by executing the following code. ``` function str_to_array($string) { $length = grapheme_strlen($string); $ret = []; for ($i = 0; $i < $le...
here's another approach using regex: ``` function utf8_strrev($str){ preg_match_all('/./us', $str, $ar); return implode(array_reverse($ar[0])); } ```
How to reverse a Unicode string
[ "", "php", "string", "unicode", "reverse", "" ]
I am looking at some javascript code and it has this in a function: ``` $$('.CssClass').each(function(x) { .... } ) ``` I get that the intent is to apply the anonymous function to each element with a class of CssClass, but I can't work what the $$ refers to ... and can't google for $$! **Update**: thanks for the hin...
Probably [this](http://www.prototypejs.org/api/utility#method-%24%24) prototype function: ``` $$(cssRule...) -> [HTMLElement...] ``` > Takes an arbitrary number of CSS > selectors (strings) and returns a > document-order array of extended DOM > elements that match any of them. [http://www.prototypejs.org/api/utility...
$ is an ordinary symbol character, thus "$", "$$", "$$$" are ordinary variables. the meaning of $ depends upon the libraries that are in use; in jQuery the $-function creates a jquery object from a css selector, e.g. $("DIV") is a collection of all DIVs in the current document.
What does $$ mean in Javascript?
[ "", "javascript", "prototypejs", "" ]
My problem is very similar to eight queens puzzle. I've got 2-dimensional array (N x N) that for example, looks like this: ``` 0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-> ``` I'm checking horizontally, vertically and diagonally for occurrences of 1 ``` \,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0...
One possible solution: ``` def collision(x1, y1, x2, y2): return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2) ``` i.e. there is a collision if the two points are on the same horizontal row, same vertical row or same diagonal (vertical distance == horizontal distance).
Your description sounds like an instance of an exact cover problem, which can be solved using an algorithm Knuth calls [Algorithm X](http://en.wikipedia.org/wiki/Algorithm_X). I have implemented a [Sudoku solver in Javascript](http://hewgill.com/sudoku/) using this technique. You can probably find implementations in Py...
Checking 2-dimensional array (like eight queens puzzle)
[ "", "python", "arrays", "puzzle", "" ]
When writing destructive queries (e.g., DELETE or UPDATE) in SQL Server Management Studio I always find myself wishing I could preview the results of the query without actually running it. Access very conveniently allows you to do this, but I prefer to code my SQL by hand which, sadly, Access is very poor at. So my qu...
I would use the OUTPUT clause present in SQL SERVER 2008 onwards... [**OUTPUT Clause (Transact-SQL)**](http://msdn.microsoft.com/en-us/library/ms177564.aspx) Something like... ``` BEGIN TRANSACTION DELETE [table] OUTPUT deleted.* WHERE [woof] ROLLBACK TRANSACTION ``` INSERTs and UPDATEs can use the 'inserted' ta...
I live in fear of someone doing this to my databases so I always ask my Team to do something like the following: ``` BEGIN TRAN   DELETE FROM X -- SELECT * FROM X FROM Table A as X JOIN Table B ON Blah blah blah WHERE blah blah blah   ROLLBACK TRAN COMMIT TRAN ``` In this way, if you accidentally hit F5 (done it!) yo...
How do I preview a destructive SQL query?
[ "", "sql", "sql-server", "" ]
I have a custom object that implements INotifyPropertyChanged. I have a collection of these objects where the collection is based on BindingList I have created a binding source for the collection, and set the datasources of the bindingsource and datagridview. Everything works great, except I need to update properties ...
I found this class in a forum that works. Just use this instead of BindingList ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Threading; namespace Utility { public class ThreadedBindingList<T> : BindingList<T> { Sync...
Since I took the time to format the sample for my needs I might as well post it here as a readable reference. Nothing changed except formatting. ``` using System.ComponentModel; using System.Threading; namespace Utility { public class ThreadedBindingList : BindingList { SynchronizationContext ctx = Synchro...
How do you correctly update a databound datagridview from a background thread
[ "", "c#", "multithreading", "data-binding", "datagridview", "inotifypropertychanged", "" ]
I have a localization issue. One of my industrious coworkers has replaced all the strings throughout our application with constants that are contained in a dictionary. That dictionary gets various strings placed in it once the user selects a language (English by default, but target languages are German, Spanish, Frenc...
I have a very short [guide to debugging Unicode problems](http://pobox.com/~skeet/csharp/debuggingunicode.html). It's targeted at fetching text from databases, but the same principles apply in general. The most important starting point IMO is to know what's actually in your string when it just shows a box. Dump the co...
I would say that most certainly Notepad is the culprit. Notepad does not deal well with unicode characters. If you want to hand edit this file, use something like [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm) which can handle unicode, and make sure you save the file as UTF-8. You can probably just use VS...
Display ñ on a C# .NET application
[ "", "c#", "unicode", "localization", "character-encoding", "" ]
I have an enumeration: `ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )` If I sort my table by this column I get them in the correct order defined above. However, I can't find a way to select a subset of these, e.g. everything before delta. Using `WHERE status < 'delta'` only returns alpha and beta, not gamma. It ...
You're trying to use data-manipulation methods on metadata, and this is bound to be awkward. This is a good reason to replace the `ENUM` with a foreign key to a lookup table. Then you can use conventional data-manipulation techniques.
You can use `status+0` to return the index of the ENUM, starting from 1. Refer <http://serghei.net/docs/database/mysql/doc/E/N/ENUM.html>
Can I compare MySQL enums?
[ "", "sql", "mysql", "enums", "compare", "" ]
Suppose I have files `a.cpp` and `b.cpp` and I get warnings in `a.cpp` and an error in `b.cpp`. I fix the error in `b.cpp` and recompile -- since Visual Studio doesn't have to recompile `a.cpp`, it doesn't remind me of the warnings it found before. I'd like to somehow have the warnings persist; however, I **don't** wa...
Essentially, you're out of luck. The C++ compilation will discard all of the errors and warnings. Because it only recompiles .CPP files that have a missing .OBJ file (i.e. the ones that had errors and failed last time), you'll only see the errors. You have a few options. Off the top of my head: * Write a macro that r...
You could go into the project settings and set all warnings as errors in the C/C++ tab (category: General).
How to make warnings persist in visual studio
[ "", "c++", "visual-studio", "warnings", "" ]
How is it possible to programmatically select an item in a WPF `TreeView`? The `ItemsControl` model seems to prevent it.
It's a real pain for some strange reason, you have to use ContainerFromItem to get the container, then invoke the select method. ``` // selectedItemObject is not a TreeViewItem, but an item from the collection that // populated the TreeView. var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemO...
For those who are still looking for the right solution to this problem here is the one below. I found this one in the comments to the Code Project article “WPF TreeView Selection” <http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx> by DaWanderer. It was posted by Kenrae on Nov 25 2008. This worked great for ...
How to programmatically select an item in a WPF TreeView?
[ "", "c#", ".net", "wpf", "treeview", "itemscontrol", "" ]
How would you implement a Plugin-system for your Java application? Is it possible to have an easy to use (for the developer) system which achieves the following: * Users put their plugins into a subdirectory of the app * The Plugin can provide a configuration screen * If you use a framework, is the license compatible...
First you need an interface that all plugins need to implement, e.g. ``` public interface Plugin { public void load(PluginConfiguration pluginConfiguration); public void run(); public void unload(); public JComponent getConfigurationPage(); } ``` Plugin authors should then bundle their plugins into JA...
Use [OSGi](http://en.wikipedia.org/wiki/OSGi). It is the foundation of the Eclipse plug-in system. [Equinox](http://en.wikipedia.org/wiki/Equinox_OSGi) is Eclipse's implementation (licensed EPL) and [Felix](http://felix.apache.org/) is the Apache Project's implementation (licensed Apache Public License). Eclipse prov...
Best way to build a Plugin system with Java
[ "", "java", "design-patterns", "plugins", "frameworks", "plugin-architecture", "" ]
I'm a student about to start my exam project, where I will be responsible for the server implementation of an online game targeting the flash player. I have a hard time to decide wether i should write my own lightweight server in Erlang or use the open source Red5. My experience is that java-developers tend to overcom...
I'd say use Red5 if you are ok with programming java - it might feel trivial to implement your own server but I'd guess you probably will find out that there are some more things to it than you are thinking of now. However, if you want to program in erlang and think you'll have loads of fun developing your own server ...
I think you need to estimate for yourself the effort for implementing your own, lightweight, server. Often ones own requirements are small and specific and implementing a server that meets them is the way to go. Also check out Blaze DS (Java flash server) and Juggernaut (ruby flash server). I think maybe Juggernaut is...
Should i write my own flash-server in Erlang or use Red5?
[ "", "java", "flash", "erlang", "red5", "online-game", "" ]
To be specific, I was trying this code: ``` package hello; public class Hello { Clock clock = new Clock(); public static void main(String args[]) { clock.sayTime(); } } ``` But it gave the error > Cannot access non-static field in static method main So I changed the declaration of `clock` to ...
`static` members belong to the class instead of a specific instance. It means that **only one instance of a `static` field exists**[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances. Since `static` methods also do not belong to a specific instance, they...
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class. So if you were to do a "new Hello" anywhere in your code: A- in the first scenar...
What does the 'static' keyword do in a class?
[ "", "java", "static", "oop", "language-features", "restriction", "" ]
I have read that private variables in a base class are technically inherited by child classes, but are not accessible. If this is correct, why do we say they are inherited when presumably they can only be accessed by reflection?
Subclassing is about inheriting *implementation*; and fields are an implementation detail. The fields are indeed present, and are available via reflection. But ultimately, it is the base-classes job to manage the state of those fields via any public/protected/etc members. But ultimately - if a base-class declares a p...
Private fields are inherited in the sense, that they take up space on the heap when allocated. However, the derived class cannot access them directly.
Are private static and instance variables inherited in C# and why?
[ "", "c#", "inheritance", "" ]
I would like to detect whether the OS I'm compiling on is Windows. Is there a simple macro I can check to verify that?
*[Edit: I assume you want to use compile-time macros to determine which environment you're on. Maybe you want to determine if you're running on Wine under Linux or something instead of Windows, but in general, your compiler targets a specific environment, and that is either Windows (DOS) or it isn't, but it's rarely (n...
There are a number of different ways to detect compilation, host, and runtime environments. All depending on exactly what you want to know. There are three broad types of environments: * **Build**: This is the environment in which the program is compiled. * **Host**: This is the environment in which the program is bei...
Are there any macros to determine if my code is being compiled to Windows?
[ "", "c++", "c", "operating-system", "c-preprocessor", "" ]
I need to work with array from several threads, so I use CRITICAL SECTION to give it an exclusive access to the data. Here is my template: ``` #include "stdafx.h" #ifndef SHAREDVECTOR_H #define SHAREDVECTOR_H #include <vector> #include <windows.h> template<class T> class SharedVector { std::vector<T> vect; ...
Just declare `cs` as: ``` mutable CRITICAL_SECTION cs; ``` or else remove the const clause on `size()` Entering a critical section modifies the `CRITICAL_SECTION`, and leaving modifies it again. Since entering and leaving a critical section doesn't make the `size()` method call logically non-`const`, I'd say leave i...
Also the code above is not Exception safe. There is no guarantee that push\_back() pop\_back() will not throw. If they do they will leave your critical section permanently locked. You should create a locker class that calls EnterCriticalSection() on construction and LeaveCriticalSection() on destruction. Also this m...
Problems using EnterCriticalSection
[ "", "c++", "winapi", "critical-section", "" ]
I want to know if the page is being accessed via http or https using JavaScript. Is there some sort of isSecure() method, or should I just parse it out of the URL somehow?
`location.protocol` should do it for you. (as in: ``` if (location.protocol === 'https:') { // page is secure } ``` )
You should be able to check `document.location.protocol` to see if it's "http:" or "https:"
How do I determine whether a page is secure via JavaScript?
[ "", "javascript", "https", "" ]
What is the equivalent of varchar(max) in Oracle? CLOB?
Varchars are limited to 4000 characters in Oracle. Other than that, you have to use a LONG or a CLOB. Prefer CLOBs. LONGs are the older equivalent. From [this Oracle documentation](http://www.cs.umbc.edu/help/oracle8/server.815/a68022/lob.htm): > **LOBs vs. LONG and LONG RAW** > > LOBs are different from the older LO...
As I understand it, a VARCHAR(MAX) data type is a SQL Server 2005 specific way of specifying a text field that can either be small (up to 8000 characters in SQL Server) ***or*** big (up to 2GB in SQL Server). The database handles the change in storage *behind the scenes* as the content grows from the small range to the...
What is the equivalent of varchar(max) in Oracle?
[ "", "sql", "sql-server", "oracle", "" ]
I need to batch create images with text. Requirements: 1. arbitrary size of bitmap 2. PNG format 3. transparent background 4. black text anti-aliased against transparency 5. adjustable character spacing 6. adjustable text position (x and y coordinates where text begins) 7. TrueType and/or Type1 support 8. Unix command...
Here's the SVG + ImageMagick solution: Programmatically create SVG documents based on this template, replacing "TEXT HERE" with the desired text content: ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <...
(5) indeed looks tricky, short of inserting dummy narrow-spaces into the string (which will break kerning) or using something much higher-level like the SVG or HTML/CSS renderer. However, if you don't mind getting your hands dirty, it looks quite easy to hack PIL's freetype renderer into adding horizontal space. See [...
Tools for creating text as bitmaps (anti-aliased text, custom spacing, transparent background)
[ "", "python", "fonts", "bitmap", "spacing", "unix", "" ]
So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly. Is there any way to debug templates besides iterating for every line of code?
Mako actually provides a [VERY nice way to track down errors in a template](http://docs.makotemplates.org/en/latest/usage.html#handling-exceptions): ``` from mako import exceptions try: template = lookup.get_template(uri) print template.render() except: print exceptions.html_error_template().render() ```
Looking at the [Flask-Mako](http://pythonhosted.org/Flask-Mako/) source, I found an undocumented configuration parameter called `MAKO_TRANSLATE_EXCEPTIONS`. Set this to `False` in your Flask app config and you'll get nice exceptions bubbling up from the template. This accomplishes the same thing as @Mariano suggested,...
How do you debug Mako templates?
[ "", "python", "debugging", "templates", "jinja2", "mako", "" ]
Is there any advantage to writing a PHP conditional like this: ``` if ($variable != NULL) { ``` versus ``` if (!empty($variable)) { ``` versus ``` if ($variable) { ``` Aren't they all same thing? It seems like the last is always the simplest if you are just trying to tell whether the variable exists or not. Thank...
I agree with Sean but I'll outline what each does in plain English: ``` if ($variable != NULL) { ``` `$variable` will be `NULL` if it hasn't been set. This is practically the same as `isset` and the same as the variable being undefined. ``` if (!empty($variable)) { ``` Generally, this checks whether `$variable` as ...
Check out [this table](http://de3.php.net/types.comparisons) to get the skinny on PHP comparison operators. There's a number of subtle differences between false, 0, "", NULL and variables that are simply undefined.
Are these PHP conditionals the same or does one have an advantage
[ "", "php", "variables", "conditional-statements", "" ]
It seems like my code works to check for null if I do ``` if ($tx) ``` or ``` if (isset($tx)) ``` why would I do the second one when it's harder to write?
I want to point out that everyone's reponse I've read here should have one caveat added: **"isset() will return FALSE if testing a variable that has been set to NULL"** ([php.net/isset](http://php.net/isset)). This means that in *some* cases, like checking for a GET or POST parameter, using isset() is enough to tell ...
``` if ($tx) ``` This code will evaluate to false for **any** of the following conditions: ``` unset($tx); // not set, will also produce E_WARNING $tx = null; $tx = 0; $tx = '0'; $tx = false; $tx = array(); ``` The code below will only evaluate to false under the following conditions: ``` if (isset($tx)) // False ...
Weak typing in PHP: why use isset at all?
[ "", "php", "syntax", "" ]
Simple idea: I have two images that I want to merge, one is 500x500 that is transparent in the middle the other one is 150x150. Basic idea is this: Create an empty canvas that is 500x500, position the 150x150 image in the middle of the empty canvas and then copy the 500x500 image over so that the transparent middle of...
basically i use this in one of our apps: we want to overlay a playicon over a frame of a video: ``` Image playbutton; try { playbutton = Image.FromFile(/*somekindofpath*/); } catch (Exception ex) { return; } Image frame; try { frame = Image.FromFile(/*somekindofpath*/); } catch (Exception ex) { return...
This will add an image to another. ``` using (Graphics grfx = Graphics.FromImage(image)) { grfx.DrawImage(newImage, x, y) } ``` Graphics is in the namespace `System.Drawing`
Merging two images in C#/.NET
[ "", "c#", ".net", "image", "" ]
A while back, online apps used to say, "do not click submit more than once." That's gone now, right? How do you guard against that in, say, PHP? One solution I'm using involves putting a variable in the Session, so you cannot submit to a page more than once every 10 seconds. That way the database work will have comple...
You should do both client- and server-side protections. **Client side** - disable button e.g. by jquery as cletus has described. **Server side** - put a token in the form. If there are two submissions with the same token, ignore the latter. Using this approach, you are protected against [CSRF](http://en.wikipedia.org...
This is an excellent example of what jQuery is useful for (you can do it in any Javascript though). Add this code: ``` $("form").submit(function() { $(":submit",this).attr("disabled", "disabled"); }); ``` And it disables submit buttons once clicked once.
Avoid Race Conditions in PHP on Submit: Please do not click submit more than once!
[ "", "php", "" ]
Due to lack of capital and time we are having to do our game in 2D even though me (the developer) would prefer if it was done in 3D. I would hate for users to join the game, only to think the graphics look bad and leave. Though I suppose we just have to try and do our best. That being said, I would like to develop the...
> Due to lack of capital and time we are > having to do our game in 2D even > though me (the developer) would prefer > if it was done in 3D. I would hate for > users to join the game, only to think > the graphics look bad and leave. > Though I suppose we just have to try > and do our best. I don't think everything has...
The simplest way to achieve this is to write the game in 3D, and render the views using a 3d to 2d projection, e.g. in plan or elevation. If the games internal mechanics are 2D and you try to move to a true 3d frame, you would probably better off with a rewrite. It also depends to an extent on what you mean by 3D, and ...
Porting easily from 2D to 3D on a Java game
[ "", "java", "3d", "2d", "" ]
``` Response.Redirect(string.Format("myprofile.aspx?uid={0}&result=saved#main",user.UserID)); ``` said code translates to **IE7** - `myprofile.aspx?uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved` **FF**- `myprofile.aspx?uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved#main` why does IE7 drop my anchor? ...
It would be quite the hack, but if IE isn't behaving, you could do this. pass a param as well, e.g. ``` uid=933fdf8e-1be0-4bc2-a269-ac0b01ba4755&result=saved&hash=main#main ``` Then on your page (before the body close tag, or as an onload event), only for IE, extract the parameter if present and set the hash manuall...
Maybe it is a regression issue from IE6? Did you try [working around it](http://blogs.vertigo.com/personal/tomphan/Blog/Lists/Posts/Post.aspx?ID=6) by prepending it with an &?
Response.Redirect with # anchor, does not work in IE7
[ "", "c#", "asp.net", "jquery-ui", "internet-explorer-7", "jquery-ui-tabs", "" ]
I am tying to make comments in a blog engine XSS-safe. Tried a lot of different approaches but find it very difficult. When I am displaying the comments I am first using [Microsoft AntiXss 3.0](http://www.codeplex.com/AntiXSS) to html encode the whole thing. Then I am trying to html decode the safe tags using a whitel...
Your problem is that C# is missinterpretating your regexp. You need to escape the #-sign. Without the escape it matches too much. ``` private static Regex _whitelist = new Regex(@" ^&\#60;(&\#47;)? (a|b(lockquote)?|code|em|h(1|2|3)|i|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)&\#62;$ |^&\#60;(b|h)r\s?(&\#47;)?&\#62...
Have you considered using Markdown or VBCode or some similar approaches for the users to mark their comments up with? Then you can disallow all HTML. If you must allow HTML then I would consider using a HTML parser (in the spirit of HTMLTidy) and do the white-listing there.
Sanitize html encoded text (#decimal notation) from AntiXSS v3 output
[ "", "c#", "html", "regex", "xss", "" ]
The following code prints 20, i.e. sizeof(z) is 20. ``` #include <iostream.h> class Base { public: int a; }; class X:virtual public Base { public: int x; }; class Y:virtual public Base { public: int y; }; class Z:public X,public Y { }; int main() { Z z; cout <<...
Let's look at the class layout of the two cases. Without the virtual, you have two base classes ("X" and "Y") with an integer each, and each of those classes have integrated into them a "Base" base class which also has an integer. That is 4 integers, 32-bits each, totalling your 16 bytes. ``` Offset Size Type Scop...
Mark Santesson's answer is pretty much on the money, but the assertation that there are no vtables is incorrect. You can use g++ -fdump-class-hierarchy to show what's going on. Here's the no virtuals case: ``` Class Base size=4 align=4 base size=4 base align=4 Base (0x19a8400) 0 Class X size=8 align=4 bas...
Question on multiple inheritance, virtual base classes, and object size in C++
[ "", "c++", "multiple-inheritance", "sizeof", "" ]
I wonder if this is even possible. I have an application that adds a context menu when you right click a file. It all works fine but here is what I'd like to do: If the file is a PSD then I want the program to extract the image. Is this possible to do without having Photoshop installed? Basically I want the user to r...
For people who are reading this now: the link from accepted answer doesn't seem to work anymore (at least for me). Would add a comment there, but not allowed to comment yet - hence I'm adding a new answer. The working link where you can find the psdplugin code for Paint.Net: <https://github.com/PsdPlugin/PsdPlugin>
The [ImageMagick](http://www.imagemagick.org) libraries (which provide [bindings for C#](http://midimick.com/magicknet/)) also support the PSD format. They might be easier to get started with than getting into the Paint.NET code and also come with a quite free (BSD-like) license. A simple sample (found at [http://midi...
Reading PSD file format
[ "", "c#", "photoshop", "file-format", "" ]
I have the following SQL Statement. I need to select the latest record for each System.Id using the System.RevisedDate ``` SELECT [System.Id],[System.RevisedDate], [System.Title], [System.State], [System.Reason], [System.CreatedDate], [System.WorkItemType], [System.TeamProject], [Microsoft.V...
Try this: ``` SELECT * FROM WorkItems w JOIN ( SELECT [System.Id],MAX([System.RevisedDate]) FROM WorkItems WHERE ([System.WorkItemType] = 'Change Request') AND ([System.CreatedDate] >= '09/30/2008') AND ([System.TeamProject] NOT LIKE '%Deleted%') AND ([System.TeamProject] NOT LIKE '%Sandbox%') GROUP BY {System....
In general it should go some thing like ``` SELECT ID,DATE_FIELD,FIELD1,FIELD2 FROM TBL1 AS A WHERE DATE_FIELD >= ALL ( SELECT DATE_FIELD FROM TBL1 AS B WHERE A.ID = B.ID ) ```
SQL Distinct by ID and Latest By Date
[ "", "sql", "tfs", "reporting-services", "" ]